Android Tutorial : Custom adapter for ListView to create bubble shaped list rows


Hi.
I am seeing many people interested in writing their own adapters for various reasons. the primary reason being their need to implement their custom layouts in the rows.
In this tutorial, I am going to explain how you can set custom layouts to your lists and their rows.
Although, here's an in-depth article (An excerpt from his awesome book) about custom adapters from the great book of 'CommonsGuy' Mark Murphy at his website, but this tutorial is a quick way of doing that.

For this example, I have created a ListView which has a custom background, and custom rows representing a conversation in bubble format.

Here's the screenshot to make things clear:



Find the whole source code at this link.

The whole concept works like this-
  • You create two layouts:
    • One for Even rows
    • One for Odd rows
  • These layouts are designed keeping in mind that they'll be used as layouts of a row.
  • Your code has an array containing the data that will be displayed in the list view.
  • Inside your code, write a simple class extending BaseAdapter.
    • In this class we implement following methods of Android.Widget.Adapter super class, in order to get things working:
      • getCount() - returns the total number of elements in your data array
      • getIterm() - returns the data item associated with the specified position in the data set. Not implemented at this point.
      • getItemId() - returns the row id associated with the specified position in the list. Not implemented at this point.
      • getView() - returns the row that has to be drawn. This is the method we're interested in the most. It will be called every time the ListView draws a new row.
        Here, you can control what gets drawn in a particular row, by selecting a layout and setting data into it.
        In our example, we are checking whether the position of the row is even or odd, and according to that, we are setting the row's layout.
  • I have also set a background to the layout which holds the list.
  • A list has a transparent background in normal conditions which makes you see the image that you set as the layout background, but when the List is scrolled, it doesn't remain transparent any more.
  • If you want you background image to be visible while scrolling too, set cacheColorHint of your ListView.

Refer to the project for more, and revert for feedback.

Download the source code here.
Happy Coding!

Show Splash Screen for fixed amount of time in Android Apps


You'll be into situations where you have to present a user with a splash screen that stays for sometime and then loads the main application and goes away.

This post demonstrates a code that displays a splash screen for a fixed amount of time and then loads the main screen.

This code isn't for the situation where you have to display a splash screen until you finish doing some work or load data from the web.
It will be covered in a different post.

Read the code, and understand the things from the comments

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;
import android.view.WindowManager;

public class SplashScreen extends Activity {

private final int DISPLAY_LENGTH = 1000;

/** Called when the activity is first created. */

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splash_screen);

/* New Handler to start the Menu-Activity
* and close this Splash-Screen after DISPLAY_LENGTH/1000 seconds.*/
new Handler().postDelayed(new Runnable(){

@Override
public void run() {
/* Create an Intent that will start the Main-Activity. */
Intent mainIntent = new Intent(SplashScreen.this,Main.class);
SplashScreen.this.startActivity(mainIntent);
SplashScreen.this.finish();
}}, DISPLAY_LENGTH);
}
}

Android OS Source Code Modification (Part-II): Making the System

Considering that you have followed all the instructions in my previous post here, I take this series of post forward which illustrates how to compile the source code in order to get it running in an emulator.

Building Android 2.2 source to run an Emulator

The main reason for first doing this instead of illustrating the modification of source is that, you should know what steps you have to perform in order to see the changes that you have made.
Secondly, you must be aware of outcomes of your modification.
Third, You must know what your objective is, then you'll be able to work more precisely, for example, you now know that you have to run your modifications in an emulator, so you'll see the screens, change them, make the build and will again run the emulator to see the changes.
Moreover, I feel that it will help you understand what actually happens when we build for a system, as a result, you'll be able to make changes more comfortably, and without working vaguely .

So, I have just ended up creating an emulator, and there's really nothing big involved in this.

To start the compiling/building/making process, we just use the make command.
And to make it deliver an emulator, we use the sdk switch with make command.
This is done in the following manner:

In a shell prompt, first go to the directory where your files are (probably under 'bin' or 'mydroid') or you can also set the $PATH to have any of these folders in your path, then run:

$ make sdk

The above lines will compile the source and will generate an sdk folder under your root directory (most probably this root directory will be 'bin')
If your build fails due to a missing run-java-tool then run the following command to simple set your environment variable ANDROID_JAVA_HOME:

$ export ANDROID_JAVA_HOME=$JAVA_HOME

Then again start the build process with the make sdk

Now wait for a long time, as it is going to take long for it to compile the code.
on my machine, it took 5 hours.

When it finishes, you should be able to find one sdk folder under following directories:

~/bin/out/host/[OS build]/sdk

in my case, the [OS build] folder was linux-x86, so just replace it with yours.
under normal circumstances, it should be yours too.

This folder will have the emulator which you can run.
This emulator can be found in:

~/bin/out/host/[OS build]/sdk/[sdk version dependant folder]/tools 

here [OS build] was linux-x86 on my system
and [sdk version dependant folder] was android-sdk_eng.root_linux-x86.

To run the emulator that you have just built, you'll run the emulator command from a terminal, but before that, you must have an AVD to run the emulator.

So,to create an AVD, run the following commands under a terminal

$ cd /bin/out/host/[OS build]/sdk/[sdk version dependant folder]/tools
$ ./android create avd -n [Your AVD's name] -t 1 

here [Your AVD's name] is whatever you want your AVD to be named like

As a result, you might get something like this-

Android AOSP (Preview) is a basic Android platform.
Do you wish to create a custom hardware profile [no]no
Created AVD '[Your AVD's name]' based on Android AOSP (Preview),
with the following hardware config:
hw.lcd.density=160

Now, to run the emulator with this AVD, run the following command:


~/bin/out/host/linux-x86/sdk/android-sdk_eng.root_linux-x86/tools$ ./emulator @[Your AVD's name]

You should get your Emulator running.

In the next post, I might show how to make changes in few things of the source, and how to build an emulator to see those changes.

Enjoy!

Android OS Source Code Modification: Getting Started with Android Source Code modification

I have just started playing with Android OS Source and I can assure you, it can be a real pain for some people, so be prepared.

For all the downloading and documentation needs, you can go to: source.android.com

We'll be using one key command , repo, to download the OS from the Git repository.
be patient and read the full article, it will explain all.

First of all, you can't play with it on your beloved Windows (to be specific, Android 2.2 Source Code development doesn't support Windows) . you'll have to get a Linux (preferably Ubuntu, as they've used Ubuntu) to work with the source of Android 2.2.

Second, Not all the things written in the documentation are correct. I cam across many anomalies in the documentation, sometimes total contradictions too, so I'll be discussing the real details too.

To download the source code, you'll have to go to this link to get the instructions (While I am also giving them here) -> http://source.android.com/source/index.html

