Working with SQLite on Android

From last few month, I was not able to post any new topic. So today thought to post something, but what? Then I remembered how much I had broken my head to start with the SQLite in android.

I had found few difficulties while learning because of:

  • All the database operation must has done from code only
  • Reading the data from database using ADB sell was difficult
  • If I am debugging from mobile, the data base is not accessible only

Later I manage to learn it and build a sample Application before I had to start my project. Here I am going to explain the same project which will insert record and display records in the same interface. It may be helpful for my readers.

Fig : Package Explorer of the example project

Here first step is to create a class that inherits from SQLiteOpenHelper class. This class provides three methods  two methods to override and one constructor of super class :

  • onCreate(SQLiteDatabase db): invoked when the database is created, this is where we can create tables and columns to them, create views or triggers.
  • onUpgrade(SQLiteDatabse db, int oldVersion, int newVersion): invoked when we make a modification to the database such as altering, dropping , creating new tables.
  • DatabaseHelper(Context context) : invokes to create database by providing the target context with database name and schema version.

 (It is better to put the entire database, tables and fields name in static variable so that writing code will be easier)

package com.student;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {
static final String db_demo = "db_demo";
static final String tbl_student = "tbl_student";

static String name = "name";
static String t1 = "test1";
static String t2 = "test2";
static String t3 = "test3";

// method to create or connect to a database
public DatabaseHelper(Context context) {
super(context, db_demo, null, 2);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + tbl_student + "(id  INTEGER PRIMARY KEY, "
+ "name TEXT, " + t1 + " INTEGER, " + t2 + " INTEGER, " + t3
+ " INTEGER);");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
android.util.Log.v("Constatnts :",
"Upgrading Data, Which Will Destroy All Old Data");
db.execSQL("DROP TABLE IF EXISTS  " + tbl_student);
onCreate(db);
}

}

So, here is the class which will take care of creating database, tables and upgrading the database.

Then we will create an Interface where we will write the code for insertion of the data into the table and selecting the data from same table.

The selected data I have displayed into the list view, as I have shown in one of my previous post.

package com.student;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity implements OnClickListener {
EditText et_name, et_t1, et_t2, et_t3;
Button btn_save;
ListView listView;
String name, t1, t2, t3;

List<String> list_name = new ArrayList<String>();
List<Integer> list_t1 = new ArrayList<Integer>();
List<Integer> list_t2 = new ArrayList<Integer>();
List<Integer> list_t3 = new ArrayList<Integer>();
static String[] arr_name;
static Integer[] arr_t1;
static Integer[] arr_t2;
static Integer[] arr_t3;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

et_name = (EditText) findViewById(R.id.et_name);
et_t1 = (EditText) findViewById(R.id.et_t1);
et_t2 = (EditText) findViewById(R.id.et_t2);
et_t3 = (EditText) findViewById(R.id.et_t3);
btn_save = (Button) findViewById(R.id.btn_save);
btn_save.setOnClickListener(this);

//deleteDatabase();
readDBdata();
listView = (ListView) findViewById(R.id.lv_Marks);
listView.setAdapter(new EfficientAdapter(this));

}

@Override
public void onClick(View v) {

if (v == btn_save) {
if (et_name.length() <= 0 || et_t1.length() <= 0
|| et_t2.length() <= 0 || et_t3.length() <= 0) {
Toast.makeText(this, "Please fill each field",
Toast.LENGTH_SHORT).show();
return;
}
name = et_name.getText().toString();
t1 = et_t1.getText().toString();
t2 = et_t2.getText().toString();
t3 = et_t3.getText().toString();

DatabaseHelper dbh = new DatabaseHelper(this);
SQLiteDatabase db = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(dbh.name, name);
cv.put(dbh.t1, t1);
cv.put(dbh.t2, t2);
cv.put(dbh.t3, t3);
try {
// db.insert(dbh.tbl_student, null, cv); or
db.insertOrThrow(dbh.tbl_student, null, cv);
} catch (Exception ex) {
Toast.makeText(this,
"Sorry data can't be saved. error:" + ex.toString(),
Toast.LENGTH_SHORT).show();
} finally {
db.close();
}
Toast.makeText(this, "Data has been saved.", Toast.LENGTH_SHORT)
.show();
readDBdata();
listView.setAdapter(new EfficientAdapter(this));
}
}

public void readDBdata() {
DatabaseHelper dbh = new DatabaseHelper(this);
SQLiteDatabase db = dbh.getWritableDatabase();
list_name.clear();
list_t1.clear();
list_t2.clear();
list_t3.clear();
Cursor cursor = db.rawQuery("Select " + dbh.name + "," + dbh.t1 + ","
+ dbh.t2 + "," + dbh.t3 + " from tbl_student;", null);

if (cursor.moveToFirst()) {
do {
list_name.add(cursor.getString(0));
list_t1.add(cursor.getInt(1));
list_t2.add(cursor.getInt(2));
list_t3.add(cursor.getInt(3));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
db.close();
arr_name = new String[list_name.size()];
arr_t1 = new Integer[list_t1.size()];
arr_t2 = new Integer[list_t2.size()];
arr_t3 = new Integer[list_t3.size()];

for (int i = 0; i < list_name.size(); i++) {
arr_name[i] = list_name.get(i);
arr_t1[i] = list_t1.get(i);
arr_t2[i] = list_t2.get(i);
arr_t3[i] = list_t3.get(i);
}
// Toast.makeText(this, list_t3.toString(), Toast.LENGTH_SHORT).show();
}

private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;

public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}

public int getCount() {
return arr_name.length;
}

public Object getItem(int position) {
return position;
}

public long getItemId(int position) {
return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.three_col_row, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.TextView01);
holder.text2 = (TextView) convertView
.findViewById(R.id.TextView02);
holder.text3 = (TextView) convertView
.findViewById(R.id.TextView03);

convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}

holder.text1.setText(arr_name[position]);
holder.text2.setText(String.valueOf(arr_t1[position] + ", "
+ arr_t2[position] + ", " + arr_t3[position]));
holder.text3.setText(String.valueOf(((arr_t1[position]
+ arr_t2[position] + arr_t3[position]) / 3)));

