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.)

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

Multiple Interface Communication in Android

Here I am posting one another Android example for multiple interface communication. While developing most of the application, we may need multiple interfaces. This could be achieve by creating two activities and calling one from another.

Here in this example, I create TextView(label), EditText(textbox) and Button in main.xml interface.

<?xml version="1.0" encoding="utf-8"?>
<!-- main.xml -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10pt"
        android:textColor="#444444"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="20dip"
        android:text="Name:"/>
    <EditText
        android:id="@+id/et_name"
        android:layout_below="@id/tv_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip"
        android:background="@android:drawable/editbox_background"/>
     <Button
        android:id="@+id/btn_ok"
        android:layout_below="@id/et_name"
        android:layout_width="100dip"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginTop="15dip"
        android:text="OK" />
</RelativeLayout>

Another activity interface main_hello.xml (we can copy and paste the main.xml and make changes) is created in Project -> res -> layout. Here we provide a TextView(label) and a Button.

<?xml version="1.0" encoding="utf-8"?>
<!-- main_hello.xml -->
<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#DDDDDD"
    >
	<TextView
        android:id="@+id/tv_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10pt"
        android:textColor="#444444"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="20dip"
        android:text="Hello, "/>
    <Button
        android:id="@+id/btn_back"
        android:layout_below="@+id/tv_show"
        android:layout_width="100dip"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginTop="15dip"
        android:text="OK" />

</RelativeLayout>

On FirstActivity.java, which will show the main.xml, we have to add ClickListener to the button.

package com.multiple.example;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class FirstActivity extends Activity {
    /** Called when the activity is first created. */
	public static String name;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final EditText nm=(EditText)findViewById(R.id.et_name);
        Button next = (Button) findViewById(R.id.btn_ok);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	name=nm.getText().toString();
                Intent myIntent = new Intent(view.getContext(), SayHello.class);
                startActivityForResult(myIntent, 0);
            }
        });
    }
}

Another interface is created as SayHello.java (we can copy and paste the FirstActivity.java and make changes) which will display the man_hello.xml components with the message (textbox value). And on the click of the button, it will return to the FirstActivity interface.

package com.multiple.example;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SayHello extends Activity {
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_hello);
        Button back = (Button)findViewById(R.id.btn_back);
        TextView msg=(TextView) findViewById(R.id.tv_show);
        msg.setText("Hello, " + FirstActivity.name);
        back.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), FirstActivity.class);
                startActivityForResult(myIntent, 0);
            }
        });
    }
}

As we have created new Interface (SayHello.java) ourselves, it should be added into AndroidManifest.xml as given below.

<?xml version="1.0" encoding="utf-8"?>
<!-- AndroidManifest.xml -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.multiple.example"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".FirstActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
		<activity android:name=".SayHello"></activity>
    </application>
</manifest>

The directory tree will look like this:

Then Your project is ready to Run as below:

 

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
>
<TextView
android:id=”@+id/tv_name”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:textSize=”10pt”
android:textColor=”#444444″
android:layout_alignParentLeft=”true”
android:layout_marginTop=”20dip”
android:text=”Name:”/>
<EditText
android:id=”@+id/et_name”
android:layout_below=”@id/tv_name”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”10dip”
android:background=”@android:drawable/editbox_background”/>
<Button
android:id=”@+id/btn_ok”
android:layout_below=”@id/et_name”
android:layout_width=”100dip”
android:layout_height=”wrap_content”
android:layout_alignParentRight=”true”
android:layout_marginTop=”15dip”
android:text=”OK” />
</RelativeLayout>

Login Application For Android

Last week my friend was stuck for an Android application. That application was to use the remote database (MS SQL Server) for login.

Later I saw the coding of Android, which was Java only. Its much like just another Java framework. So I thought to give a try to help him and even I could learn some Mobile Application programming.

As Android provide flat file data storage or SQlite for data storage, it was quite tough to access the remote database like MSSQL Server, Oracle or MYSql.

Later I found in newtondev that we can execute GET or POST request from the android page and get the output of the requesting page. This lead me to the solution.

I sends the form data from Android application to the Server-side page (JSP, Servlet,ASP or PHP), then those page will compile the required operation for login validation using any database , then it returns “1” if the login is valid else return “0”.

Here are the source codes that will give you Idea for the application.

Application -> res -> layout -> main.xml (interface for Android)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="210dip"
    android:layout_marginTop="10dip"
    android:background="#DDDDDD">
    <TextView
        android:id="@+id/tv_un"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10pt"
        android:textColor="#444444"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="9dip"
        android:layout_marginTop="20dip"
        android:layout_marginLeft="10dip"
        android:text="User Name:"/>
    <EditText
        android:id="@+id/et_un"
        android:layout_width="150dip"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background"
        android:layout_toRightOf="@id/tv_un"
        android:layout_alignTop="@id/tv_un"/>
     <TextView
        android:id="@+id/tv_pw"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10pt"
        android:textColor="#444444"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/tv_un"
        android:layout_marginRight="9dip"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="10dip"
        android:text="Password:"/>
    <EditText
        android:id="@+id/et_pw"
        android:layout_width="150dip"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background"
        android:layout_toRightOf="@id/tv_pw"
        android:layout_alignTop="@id/tv_pw"
        android:layout_below="@id/et_un"
        android:layout_marginLeft="17dip"
        android:password="true"        />
    <Button
        android:id="@+id/btn_login"
        android:layout_width="100dip"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_pw"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="110dip"
        android:text="Login" />
     <TextView
        android:id="@+id/tv_error"
        android:layout_width="fill_parent"
        android:layout_height="40dip"
        android:textSize="7pt"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/btn_login"
        android:layout_marginRight="9dip"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="15dip"
        android:textColor="#AA0000"
        android:text=""/>