Steps to setup developer machine:
  1. You should have a Mac or Ubuntu machine, as Windows is not yet supported. Now here's the catch, the documentation says they haven't tested 64 bit versions of Ubuntu and prefer to have feedbacks, but the reality is, if you are going to work with Android 2.2 or higher, you wouldn't be able to build your source if you aren't running a 64 bit version. so better get the 64 bit version of Ubuntu and follow the steps ahead. and please, do get a hi end system with at least 3 GB of RAM, good 64-bit processor-motherboard and nice HDD space, as while development and building, Android OS becomes a monster in every aspect.

  2. As soon as you finish setting up your Ubuntu 64, you'll have to setup some more things. use this command to get them:

    $ sudo apt-get install git-core gnupg flex bison gperf build-essential zip curl sun-java5-jdk zlib1g-dev  gcc-multilib g++-multilib libc6-dev-i386 lib32ncurses5-dev ia32-libs x11proto-core-dev libx11-dev lib32readline5-dev lib32z-dev

    Notice here, there are a lot of packages being installed, but perhaps you won't be able to install sun-java5-jdk  as its not available in Ubuntu repository. You'll have to install it via Sun's website. AND it will also not be supported, as Android 2.2 will require Java6. don't go by the documentation for this. this is why i have written it in strike-through.

  3. Now, install Java6. to ask how this will be done, ask me separately or google for it, as this article isn't about it.

  4. Repo & Git: Repo is a client that fetches the source of Android OS from the git repository. Google guys maintain the code of Android on git, and its updated frequently, so now you'll have to setup repo and fetch the source code.
 Configuring Repo:
  1. To download repo, you'll have to follow some easy steps, follow these lines:
    
    $ cd ~
    $ mkdir bin 
    $ echo $PATH 

    The last line checks if ~/bin is in your path.
    Now to download repo:

    
    $ curl http://android.git.kernel.org/repo >~/bin/repo
    $ chmod a+x ~/bin/repo

    This will download the repo script and will make it executable.

  2. now the next step is to fetch the whole Android code. hold your breath, its of about 2.1 GB, and will take a LONG time! run this command:

    $ ./repo init -u git://android.git.kernel.org/platform/manifest.git

    Notice that the documentation doesn't include a './' before repo in this command, but you'll have to include it in order to run it. this will download the manifest and will set the repo client up, so that when you sync, it downloads the correct thing. It will ask for your name and email, so give it. better if its a Google account, it can be used to submit back the code. The next command will start download:

    $ ./repo sync

    this command will start syncing your current directory (that is ~/bin) with the Android 2.2 git repository. As this process is going to take time, you can go out for a walk or a game.

  3. Every time you run the syncing, it will sync your base code with the code available in the repository, so possible upgrades will happen. It will be good if you follow a good backup policy.

  4. When you're back, the Android OS might have got downloaded by then, and you can begin experimentation with it.

That's it for now. In my next post I'll explain how to setup Eclipse for Android Source modification and how to build the whole OS.