return convertView;
}

static class ViewHolder {
TextView text1;
TextView text2;
TextView text3;
}
}
public void deleteDatabase() {
DatabaseHelper dbh = new DatabaseHelper(this);
SQLiteDatabase SQLDb = dbh.getWritableDatabase();
dbh.close();
SQLDb.close();
if (this.deleteDatabase(dbh.db_demo)) {
Log.d("Droped", "deleteDatabase(): database deleted.");
} else {
Log.d("Cant Drop", "deleteDatabase(): database NOT deleted.");
}
}
}

Fig: Output for the project

This is not the end of the project execution. After developing the SQlite project in android, running the application successfully is one another challenging job.

While running executing the application we should always check the log for the possible errors and exceptions.

To check the data in the database, we have to go through some few steps

Find the location of the database from Windows > Show View > Other > Android  > File Explorer

You can find database in,

data>data>com.<project name>.databases>your database

Now we have to use access same location from the ADB shell

To access database data base, go to command prompt and change location to platform-tools inside android-sdk .

Then execute the “adb shell” command and give the location to your database

“sqlite3 /data/data/com.<project_name>/databases/<database_name>”

Now you are into your database, you can execute the SQlite query for the database.

(Note: we can view the database only if we are executing the application in emulator, while executing in mobile viewing the database permission will not be there.)

Retrieving records from Database in Hibernate

In my previous post I have used example for the insertion of data in Hibernate. Here is another example for selecting the records from the database using hibernate. In the same project (from previous post), I have added this new class named UsersList.java and ShowUser.java without making any other changed.

package ps.com;
//UsersList.java
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;

import java.util.Iterator;
import java.util.List;

public class UsersList {
	public static void main(String[] args) {
		Session sess = null;
		try {
			SessionFactory sfact = new Configuration().configure().buildSessionFactory();
			sess = sfact.openSession();
			Criteria crit = sess.createCriteria(User.class);
			ProjectionList proList = Projections.projectionList();

			proList.add(Projections.property("u_name"));
			proList.add(Projections.property("u_password"));
			crit.setProjection(proList);
			List list = crit.list();
			Iterator it = list.iterator();
			if (!it.hasNext()) {
				System.out.println("Data does not exist");
			} else {
				System.out.println("User Name\t\tPassword");
				System.out.println("----------------------------------");
				while (it.hasNext()) {
					Object[] row = (Object[]) it.next();
					for (int i = 0; i < row.length; i++) {
						System.out.print(row[i] +"\t\t\t");

					}
					System.out.println();
				}
			}
			sess.close();
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("Error :" + e.getMessage());
		}
	}
}

Output :

Most of the time we need to select single row with condition, which can be achieved from this piece of code.

package ps.com;
//ShowUser.java
import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;

public class ShowUser {
	public static void main(String[] args) {
		Session sess = null;
		try {
			SessionFactory sfact = new Configuration().configure()
					.buildSessionFactory();
			sess = sfact.openSession();

			User user = new User();
			user.setU_name("sharma");
			Example example = Example.create(user);
			Criteria crit = sess.createCriteria(User.class).add(example);

			ProjectionList proList = Projections.projectionList();
			proList.add(Projections.property("u_name"));
			proList.add(Projections.property("u_password"));
			crit.setProjection(proList);
			List list = crit.list();
			Iterator it = list.iterator();

			System.out.println("User Name\t\tPassword");
			System.out.println("----------------------------------");

			Object[] row = (Object[]) it.next();
			for (int i = 0; i < row.length; i++) {
				System.out.print(row[i] + "\t\t\t");

			}

			sess.close();
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("Error :" + e.getMessage());
		}
	}
}

Output

Note: In this code, Example class that is used to add criteria is defined in imported package org.hibernate.criterion.

Adding Autoincrement Field using <generator/> in Hibernate

In  my previous post, We are adding id of the user by using parameter value to the constructor.  In general jsp, servlet code If id field is required to be auto increment, we will select the maximum value of the field and next value will be inserted into the field. Same operation is done by using  “incremental” class property of <generator> in Hibernate.

If we need to implement this funtionality to the previous example. We have to just remove id parameter from the constructor and edit the user id mapping to <generator/>. Changes has been highlighted in below piece of code.

 User.java

...
...
	public User(String u_name, String u_password)
	{
		this.u_name=u_name;
		this.u_password=u_password;
	}
...
...

User.hbm.xml

...
...
	<id name="u_id" type="integer" column="id">
		<generator class="increment"/>
	</id>
...
...		

Example.java

...
...
	session=sessionFactory.openSession();
	User user=new User("Sharma","newpassword");
	session.save(user);
....
...

My First Hibernate Example

As I began with Hibernate from yesterday, I went through this small example to insert a row into database table. I have done this example in MyEclipse workbench. In this example there are mainly four files to work with:

1)      hibernate.cfg.xml :

This xml file is used to configure the connection for the database. In MyEclipse, as we add the Hibernate capabilities to the project, this file will get created.

hibernate.cfg.xml will be configered like this:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
    	<property name="hibernate.connection.driver_class">
    		com.mysql.jdbc.Driver
    	</property>
		<property name="hibernate.connection.url">
			jdbc:mysql://localhost/test_db1
		</property>    
		<property name="hibernate.connection.username">
			root
		</property>
		<property name="hibernate.connection.password">
			root
		</property>
		<property name="hibernate.connection.pool_size">
			10
		</property>
		<property name="show_sql">
			true
		</property>
		<property name="dialect">
			org.hibernate.dialect.MySQLDialect
		</property>
		<property name="hibernate.hbm2ddl.auto">
			update
		</property>
		<mapping resource="User.hbm.xml"/>
    </session-factory>

</hibernate-configuration>

2)      User.java

This is a persistence class which uses POJOs class to map the fields of the particular table. In next xml file we will have to map each of these variables with the fields of the table.