</RelativeLayout>

Application -> src -> com.example.login -> LoginLayout.java

package com.example.login;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginLayout extends Activity {
    EditText un,pw;
	TextView error;
    Button ok;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        un=(EditText)findViewById(R.id.et_un);
        pw=(EditText)findViewById(R.id.et_pw);
        ok=(Button)findViewById(R.id.btn_login);
        error=(TextView)findViewById(R.id.tv_error);

        ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            	ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            	postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
            	postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));

            	String response = null;
            	try {
            	    response = CustomHttpClient.executeHttpPost("<target page url>", postParameters);
            	    String res=response.toString();
            	    res= res.replaceAll("\\s+","");
            	    if(res.equals("1"))
            	    	error.setText("Correct Username or Password");
            	    else
            	    	error.setText("Sorry!! Incorrect Username or Password");
            	} catch (Exception e) {
            		un.setText(e.toString());
            	}

            }
        });
    }
}

Application -> src -> com.example.login ->CustomHttpClient.java (from newtondev)

package com.example.login;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class CustomHttpClient {
	/** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;

    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }

    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     *
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Since the application will not be allowed to access the Internet (remote service). So we have to add permission using following line to the AndroidManifest.xml


<uses-permission android:name="android.permission.INTERNET" />

So that the AndroidManifest.xml look like this.


<?xml version="1.0" encoding="utf-8"?>
   <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           package="com.example.layout"
           android:versionCode="1"
           android:versionName="1.0">
       <uses-permission android:name="android.permission.INTERNET" />
       <application android:icon="@drawable/icon" android:label="@string/app_name">
       .
       .
       .
       </application>

</manifest>

Then on the server-side we can check login by using password. But here in this example I have use a simple servlet, which check the static login.

package web.com;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Prashant
 */
@WebServlet(name="AndroidResponse", urlPatterns={"/androidres.do"})
public class AndroidResponse extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        String un,pw;
        un=request.getParameter("username");
        pw=request.getParameter("password");
        if(un.equalsIgnoreCase("prashant") && pw.equals("sharma"))
            out.print(1);
        else
            out.print(0);
    }
}

Output :

<?xml version=”1.0″ encoding=”utf-8″?>

<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;

android:layout_width=”fill_parent”

android:layout_height=”210dip”

android:layout_marginTop=”10dip”

android:background=”#DDDDDD”>

<TextView

android:id=”@+id/tv_un”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:textSize=”10pt”

android:textColor=”#444444″

android:layout_alignParentLeft=”true”

android:layout_marginRight=”9dip”

android:layout_marginTop=”20dip”

android:layout_marginLeft=”10dip”

android:text=”User Name:”/>

<EditText

android:id=”@+id/et_un”

android:layout_width=”150dip”

android:layout_height=”wrap_content”

android:background=”@android:drawable/editbox_background”

android:layout_toRightOf=”@id/tv_un”

android:layout_alignTop=”@id/tv_un”/>

<TextView

android:id=”@+id/tv_pw”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:textSize=”10pt”

android:textColor=”#444444″

android:layout_alignParentLeft=”true”

android:layout_below=”@id/tv_un”

android:layout_marginRight=”9dip”

android:layout_marginTop=”15dip”

android:layout_marginLeft=”10dip”

android:text=”Password:”/>

<EditText

android:id=”@+id/et_pw”

android:layout_width=”150dip”

android:layout_height=”wrap_content”

android:background=”@android:drawable/editbox_background”

android:layout_toRightOf=”@id/tv_pw”

android:layout_alignTop=”@id/tv_pw”

android:layout_below=”@id/et_un”

android:layout_marginLeft=”17dip”

android:password=”true”        />

<Button

android:id=”@+id/btn_login”

android:layout_width=”100dip”

android:layout_height=”wrap_content”

android:layout_below=”@id/et_pw”

android:layout_alignParentLeft=”true”

android:layout_marginTop=”15dip”

android:layout_marginLeft=”110dip”

android:text=”Login” />

<TextView

android:id=”@+id/tv_error”

android:layout_width=”fill_parent”

android:layout_height=”40dip”

android:textSize=”7pt”

android:layout_alignParentLeft=”true”

android:layout_below=”@id/btn_login”

android:layout_marginRight=”9dip”

android:layout_marginTop=”15dip”

android:layout_marginLeft=”15dip”

android:textColor=”#AA0000″

android:text=””/>

</RelativeLayout>