Till then, take care.
and, I love your comments, so go ahead!

    What is Outsourcing

    A lot of might have heard the term and might also have related it with only one thing BPO == Call Center.
    Where you get paid to chat with people and often to get abused by them.
    but this is not the only thing outsourcing means.

    This article is intended for students, who are either stepping into the technological industry or are planning to.
    I am not addressing the ones who are already educated.

    If you look at the word 'Outsourcing' closely, you'll find its 'Out-Sourcing'. Meaning getting something done whose source is outside of your perimeter, or simply say, country. BPO stand for Business Process Outsourcing, and is a business where one country/company asks another to do a work for it, making the services  come from the outside of the company.
    That service, or say Business Process, can be anything, ranging from customer service, manufacturing, distribution and more. In the case of customer service, the call center example fits very well, where a company asks another company to serve its customer.

    Software development in India is also outsourcing, at least mainly.
    One of the biggest company TCS is also the biggest technological exporter of the country, meaning the biggest outsourcing company.
    Because these companies work for the clients/companies who are situated in the US/UK and other places.
    It is very likely that if you're hired by many of the biggies, you're also involved in outsourcing.

    Now, the question is, Why do the international companies want other companies to work for them?
    Simple because they get cheap labor in developing countries as compared to their own.
    for example, If we take the scenario of US, per capita income of an average US citizen is quite high as compared to an Indian citizen.
    So if a company, that is situated in the US, hires an American for the job, it will end up paying more to him, than hiring an Indian, in India.
    The work done by both of the people is almost same, but cost is reduced as the US company pays for almost two indians in the same cost it would have been paying an american.

    The final software product, or all the communication involved in developing it, is done via the internet, and since internet bandwidth is not a problem with developed countries, they find it almost negligible as a cost factor.

    Now, The Fear Factor..
    This scenario made most of the US companies ask indian companies to do their work, for they'll have to pay less and earn more. This situation made india gain in various aspects: we got more dollars in our country, we got more people employed. but it almost created a problem over there in the US. companies were now not willing to hire americans to save the cost. and un-employment of skilled US personnel increased. This ended up in rage among the US people and a negative social impact.
    as a result, to correct this, the current US president Barack Obama has strong changes in US policies in his mind, and is being seen as a president not acting very helpful to outsourcing.

    Why You should know it..
    Simply, you'll be in the business involving this, so you should be knowing this.
    if outsourcing fails (which really can, as China is leading in it now, beating India), you should have proper plans in mind to tackle it.
    Either work for companies, which are product oriented
    Or work for companies, who don't outsource, they just do their work .
    It's totally up to you.

    I hope it would have helped you in any manner.

    Thoughts expressed here are totally mine, neither copied, nor influenced

    Approaching till the end of your studies.. Now what?

    This article is meant for Indian Engineering students (BTech, BE, BCA, MCA).
    And since it has involved my precious time, I suppose you read all of it and comment on it if you like/dislike it. :-)

    It is understood that you’re about to enter your final semester which includes, of course, industrial training. Some students, in fact many students, would find it a tough time because they can’t efficiently decide what to go for. I am not saying this for no reason, I have been a student lately, and am interacting with many of them currently, I have realized this very thing. This article is here to help you if you’re one of those people.
    First thing first, get this straight, you spent almost all of the time in college cursing the lecturers, bunking classes and labs, hanging out with friends, girlfriends/boyfriends and doing some un necessary stuff. No problem in doing that, in fact that’s important, because honestly, you’re not going to have this time back in your life again. Well, not every student might not have done so.

    But during all this, you perhaps didn’t do what was required: building yourself for the industry.
    Students tend to rely on the training and placement cells in their colleges and universities, but be aware that they DON’T guarantee your selection in any company. After all, the coming companies will be interviewing you, and if they don’t find you good enough, they’ll reject you.

    You were required to find out what you’re made of and what you’re made for. If you were not forced to jump into engineering because it was a hot trend at your time to be an engineer, then you might be having passion for it, you might be having at least some element that make you fit for engineering. So, You:

    1. MUST find out what was/is that element.
    2. Once you find out, you MUST find where in the engineering scenario, you fit with your virtue.
    Remember fellas, it is very important that you try to fit into a correct place. Since I am from Computer Engineering, I know that we are indirectly forced to be programmers. I was one, luckily, so I made it, but its not the case with everyone. Someone might like graphic designing, Database Management/Development, Networking, maintenance, testing and many more. You need to realize what you are and hone those skills in you. Then when it’s the right time, go for the hunt.

    So, when is the right time for you to start? For this, first know some things about the market. Many students go for trainings. Now if there are any misconceptions about training, then let me clarify:

    • One training is where you go into a company, which is more like an institute, you pay something to them, in lieu of that, they’ll be teaching you stuff that industry needs, in classes, and will make you work on a project, which you’ll submit in your college as your project.
    • Another training is when company, a real one, takes you in as a trainee, feeds you a li’l bit time to time and puts you to work on your own. You work as an assistant on several projects and at last, you get one to take home and submit. AND, the best part is, they pay
    Now, the first kinda training is not for the people who already are skilled enough to work directly. Imagine, why you should pay for something that your lecturers should have been doing in your college, all over again!?? Of course the trainers at these institutes are suave, but that’s not the need of the hour.The project that you get in these institutes is not a live one, well its only live on the paper, but you never get to know who the client really was and whether your project really made to the market. There may be exceptions but I am talking about the most of the cases.

    In the second type of training, which is normally called internship, you’re interviewed (Yes, eve when you’re in your final semester) and if you suit for the position, you’re taken by them. They’ll tell you in brief about how they work, and will put you to REAL grounds, and you’ll be developing projects for real clients that will be really live and will be going to the market.

    They employ you for the full working day, instead of few hours, like the first ones, take the juice out of you, make you rug your asses like anything, and at the end of the day, you come out abusing your life. But believe me, that’s exactly what will make you shine. You get to know how things are done really, how to handle pressure, stress and more importantly, you get a taste about how its going to be.
    And at the end of month, you get paid!

    The companies in the market know very well how colleges and these institutes work.
    When you show them the certificate of experience, there will be differences in a normal trained person and any intern. Your employer will be knowing very well about which company works which way, and knows that in today’s work, you just don’t work on only ONE project for the period of 6 months or so. So when you’re an intern, you have experience of multiple technologies and multiple projects, that’s the REAL experience that counts.

    It is clear that I am advocating the second type of training, internship actually, and am discouraging the first ones.

    Now I know that Institutes can sue me for this, but these are my personal views for you guys.

    Now, get back to how you know that you’re for the second type of training.

    1. Have you taken interest in several technologies of your domain?
    2. Have you ever developed something on your own?
    3. And that thing can be presented to anyone as a whole?
    4. Do you consider yourself as the person who can really do something with the knowledge you currently posses?
    5. Are you courageous to be facing challenges and passing through them?
    6. Have you, during the whole course of your studies, done many developments related to your technology and domain, that were not directly related to your studies?

    If answers to the above questions is yes, then please try to get interviewed by as many companies as possible and try to crack the nut as early as possible.

    If not, then please enroll in any of the institutes like the ones I stated above, and learn the real thing. What, its not a problem or inferiority. You don’t know things, and you’re willing to learn them, its good!
    Just keep in mind that what you didn’t do in the whole course of your studies, you can do it now: expand your skills and sharp your talent.

    The best time for applying for internships is October-November, because if you start applying at this time, there are chances that you’ll start getting calls/emails by November last, perhaps your interviews will start in starting of December, and perhaps till the end of December, you’ll crack some of them, and by the first or second week of January, you’ll be finalizing the things with any company and will be going to them.
    The best time for applying to institutes is: anytime.

    So, if you’re interested in internship, here’s a website which can help you in spotting offers made by several companies in several domains, and in several part of the country:
    www.10internship.in

    Never hesitate to go out of the way to learn things, never be afraid of going to any place which you haven’t visited before, to get things done, because this is the time when you can learn from life experiences, and this is the only time when you’re supposed to be digging it hard. If not now, then when?

    Wait for my other post related to this matter, and if you have any complaints/suggestions you can freely comment here, I know you guys would be having at least one google ID used for orkut ;-)
    And yes, if you liked it, then also you can comment, and please, spread the word.

    Guide: How to set up Android SDK on Linux machines

    I know many of you have already done this before, but I also believe that there will be a lot who will gain from this document.

    Here is a 6 page Google doc in PDF format, which teaches you how to install Android SDK on your Linux machine, set it up and even makes you build your first project on it.

    I hope you'll find it useful.
    Find the document here: http://bit.ly/cQJJKE

    Feel free to download, and in case of any correction, complaint, modification request, you always have comments area here on blogspot :)

    MySql :: How to convert UNIX_TIMESTAMP data into DATE data in queries

    There might be situations where you would want to convert a data stored in UNIX_TIMESTAMP format (may be by your code or else) to human readable DATE format of mysql, then just run this query-
    SELECT FROM_UNIXTIME(time_stamp_fieldname) as any_ FROM table;

    and see the results in a new table format, every record's timestamp data will be changed in Date data.
    try it.
    n
    enjoy!
    :-)

    How to import data into MySql Database table from a CSV file

    Whenever I have to fill a table with data in CSV file, I do this-

    1.) Log in to your mysql console
        mysql -u root -p

    2.) Make sure you have a database set up. now select that database
       mysql> use mydatabase;

    3.) Create the table where you'll be inserting the data of CSV. now here, make sure that the table has the same column names ordering as they appear in the CSV file, because mysql puts all data as it encounters it. means in the same order. so if u break the order, then ur table may have fields with irrelevant data.

    4.) Now fire this command to actually load the data from CSV into table-
         mysql>load data local infile 'c:/path/to ur/ file/filename.csv' into table yourTableName fields terminated by ',' enclosed by ' " ' lines terminated by '\n'


    This should do all.
    Any confusions?
    ask me.
    comment/compliment here.

    Apache Access log mods : Redirecting logs to a MySql Database

    Purpose

    There are times when you require that your Apache server logs the request made to it, in a customized location. In my case, i wanted it to log all the incoming requests in a MySql database, so i made some experiments based on the things told by many people and yes, finally i got it. Read the full article for more details. I have tried to keep this article as short as possible, still have tried to make it understandable.

    Objective

    Redirect all the output to a user defined database (here MySql database) which is logged in "access.log" file by default.

    Testing System Configuration

    The test machine was running Ubuntu 9.10 with Apache2 and MySql5.

    Requirements

    1.) For this example, you'll need-
    mod_log_sql
    2.) Second thing,you'll need to define a database that will hold the table having access logs. I'll show you how.
    3.) Lastly, what you need, is a modification to the default configuration file of Apache. I'll show you how to do it.

    How Things Are Done : Step by Step


    Step1: Installing mod_log_sql

    If you don't have this installed by default, which i didnt have, use these procedures to get it installed
    Open a terminal, and type-
    sudo apt-get install libapache-mod-log-sql-mysql
    
    this will install mod_log_sql.we need this in order to get things done.
    now restart the apache server-
    sudo /etc/init.d/apache2 reload
    

    Step2: MySql part

    you can use database creation from phpMyadmin as well, but i prefer using terminal, since so many things will be done using only terminal.
    So open a terminal, type-
    mysql -u root -p
    
    and give your root password.
    Now we'll create a user called "loguser" which will be updating tables, and we are going to grant CREATE, INSERT permissions to this user, sinse this user will be doing these things. Fire this command-
    grant insert,create on apachelogs.* to loguser@localhost identified by 'loguser_password';
    grant insert,create on apachelogs.* to loguser@localhost.localdomain identified by 'loguser_password';
    FLUSH PRIVILEGES;
    
    where 'loguser_password' can be anything that you like the password to be.

    Step3: Apache part

    Do the following things to create a virtual host of apache, a new virtual host actually.
    This involves creating a separate default config file.
    So first, we backup our own default config file.
    Fire these commands-

    Backing up old config file

    sudo mv /etc/apache2/sites-available/default /etc/apache2/sites-available/default_orig
    
    We renamed our old file to default-orig'

    Creating new config file

    Open a new file-
    sudo gedit /etc/apache2/sites-available/default
    
    After this, paste the following text in it-
    LogSQLLoginInfo mysql://loguser:loguser_password@localhost/apachelogs
    LogSQLCreateTables on
    LogSQLDBParam socketfile /var/run/mysqld/mysqld.sock
    LogSQLTransferLogFormat AbHhmRSsTUuvI
    
    NameVirtualHost *
    <VirtualHost *>
    ServerAdmin webmaster@localhost
    
    DocumentRoot /var/www/web1/web/
    <Directory /var/www/web1/web/>
    Options Indexes MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
    </Directory>
    
    LogSQLTransferLogTable web1_access_log
    </VirtualHost> 
     
    Update: I noticed, that if you edit your default config file and put these lines in it in the way that it doesn't create a problem, 
    then you'll end up with apache logging on two places: one is the default log file, and the second will be your MySql database.
    Cool, isn't it? 
     
    after doing this, restart your apache-

    sudo /etc/init.d/apache2 reload 
     
    After this, make some requests to apache, and open the particular database that you had created, to see the changes.
    We're done!

    Conclusion/Known Issues

    Well, there are some things you should be careful about-
    1.) You'll end up creating a NEW virtual host, so any settings particular to the old virtual host, may not work
    2.) I got several warnings, which meant that apache couldn't map the name localhost to the ip 127.0.0.1, so it used the real ip. means, i couldn't use localhost in my URL anymore.
    3.) You should have root permissions to perform most of the things, so i prefixed a sudo before commands.
    4.) This thing may not be suitable if your database isn't dedicated to the sole task you want this feature to work for, So if you want logging to be done in a file too, then try another methods available on the Internet.
    Update: I devised another method. please look at the update of step3 Creating New Config File

    For more information, you can refer to this page at How to Forge. But this article is optimized for Ubuntu, while How to Forge article focuses on Debian Etch Linux.
    Happy moding!