package ps.com;
//User.java
public class User {
	Integer u_id;
	String u_name;
	String u_password;
	public User()
	{

	}
	public User(Integer u_id,String u_name, String u_password)
	{
		this.u_id=u_id;
		this.u_name=u_name;
		this.u_password=u_password;
	}
	public Integer getU_id() {
		return u_id;
	}
	public void setU_id(Integer u_id) {
		this.u_id = u_id;
	}
	public String getU_name() {
		return u_name;
	}
	public void setU_name(String u_name) {
		this.u_name = u_name;
	}
	public String getU_password() {
		return u_password;
	}
	public void setU_password(String u_password) {
		this.u_password = u_password;
	}
}

3)      User.hbm.xml

In this xml file, we map the variable of the persistence class with the fields of the database table. In mysql, this file is created by right clicking on the project, new>xml(basic template)

Then provide the name of the xml file (User.hbm.xml), Click on next

Select “Create XML file from a DTD file” radio button, click on next

Select “Select XML category entry” radio button

Select “-//Hibernate/Hibernate Mapping DTD 3.0//EN” from the key list, click on next

Click on finish.

The properties will be mapped like this :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
	<class name="ps.com.User" table="tbl_user">
		<id name="u_id" type="long" column="id">
			<generator class="assigned"/>
		</id>
		<property name="u_name">
			<column name="name"></column>
		</property>
		<property name="u_password">
			<column name="password"></column>
		</property>		
	</class>
</hibernate-mapping>

4)      Example.java

This is the file where we will write the code for reading the configuration file and database operations.

package ps.com;
//Example.java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

public class Example {
	public static void  main(String[] args) {
		Session session=null;
		try
		{
			SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
			session=sessionFactory.openSession();

			User user=new User(1,"Prashant","mypassword");
			session.save(user);
			session.beginTransaction().commit();
		}
		catch (Exception ex)
		{
			System.out.println("Error:" + ex);
		}
		finally
		{
			session.flush();
			session.close();
		}
	}
}

Before running the code, MySql.jar should be added to the project. And then you will need to add the Schema into the database.

As the output of this project, with the run of the Example.java, Table will be created according to the mapped setting and the given data in the example file will get saved.

Adding Simple Animations To Your Android Interface

Today one of my readers asked me for help to create simple animation. So I thought, it may be helpful for him as well as others if I could post an example as a topic.

For this example, we will need to create a folder “anim”, inside res. Then create xml files to define animation. So the explorer will look like this.

So, here is the code and source project for the example, using what you can create a simple animation for your welcome screen.

package com.anim;

//ShowAnim.java

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ShowAnim extends Activity {
    /** Called when the activity is first created. */
	LinearLayout ll_buttons;
	TextView heading,subheading;
	Button exit;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        heading=(TextView)findViewById(R.id.heading);
        subheading=(TextView)findViewById(R.id.subheading);
        ll_buttons=(LinearLayout)findViewById(R.id.ll_buttons);
        ll_buttons.setVisibility(View.GONE);
        Animation heading_animation = AnimationUtils.loadAnimation(this, R.anim.heading);
        Animation subheading_animation = AnimationUtils.loadAnimation(this, R.anim.subheading);
        heading.startAnimation(heading_animation);
        subheading.startAnimation(subheading_animation);

        subheading_animation.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onAnimationEnd(Animation animation) {
            	startButtonAnimation();
            }
        });
        exit=(Button)findViewById(R.id.btn_exit);
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            	finish();
            }
        });
    }

    public void startButtonAnimation()
    {
 	   ll_buttons.setVisibility(View.VISIBLE);
 	   Animation buttons_animation = AnimationUtils.loadAnimation(this, R.anim.buttons);
       ll_buttons.startAnimation(buttons_animation);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<!-- main.xml -->
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
>
<TextView android:id="@+id/heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_centerHorizontal="true"
android:textColor="#FFEA00"
android:textSize="40dip"
android:textStyle="bold"
android:layout_marginTop="30dip"
android:text="ANDROID"/>
<TextView android:id="@+id/subheading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_centerHorizontal="true"
android:textColor="#00FFF0"
android:textSize="15dip"
android:textStyle="bold"
android:layout_marginTop="10dip"
android:text="A Software Stack for Mobile Devices."/>
<LinearLayout
android:id="@+id/ll_buttons"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:layout_below="@+id/slogon"
android:layout_marginTop="50dip">
<Button
android:id="@+id/btn_exit"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:layout_below="@+id/slogon"
android:layout_alignParentLeft="true"
android:textColor="#FF0000"
android:textStyle="bold"
android:text="EXIT" />
</LinearLayout>
</LinearLayout >
 
<?xml version="1.0" encoding="UTF-8"?>
<!-- heading.xml -->
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<alpha
android:fromAlpha="0"
android:toAlpha="1.0"
android:duration="5000"
android:delay="3000" />
<!-- If you want rotation, you can use this -->
<!--<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:toYScale="100"
android:pivotX="50%"
android:pivotY="50%"
android:duration="3000"/>
-->
<translate
android:fromXDelta="0"
android:toXDelta="0"
android:fromYDelta="-100.0"
android:toYDelta="0.0"
android:duration="3000"/>
</set>
<?xml version="1.0" encoding="UTF-8"?>
<!-- subheading.xml -->
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<alpha
android:fromAlpha="0"
android:toAlpha="1.0"
android:duration="3000"
android:delay="3000" />
<scale
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:fromXScale="5"
android:toXScale="1"
android:fromYScale="5"
android:toYScale="1"
android:pivotX="50%"
android:pivotY="50%"
android:fillAfter="false"
android:duration="3000" />
<translate
android:fromXDelta="0"
android:toXDelta="0"
android:fromYDelta="100.0"
android:toYDelta="0.0"
android:duration="3000"/>

</set>
<?xml version="1.0" encoding="UTF-8"?>
<!-- buttons.xml -->
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<alpha
android:fromAlpha="0"
android:toAlpha="1.0"
android:duration="500"/>
<translate
android:fromXDelta="0"
android:toXDelta="0"
android:fromYDelta="30.0"
android:toYDelta="0.0"
android:duration="500"/>
</set>

Project Source Code is Available here

Sending Email from Android Application

Few readers of mine has requested me to upload the source project of my previous two examples. Then I decided to add some flavor to them before I upload, which result this example. For mailing concept, I have referred from the Jon Simon’s blog. I tried lots of other way, but his code work very well for me.

This example is only the combination of Barcode Scanner, GPS and mail.

You can download source project from here.

The changes you have to make in this downloaded project is, to add any gmail user id and password into sendMail() method, in SendInfo class.

Dynamic TableLayout in Android

As my previous post for dynamic ListView is quite helpful for few readers, here I am with a similar post. Here I am creating dynamic table. The concept looks similar but the method of creation will differ. While creating a table, we will need to create the TableLayout and from the code we will be adding rows and columns. As the table rows are more, we have to put the table into a ScrollView.

Here is same example given for ListView but will provide the country and its abbreviation in a table.

//CountriesList.java

package com.dynalist;

public class CountriesList {
	public static String[] countries = { "Afghanistan", "Albania", "Algeria",
			"American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica",
			"Antigua and Barbuda", "Argentina", "Armenia", "Aruba",
			"Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain",
			"Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin",
			"Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina",
			"Botswana", "Bouvet Island", "Brazil",
			"British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria",
			"Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada",
			"Cape Verde", "Cayman Islands", "Central African Republic", "Chad",
			"Chile", "China", "Christmas Island", "Cocos (Keeling) Islands",
			"Colombia", "Comoros", "Congo",
			"Congo, the Democratic Republic of the", "Cook Islands",
			"Costa Rica", "Cote D'Ivoire", "Croatia", "Cuba", "Cyprus",
			"Czech Republic", "Denmark", "Djibouti", "Dominica",
			"Dominican Republic", "Ecuador", "Egypt", "El Salvador",
			"Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia",
			"Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland",
			"France", "French Guiana", "French Polynesia",
			"French Southern Territories", "Gabon", "Gambia", "Georgia",
			"Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada",
			"Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
			"Guyana", "Haiti", "Heard Island and Mcdonald Islands",
			"Holy See (Vatican City State)", "Honduras", "Hong Kong",
			"Hungary", "Iceland", "India", "Indonesia",
			"Iran, Islamic Republic of", "Iraq", "Ireland", "Israel", "Italy",
			"Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati",
			"Korea, Democratic People's Republic of", "Korea, Republic of",
			"Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic",
			"Latvia", "Lebanon", "Lesotho", "Liberia",
			"Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania",
			"Luxembourg", "Macao",
			"Macedonia, the Former Yugoslav Republic of", "Madagascar",
			"Malawi", "Malaysia", "Maldives", "Mali", "Malta",
			"Marshall Islands", "Martinique", "Mauritania", "Mauritius",
			"Mayotte", "Mexico", "Micronesia, Federated States of",
			"Moldova, Republic of", "Monaco", "Mongolia", "Montserrat",
			"Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal",
			"Netherlands", "Netherlands Antilles", "New Caledonia",
			"New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue",
			"Norfolk Island", "Northern Mariana Islands", "Norway", "Oman",
			"Pakistan", "Palau", "Palestinian Territory, Occupied", "Panama",
			"Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn",
			"Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania",
			"Russian Federation", "Rwanda", "Saint Helena",
			"Saint Kitts and Nevis", "Saint Lucia",
			"Saint Pierre and Miquelon", "Saint Vincent and the Grenadines",
			"Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia",
			"Senegal", "Serbia and Montenegro", "Seychelles", "Sierra Leone",
			"Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia",
			"South Africa", "South Georgia and the South Sandwich Islands",
			"Spain", "Sri Lanka", "Sudan", "Suriname",
			"Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland",
			"Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan",
			"Tanzania, United Republic of", "Thailand", "Timor-Leste", "Togo",
			"Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
			"Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda",
			"Ukraine", "United Arab Emirates", "United Kingdom",
			"United States", "United States Minor Outlying Islands", "Uruguay",
			"Uzbekistan", "Vanuatu", "Venezuela", "Viet Nam",
			"Virgin Islands, British", "Virgin Islands, U.s.",
			"Wallis and Futuna", "Western Sahara", "Yemen", "Zambia",
			"Zimbabwe" };
	public static String[] abbreviations = { "AF", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ",
			"AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB",
			"BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BV", "BR",
			"IO", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", "KY", "CF",
			"TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR",
			"CI", "HR", "CU", "CY", "CZ", "DK", "DJ", "DM", "DO", "EC", "EG",
			"SV", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF",
			"PF", "TF", "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD",
			"GP", "GU", "GT", "GN", "GW", "GY", "HT", "HM", "VA", "HN", "HK",
			"HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IL", "IT", "JM", "JP",
			"JO", "KZ", "KE", "KI", "KP", "KR", "KW", "KG", "LA", "LV", "LB",
			"LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MY",
			"MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD",
			"MC", "MN", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "NL", "AN",
			"NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK",
			"PW", "PS", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR",
			"QA", "RE", "RO", "RU", "RW", "SH", "KN", "LC", "PM", "VC", "WS",
			"SM", "ST", "SA", "SN", "CS", "SC", "SL", "SG", "SK", "SI", "SB",
			"SO", "ZA", "GS", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH",
			"SY", "TW", "TJ", "TZ", "TH", "TL", "TG", "TK", "TO", "TT", "TN",
			"TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UM", "UY",
			"UZ", "VU", "VE", "VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW" };
}
//MyTable.java
package com.dynatable;

import android.app.Activity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.dynatable.R;

public class MyTable extends Activity {
	/** Called when the activity is first created. */
	TableLayout country_table;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		country_table=(TableLayout)findViewById(R.id.country_table);
		fillCountryTable();
	}
	void fillCountryTable() {

		TableRow row;
		TextView t1, t2;
		//Converting to dip unit
		int dip = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				(float) 1, getResources().getDisplayMetrics());

		for (int current = 0; current < CountriesList.abbreviations.length; current++) {
			row = new TableRow(this);

			t1 = new TextView(this);
			t1.setTextColor(getResources().getColor(R.color.yellow));
			t2 = new TextView(this);
			t2.setTextColor(getResources().getColor(R.color.dark_red));

			t1.setText(CountriesList.abbreviations[current]);
			t2.setText(CountriesList.countries[current]);

			t1.setTypeface(null, 1);
			t2.setTypeface(null, 1);

			t1.setTextSize(15);
			t2.setTextSize(15);

			t1.setWidth(50 * dip);
			t2.setWidth(150 * dip);
			t1.setPadding(20*dip, 0, 0, 0);
			row.addView(t1);
			row.addView(t2);

			country_table.addView(row, new TableLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

		}
	}
}
<?xml version="1.0" encoding="utf-8"?>
<!--main.xml-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffccd0"
    >
    <TextView
    	    android:text="Countries List"
    	    android:textColor="#b3000d"
    	    android:gravity="center_vertical|center_horizontal"
    	    android:textSize="26dip"
    	    android:layout_width="fill_parent"
    	    android:layout_height="wrap_content"
    	    android:textStyle="bold"
    	    android:background="#ffb0b6"
    	    android:layout_marginBottom="5dip"
    	    android:typeface="sans"/>
    <RelativeLayout android:id="@+id/rl_country_heading"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:background="#555555">
		<TextView android:id="@+id/tv_11"
			android:layout_width="70dip"
			android:layout_height="wrap_content"
			android:gravity="center"
			android:text="Abbr"
			android:textStyle="normal|bold"
			android:textColor="#FFFFFF"
			android:textSize="18dip">
		</TextView>
		<TextView android:id="@+id/tv_12"
			android:layout_width="150dip"
			android:layout_height="wrap_content"
			android:gravity="center"
			android:text="Comment"
			android:textStyle="normal|bold"
			android:textColor="#FFFFFF"
			android:textSize="18dip"
			android:layout_toRightOf="@+id/tv_11">
		</TextView>
	</RelativeLayout>
	<LinearLayout android:id="@+id/ll_country"
		android:layout_height="fill_parent" android:layout_width="fill_parent">
		<ScrollView android:id="@+id/ScrollView11"
			android:layout_width="fill_parent" android:layout_height="fill_parent"
			android:fillViewport="true">
			<LinearLayout android:layout_width="fill_parent"
				android:layout_height="wrap_content" android:layout_margin="5dip">
				<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
					android:layout_width="fill_parent" android:layout_height="fill_parent"
					android:stretchColumns="0,1" android:id="@+id/country_table">
				</TableLayout>
			</LinearLayout>
		</ScrollView>
	</LinearLayout>
</LinearLayout>

//MyTable.java
package com.dynatable; 

import android.app.Activity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.dynatable.R;

public class MyTable extends Activity {
/** Called when the activity is first created. */
TableLayout country_table;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
country_table=(TableLayout)findViewById(R.id.country_table);
fillCountryTable();
}
void fillCountryTable() {

TableRow row;
TextView t1, t2;
//Converting to dip unit
int dip = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
(float) 1, getResources().getDisplayMetrics());

for (int current = 0; current < CountriesList.abbreviations.length; current++) {
row = new TableRow(this);

t1 = new TextView(this);
t1.setTextColor(getResources().getColor(R.color.yellow));
t2 = new TextView(this);
t2.setTextColor(getResources().getColor(R.color.dark_red));

t1.setText(CountriesList.abbreviations[current]);
t2.setText(CountriesList.countries[current]);

t1.setTypeface(null, 1);
t2.setTypeface(null, 1);

t1.setTextSize(15);
t2.setTextSize(15);

t1.setWidth(50 * dip);
t2.setWidth(150 * dip);
t1.setPadding(20*dip, 0, 0, 0);
row.addView(t1);
row.addView(t2);

country_table.addView(row, new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

}
}
}

The package explorer will look like this:

Output of the example looks like this:

Dynamic ListView in Android

Yesterday one of my readers mail me, asking help for creating the dynamic list. Here is the solution where I have listed the abbreviation and name of the countries in two column list.

In this project I have mainly worked with 4 files.

CountriesList.java : To store the list of all countries and their abbreviations.

MyList.java : It contain the context of the example.

Main.xml : for the creation of the layout of the MyList context.

Two_col_row.xml : It only contain two TextView for the rows in the ListView.

//CountriesList.java

package com.dynalist;

public class CountriesList {
	public static String[] countries = { "Afghanistan", "Albania", "Algeria",
			"American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica",
			"Antigua and Barbuda", "Argentina", "Armenia", "Aruba",
			"Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain",
			"Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin",
			"Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina",
			"Botswana", "Bouvet Island", "Brazil",
			"British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria",
			"Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada",
			"Cape Verde", "Cayman Islands", "Central African Republic", "Chad",
			"Chile", "China", "Christmas Island", "Cocos (Keeling) Islands",
			"Colombia", "Comoros", "Congo",
			"Congo, the Democratic Republic of the", "Cook Islands",
			"Costa Rica", "Cote D'Ivoire", "Croatia", "Cuba", "Cyprus",
			"Czech Republic", "Denmark", "Djibouti", "Dominica",
			"Dominican Republic", "Ecuador", "Egypt", "El Salvador",
			"Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia",
			"Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland",
			"France", "French Guiana", "French Polynesia",
			"French Southern Territories", "Gabon", "Gambia", "Georgia",
			"Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada",
			"Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
			"Guyana", "Haiti", "Heard Island and Mcdonald Islands",
			"Holy See (Vatican City State)", "Honduras", "Hong Kong",
			"Hungary", "Iceland", "India", "Indonesia",
			"Iran, Islamic Republic of", "Iraq", "Ireland", "Israel", "Italy",
			"Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati",
			"Korea, Democratic People's Republic of", "Korea, Republic of",
			"Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic",
			"Latvia", "Lebanon", "Lesotho", "Liberia",
			"Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania",
			"Luxembourg", "Macao",
			"Macedonia, the Former Yugoslav Republic of", "Madagascar",
			"Malawi", "Malaysia", "Maldives", "Mali", "Malta",
			"Marshall Islands", "Martinique", "Mauritania", "Mauritius",
			"Mayotte", "Mexico", "Micronesia, Federated States of",
			"Moldova, Republic of", "Monaco", "Mongolia", "Montserrat",
			"Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal",
			"Netherlands", "Netherlands Antilles", "New Caledonia",
			"New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue",
			"Norfolk Island", "Northern Mariana Islands", "Norway", "Oman",
			"Pakistan", "Palau", "Palestinian Territory, Occupied", "Panama",
			"Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn",
			"Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania",
			"Russian Federation", "Rwanda", "Saint Helena",
			"Saint Kitts and Nevis", "Saint Lucia",
			"Saint Pierre and Miquelon", "Saint Vincent and the Grenadines",
			"Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia",
			"Senegal", "Serbia and Montenegro", "Seychelles", "Sierra Leone",
			"Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia",
			"South Africa", "South Georgia and the South Sandwich Islands",
			"Spain", "Sri Lanka", "Sudan", "Suriname",
			"Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland",
			"Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan",
			"Tanzania, United Republic of", "Thailand", "Timor-Leste", "Togo",
			"Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
			"Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda",
			"Ukraine", "United Arab Emirates", "United Kingdom",
			"United States", "United States Minor Outlying Islands", "Uruguay",
			"Uzbekistan", "Vanuatu", "Venezuela", "Viet Nam",
			"Virgin Islands, British", "Virgin Islands, U.s.",
			"Wallis and Futuna", "Western Sahara", "Yemen", "Zambia",
			"Zimbabwe" };
	public static String[] abbreviations = { "AF", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ",
			"AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB",
			"BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BV", "BR",
			"IO", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", "KY", "CF",
			"TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR",
			"CI", "HR", "CU", "CY", "CZ", "DK", "DJ", "DM", "DO", "EC", "EG",
			"SV", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF",
			"PF", "TF", "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD",
			"GP", "GU", "GT", "GN", "GW", "GY", "HT", "HM", "VA", "HN", "HK",
			"HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IL", "IT", "JM", "JP",
			"JO", "KZ", "KE", "KI", "KP", "KR", "KW", "KG", "LA", "LV", "LB",
			"LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MY",
			"MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD",
			"MC", "MN", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "NL", "AN",
			"NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK",
			"PW", "PS", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR",
			"QA", "RE", "RO", "RU", "RW", "SH", "KN", "LC", "PM", "VC", "WS",
			"SM", "ST", "SA", "SN", "CS", "SC", "SL", "SG", "SK", "SI", "SB",
			"SO", "ZA", "GS", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH",
			"SY", "TW", "TJ", "TZ", "TH", "TL", "TG", "TK", "TO", "TT", "TN",
			"TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UM", "UY",
			"UZ", "VU", "VE", "VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW" };
}
//MyList .java

package com.dynalist;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MyList extends Activity {
	/** Called when the activity is first created. */
	ListView listView;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		listView = (ListView) findViewById(R.id.lv_country);
		listView.setAdapter(new EfficientAdapter(this));
	}
	private static class EfficientAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public EfficientAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
		}

		public int getCount() {
			return CountriesList.abbreviations.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.two_col_row, null);
				holder = new ViewHolder();
				holder.text1 = (TextView) convertView
						.findViewById(R.id.TextView01);
				holder.text2 = (TextView) convertView
						.findViewById(R.id.TextView02);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.text1.setText(CountriesList.abbreviations[position]);
			holder.text2.setText(CountriesList.countries[position]);

			return convertView;
		}

		static class ViewHolder {
			TextView text1;
			TextView text2;
		}
	}
}
<?xml version="1.0" encoding="utf-8"?>
<!--main.xml-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffccd0"
    >
    <TextView
    	    android:text="Countries List"
    	    android:textColor="#b3000d"
    	    android:gravity="center_vertical|center_horizontal"
    	    android:textSize="26dip"
    	    android:layout_width="fill_parent"
    	    android:layout_height="wrap_content"
    	    android:textStyle="bold"
    	    android:background="#ffb0b6"
    	    android:layout_marginBottom="5dip"
    	    android:typeface="sans"/>
   	<RelativeLayout
		android:layout_width="fill_parent"
	 	android:layout_height="wrap_content"
		android:background="#570000">
	    <TextView android:id="@+id/tv_1"
			android:textColor="#FFFFFF"
			android:gravity="center_vertical|left"
			android:textSize="16dip"
			android:layout_height="wrap_content"
			android:textStyle="bold"
			android:typeface="serif"
			android:layout_width="70dip"
			android:paddingLeft="20dip"
			android:text="Abbr">
		</TextView>
		<TextView android:id="@+id/tv_2"
			android:textColor="#FFFFFF"
			android:gravity="center_vertical|left"
			android:textSize="16dip"
			android:layout_height="wrap_content"
			android:textStyle="bold"
			android:typeface="serif"
			android:layout_width="200dip"
			android:layout_toRightOf="@+id/tv_1"
			android:text="Countries">
		</TextView>

	</RelativeLayout>
	<ListView
 		android:id="@+id/lv_country"
 		android:layout_height="wrap_content"
 		android:layout_width="fill_parent"
 		android:cacheColorHint="#00000000">
 	</ListView>
</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<!--two_col_row.xml-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_height="wrap_content"
	android:gravity="left|center"
 	android:layout_width="wrap_content"
 	android:paddingBottom="10px"
 	android:paddingTop="10px"
 	android:paddingLeft="3px">
	 <TextView
	 	android:id="@+id/TextView01"
	 	android:layout_width="70dip"
	 	android:layout_height="wrap_content"
	 	android:gravity="left"
	 	android:textSize="15dip"
	 	android:textStyle="bold"
	 	android:textColor="#d08021"
		android:paddingLeft="20dip">
	 </TextView>
	 <TextView
	 	android:id="@+id/TextView02"
	 	android:layout_width="200dip"
	 	android:layout_height="wrap_content"
	 	android:gravity="left"
	 	android:layout_marginLeft="10dip"
	 	android:textSize="15dip"
	 	android:textStyle="bold"
	 	android:textColor="#7f0000">
	 </TextView>

</LinearLayout>

The package explorer will look like this:

Output of the example looks like this:

This example can be very much helpful, when you are creating a list from the data from database.

//CountriesList.java

package com.dynalist;

public class CountriesList {
public static String[] countries = { “Afghanistan”, “Albania”, “Algeria”,
“American Samoa”, “Andorra”, “Angola”, “Anguilla”, “Antarctica”,
“Antigua and Barbuda”, “Argentina”, “Armenia”, “Aruba”,
“Australia”, “Austria”, “Azerbaijan”, “Bahamas”, “Bahrain”,
“Bangladesh”, “Barbados”, “Belarus”, “Belgium”, “Belize”, “Benin”,
“Bermuda”, “Bhutan”, “Bolivia”, “Bosnia and Herzegovina”,
“Botswana”, “Bouvet Island”, “Brazil”,
“British Indian Ocean Territory”, “Brunei Darussalam”, “Bulgaria”,
“Burkina Faso”, “Burundi”, “Cambodia”, “Cameroon”, “Canada”,
“Cape Verde”, “Cayman Islands”, “Central African Republic”, “Chad”,
“Chile”, “China”, “Christmas Island”, “Cocos (Keeling) Islands”,
“Colombia”, “Comoros”, “Congo”,
“Congo, the Democratic Republic of the”, “Cook Islands”,
“Costa Rica”, “Cote D’Ivoire”, “Croatia”, “Cuba”, “Cyprus”,
“Czech Republic”, “Denmark”, “Djibouti”, “Dominica”,
“Dominican Republic”, “Ecuador”, “Egypt”, “El Salvador”,
“Equatorial Guinea”, “Eritrea”, “Estonia”, “Ethiopia”,
“Falkland Islands (Malvinas)”, “Faroe Islands”, “Fiji”, “Finland”,
“France”, “French Guiana”, “French Polynesia”,
“French Southern Territories”, “Gabon”, “Gambia”, “Georgia”,
“Germany”, “Ghana”, “Gibraltar”, “Greece”, “Greenland”, “Grenada”,
“Guadeloupe”, “Guam”, “Guatemala”, “Guinea”, “Guinea-Bissau”,
“Guyana”, “Haiti”, “Heard Island and Mcdonald Islands”,
“Holy See (Vatican City State)”, “Honduras”, “Hong Kong”,
“Hungary”, “Iceland”, “India”, “Indonesia”,
“Iran, Islamic Republic of”, “Iraq”, “Ireland”, “Israel”, “Italy”,
“Jamaica”, “Japan”, “Jordan”, “Kazakhstan”, “Kenya”, “Kiribati”,
“Korea, Democratic People’s Republic of”, “Korea, Republic of”,
“Kuwait”, “Kyrgyzstan”, “Lao People’s Democratic Republic”,
“Latvia”, “Lebanon”, “Lesotho”, “Liberia”,
“Libyan Arab Jamahiriya”, “Liechtenstein”, “Lithuania”,
“Luxembourg”, “Macao”,
“Macedonia, the Former Yugoslav Republic of”, “Madagascar”,
“Malawi”, “Malaysia”, “Maldives”, “Mali”, “Malta”,
“Marshall Islands”, “Martinique”, “Mauritania”, “Mauritius”,
“Mayotte”, “Mexico”, “Micronesia, Federated States of”,
“Moldova, Republic of”, “Monaco”, “Mongolia”, “Montserrat”,
“Morocco”, “Mozambique”, “Myanmar”, “Namibia”, “Nauru”, “Nepal”,
“Netherlands”, “Netherlands Antilles”, “New Caledonia”,
“New Zealand”, “Nicaragua”, “Niger”, “Nigeria”, “Niue”,
“Norfolk Island”, “Northern Mariana Islands”, “Norway”, “Oman”,
“Pakistan”, “Palau”, “Palestinian Territory, Occupied”, “Panama”,
“Papua New Guinea”, “Paraguay”, “Peru”, “Philippines”, “Pitcairn”,
“Poland”, “Portugal”, “Puerto Rico”, “Qatar”, “Reunion”, “Romania”,
“Russian Federation”, “Rwanda”, “Saint Helena”,
“Saint Kitts and Nevis”, “Saint Lucia”,
“Saint Pierre and Miquelon”, “Saint Vincent and the Grenadines”,
“Samoa”, “San Marino”, “Sao Tome and Principe”, “Saudi Arabia”,
“Senegal”, “Serbia and Montenegro”, “Seychelles”, “Sierra Leone”,
“Singapore”, “Slovakia”, “Slovenia”, “Solomon Islands”, “Somalia”,
“South Africa”, “South Georgia and the South Sandwich Islands”,
“Spain”, “Sri Lanka”, “Sudan”, “Suriname”,
“Svalbard and Jan Mayen”, “Swaziland”, “Sweden”, “Switzerland”,
“Syrian Arab Republic”, “Taiwan, Province of China”, “Tajikistan”,
“Tanzania, United Republic of”, “Thailand”, “Timor-Leste”, “Togo”,
“Tokelau”, “Tonga”, “Trinidad and Tobago”, “Tunisia”, “Turkey”,
“Turkmenistan”, “Turks and Caicos Islands”, “Tuvalu”, “Uganda”,
“Ukraine”, “United Arab Emirates”, “United Kingdom”,
“United States”, “United States Minor Outlying Islands”, “Uruguay”,
“Uzbekistan”, “Vanuatu”, “Venezuela”, “Viet Nam”,
“Virgin Islands, British”, “Virgin Islands, U.s.”,
“Wallis and Futuna”, “Western Sahara”, “Yemen”, “Zambia”,
“Zimbabwe” };
public static String[] abbreviations = { “AF”, “AL”, “DZ”, “AS”, “AD”, “AO”, “AI”, “AQ”,
“AG”, “AR”, “AM”, “AW”, “AU”, “AT”, “AZ”, “BS”, “BH”, “BD”, “BB”,
“BY”, “BE”, “BZ”, “BJ”, “BM”, “BT”, “BO”, “BA”, “BW”, “BV”, “BR”,
“IO”, “BN”, “BG”, “BF”, “BI”, “KH”, “CM”, “CA”, “CV”, “KY”, “CF”,
“TD”, “CL”, “CN”, “CX”, “CC”, “CO”, “KM”, “CG”, “CD”, “CK”, “CR”,
“CI”, “HR”, “CU”, “CY”, “CZ”, “DK”, “DJ”, “DM”, “DO”, “EC”, “EG”,
“SV”, “GQ”, “ER”, “EE”, “ET”, “FK”, “FO”, “FJ”, “FI”, “FR”, “GF”,
“PF”, “TF”, “GA”, “GM”, “GE”, “DE”, “GH”, “GI”, “GR”, “GL”, “GD”,
“GP”, “GU”, “GT”, “GN”, “GW”, “GY”, “HT”, “HM”, “VA”, “HN”, “HK”,
“HU”, “IS”, “IN”, “ID”, “IR”, “IQ”, “IE”, “IL”, “IT”, “JM”, “JP”,
“JO”, “KZ”, “KE”, “KI”, “KP”, “KR”, “KW”, “KG”, “LA”, “LV”, “LB”,
“LS”, “LR”, “LY”, “LI”, “LT”, “LU”, “MO”, “MK”, “MG”, “MW”, “MY”,
“MV”, “ML”, “MT”, “MH”, “MQ”, “MR”, “MU”, “YT”, “MX”, “FM”, “MD”,
“MC”, “MN”, “MS”, “MA”, “MZ”, “MM”, “NA”, “NR”, “NP”, “NL”, “AN”,
“NC”, “NZ”, “NI”, “NE”, “NG”, “NU”, “NF”, “MP”, “NO”, “OM”, “PK”,
“PW”, “PS”, “PA”, “PG”, “PY”, “PE”, “PH”, “PN”, “PL”, “PT”, “PR”,
“QA”, “RE”, “RO”, “RU”, “RW”, “SH”, “KN”, “LC”, “PM”, “VC”, “WS”,
“SM”, “ST”, “SA”, “SN”, “CS”, “SC”, “SL”, “SG”, “SK”, “SI”, “SB”,
“SO”, “ZA”, “GS”, “ES”, “LK”, “SD”, “SR”, “SJ”, “SZ”, “SE”, “CH”,
“SY”, “TW”, “TJ”, “TZ”, “TH”, “TL”, “TG”, “TK”, “TO”, “TT”, “TN”,
“TR”, “TM”, “TC”, “TV”, “UG”, “UA”, “AE”, “GB”, “US”, “UM”, “UY”,
“UZ”, “VU”, “VE”, “VN”, “VG”, “VI”, “WF”, “EH”, “YE”, “ZM”, “ZW” };
}

Geting current location in Android application, using GPS

Today one another functionality I tried in the android application. It was to provide the longitude and latitude of the current location in android using it GPS system. The coding was quite easy.  We have to create a LocationManager and LocationListener. And sending the GPS_PROVIDE, we can get the current location value in term of longitude and latitude.

Here are the codes I have implemented in my project

1.       Enable the ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION by adding the following two tag (line 18,19) into the Minifest xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.yms"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name" >
        <activity android:name=".Login"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        .
        .
        .
    </application>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
</manifest>

2.       Write a class which will return the longitude and latitude using the current GPS Location

package com.testgps;

import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;

public class MyLocationListener implements LocationListener {

    public static double latitude;
    public static double longitude;

    @Override
	public void onLocationChanged(Location loc)
	{
		loc.getLatitude();
		loc.getLongitude();
		latitude=loc.getLatitude();
		longitude=loc.getLongitude();
	}

	@Override
	public void onProviderDisabled(String provider)
	{
		//print "Currently GPS is Disabled";
	}
	@Override
	public void onProviderEnabled(String provider)
	{
		//print "GPS got Enabled";
	}
	@Override
	public void onStatusChanged(String provider, int status, Bundle extras)
	{
	}
}

3.       On button click call onLocationChange, which will return the value that could be assigned to EditText or any other control

btn_show_location.setOnClickListener(new View.OnClickListener() {
     public void onClick(View view) {
         LocationManager mlocManager=null;
         LocationListener mlocListener;
         mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
         mlocListener = new MyLocationListener();
        mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);

        if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if(MyLocationListener.latitude>0)
            {
                 et_field_name.append("Latitude:- " + MyLocationListener.latitude + '\n');
                 et_field_name.append("Longitude:- " + MyLocationListener.longitude + '\n');
             }
             else
             {
                  alert.setTitle("Wait");
                  alert.setMessage("GPS in progress, please wait.");
                  alert.setPositiveButton("OK", null);
                  alert.show();
              }
          } else {
              et_field_name.setText("GPS is not turned on...");
          }

      }
 });

Referred from firstdroid.com

Scanning barcode from Android application

Today, I was able to do a remarkable task in Android. Actually I have got to read barcode using the android camera. First thing came to my mind was, is it possible? But later after goggling few hours, I found zxing , an open source application for barcode scanning which can be embed into our own application.

My task was to read barcode in a selected textbox. For that I had to do the following thing:

1. I had downloaded and installed BarcodeScanner apk file from here

2. Created an interface with a EditText and a Button

3. On Button click I had to send the intent to the BarcodeScanner

btn_search.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {

        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        intent.setPackage("com.google.zxing.client.android");
        intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent, 0);
    }
});

4. I had placed the Barcode symbol inside the rectangle, given by BarcodeScanner

5.  After scan as it returns to our application, I had to put the barcode number into the EditText, which is done by following code.

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == 0) {
        if (resultCode == RESULT_OK) {
            String contents = intent.getStringExtra("SCAN_RESULT");
            et_code.setText(contents);
            String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
        } else if (resultCode == RESULT_CANCELED) {
            et_code.setText("Please scan again");
        }
    }
}

scan a barcode

Follow

Get every new post delivered to your Inbox.

Join 187 other followers