How to load a spinner with values from SQlite Database in android?

Here is a simple example showing how to load a database values in a spinner in android.

Spinner from SQLite

OK we will start.

This is the layout for the spinner row.
spinner_row.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation     =      "vertical"
    android:id="@+id/tv"
    android:layout_margin="10dp">   
</TextView>

This is the layout for the interface.

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textStyle="bold"
        android:text="Load DB values into Spinner"
         >
    </TextView>

    <Spinner
        android:id="@+id/spinner1"
        android:layout_below="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

</LinearLayout>

Now this is the MainActivity.java file that uses the spinner and the database.

package com.coderzheaven.loadspinnerfromdb;

import   java  .util  .ArrayList;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {

	SQLiteDatabase mydb;
	private   static String DBNAME = "PERSONS.db";
	private static String TABLE = "MY_TABLE";

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

		createTable();
		insertIntoTable();

		ArrayList<String> my_array = new ArrayList<String>();
		my_array = getTableValues();

		Spinner My_spinner = (Spinner) findViewById(R.id.spinner1);
		ArrayAdapter my_Adapter = new ArrayAdapter(this, R.layout.spinner_row,
				my_array);
		My_spinner.setAdapter(my_Adapter);
	}

	// CREATE TABLE IF NOT EXISTS
	public void createTable() {
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			mydb.execSQL("CREATE TABLE IF  NOT EXISTS " + TABLE
					+ " (ID INTEGER PRIMARY KEY, NAME TEXT, PLACE TEXT);");
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error in creating table",
					Toast.LENGTH_LONG);
		}
	}

	// THIS FUNCTION INSERTS DATA TO THE DATABASE
	public void insertIntoTable() {
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('CODERZHEAVEN','GREAT INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('ANTHONY','USA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('SHUING','JAPAN')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('JAMES','INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('SOORYA','INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('MALIK','INDIA')");
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(),
					"Error in inserting into table", Toast.LENGTH_LONG);
		}
	}

	// THIS FUNCTION SHOWS DATA FROM THE DATABASE
	public ArrayList<String> getTableValues() {

		ArrayList<String> my_array = new ArrayList<String>();
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			Cursor allrows = mydb.rawQuery("SELECT * FROM " + TABLE, null);
			System.out.println("COUNT : " + allrows.getCount());

			if (allrows.moveToFirst()) {
				do {

					String ID = allrows.getString(0);
					String NAME = allrows.getString(1);
					String PLACE = allrows.getString(2);
					my_array.add(NAME);

				} while (allrows.moveToNext());
			}
			allrows.close();
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error encountered.",
					Toast.LENGTH_LONG);
		}
		return my_array;
	}

}

Join the Forum discussion on this post

Note : Please remove the “span” tags from the post when you copy it.

Download the complete source code for this example from here.

Select an Image from gallery in ANDROID and show it in an ImageView.

Hi all
In this tutorial I will show you how to get an image from your phone gallery and show it in an imageview.
Here we use intents to open up the image gallery and get the image URI.
Here I am setting the image type as “image” to get only the images.
And on onActivityResult if the result is OK, then get the data using getData() function and converting the imageURI to the stringPath.
Then show the image in the imageview using setImageURI.

package pack.GetImage;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class GetImageActivity extends Activity {

	private static final int SELECT_PICTURE = 1;

	private String selectedImagePath;
	private ImageView img;

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

	    img = (ImageView)findViewById(R.id.ImageView01);

	    ((Button) findViewById(R.id.Button01))
	            .setOnClickListener(new OnClickListener() {
	                public void onClick(View arg0) {
	                    Intent intent = new Intent();
	                    intent.setType("image/*");
	                    intent.setAction(Intent.ACTION_GET_CONTENT);
	                    startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
	                }
	            });
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode == RESULT_OK) {
	        if (requestCode == SELECT_PICTURE) {
	            Uri selectedImageUri = data.getData();
	            selectedImagePath = getPath(selectedImageUri);
	            System.out.println("Image Path : " + selectedImagePath);
	            img.setImageURI(selectedImageUri);
	        }
	    }
	}

	public String getPath(Uri uri) {
	    String[] projection = { MediaStore.Images.Media.DATA };
	    Cursor cursor = managedQuery(uri, projection, null, null, null);
	    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    cursor.moveToFirst();
	    return cursor.getString(column_index);
	}
}

Here is the main.xml file


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Button android:text="Browse gallery"
	android:id="@+id/Button01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
<ImageView android:id="@+id/ImageView01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</ImageView>
</LinearLayout>

Please leave your valuable comments if you found this post useful.

How to save data or score in Android Cocos2D?

Hello Friends
Today I will show you how to save data in cocos2D android in a database and reload it when the game starts.
This has been always a problem withe game developers for cocos2D android.
I will show you a way to save almost any number of data in a database using SQlite in android.

Check these examples for how to use SQlite databases in android
1. Working with SQLite Database in ANDROID.
2. Using SQLite in ANDROID, A really simple example.

First thing you need to know is cocos2d.
Downlod a sample project for cocos2D from here and copy the libraries into your project
Assuming all are familiar with Cocos2D. I am starting this tutorial.

Create a fresh project named SaveDataDemo.
then create a class named SQlite.java and copy this code into it.
This file contains the table definition and methods for accessing the data in the table. All you need is call these functions in your main file and insert, update or get the data from the database.

SQlite.java

package com.coderzheaven.pack;

import java.util.Set;
import java.util.Map.Entry;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

class MyTable
{
	 private String TABLE_NAME = "my_table";
	 int DATABASE_VERSION = 1;
	 private String _ID = "id";
	 private String _SCORE = "score";

	public String getTableName(){			return TABLE_NAME;}
	public int getDatabaseVersion()	{		return DATABASE_VERSION;}

	public String getID()		{		return _ID;			}
	public String getScore()	{		return _SCORE;		}

	public String getDatabaseCreateQuery()
	{
		final String DATABASE_CREATE =
		    "create table IF NOT EXISTS " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, "
		    + _SCORE + " TEXT NOT NULL)";

		return DATABASE_CREATE;

	}
}

class dbOperation
{
		static String DB_TABLE ;
		static int DB_VERSION = GlobalClass.DATABASE_VERSION;
		static String[] DATABASE_CREATE;
	    private Context context;
	    private DatabaseHelper DBHelper;
	    private SQLiteDatabase db;

	    public dbOperation(Context ctx,String[] query)
	    {
	    	this.context = ctx;
 	        DATABASE_CREATE = query;
 	        DBHelper = new DatabaseHelper(context);
	    }
	    public dbOperation(Context ctx)
	    {
	    	this.context = ctx;
	    	DBHelper = new DatabaseHelper(context);
	    }

	    public dbOperation(String tablename)  //for inner calling
	    {
	    	DB_TABLE = tablename;
	    	DBHelper = new DatabaseHelper(context);
	    }

		public dbOperation open() throws SQLException
	    {
	        db = DBHelper.getWritableDatabase();
	        return this;
	    }
	    public void close()
	    {
	        DBHelper.close();
	    }
	    private static class DatabaseHelper extends SQLiteOpenHelper
	    {
	        DatabaseHelper(Context context)
	        {
	            super(context, GlobalClass.DBNAME, null, DB_VERSION);
	        }
	        public void onCreate(SQLiteDatabase db)
	        {
	            try
	            {
	            	for (String s  : DATABASE_CREATE)
	            	{
	            		db.execSQL(s);
					}
				}
	            catch (Exception e) {
					System.out.println("Error creating items Per screen in the constructor" + e.getMessage());
				}
	        }
	        public void onUpgrade(SQLiteDatabase db, int oldVersion,
	        int newVersion)
	        {
	        	db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
	            onCreate(db);
	        }
	    }

	    public long insertTableData(String tablename,ContentValues values)  throws SQLException
	    {
	    	DB_TABLE = tablename;
	    	ContentValues initialValues2 = new ContentValues();
	        Set<Entry<String, Object>> s =  values.valueSet();
	        String new_val = "";
	        for (Entry<String, Object> entry : s) {
	            new_val = values.getAsString(entry.getKey());
	            initialValues2.put(entry.getKey(), new_val);
	        }
	        return db.insert(DB_TABLE, null, initialValues2);
	    }
	    public boolean deleteTableData(String tablename,String condition)  throws SQLException
	    {
	    	DB_TABLE = tablename;
	    	return db.delete(DB_TABLE, condition, null) > 0;
	    }
	    public Cursor getAllTableData(String tablename,String[] fields)  throws SQLException
	    {
	    	DB_TABLE = tablename;
				return db.query(DB_TABLE, fields,null, null, null, null, null);
	    }
	    public Cursor getTableRow(String tablename,String[] dbFields, String condition,String order,String limit) throws SQLException
	    {
	    	DB_TABLE = tablename;
	        Cursor mCursor =    db.query(false, DB_TABLE, dbFields,condition,
	                			null,null,null, order, limit);

	        if (mCursor != null) {
	            mCursor.moveToFirst();
	        }
	        return mCursor;
	    }
	    public boolean updateTable(String tablename,ContentValues args,String condition)
	    {
	    	DB_TABLE = tablename;
	    	return db.update(DB_TABLE, args,condition , null) > 0;

	    }
	    public int lastInsertedID(String tablename)
	    {
	    	int retVar=0;
	    	Cursor mCursor = db.rawQuery("select max(id) from "+tablename, null);

			if (mCursor != null) {
				mCursor.moveToFirst();
				retVar =Integer.parseInt(mCursor.getString(0));
			}
			mCursor.close();
			mCursor.deactivate();
			return retVar ;
	    }
}

Now create a file named “GameLayer.java” file and copy this code into it.
GameLayer.java

package com.coderzheaven.pack;

import org.cocos2d.actions.instant.CCCallFuncN;
import org.cocos2d.actions.interval.CCMoveTo;
import org.cocos2d.actions.interval.CCSequence;
import org.cocos2d.layers.CCColorLayer;
import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.nodes.CCLabel;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGSize;
import org.cocos2d.types.ccColor3B;
import org.cocos2d.types.ccColor4B;

import android.content.ContentValues;
import android.database.Cursor;
import android.view.MotionEvent;

public class GameLayer extends CCColorLayer
{
	protected CCLabel _label = null;
	CGSize winSize = CCDirector.sharedDirector().displaySize();
	int myscore = 0;

	public static CCScene scene()
	{
		CCScene scene = CCScene.node();
		CCColorLayer layer = new GameLayer(ccColor4B.ccc4(255, 255, 255, 255));
		scene.addChild(layer);
		return scene;
	}

	protected GameLayer(ccColor4B color)
	{
		super(color);
		this.setIsTouchEnabled(true);
		DBOperations();
	}

	public void DBOperations(){
		addAndroid();
		createAndInitializeTables();
		insertData(myscore);
		myscore = getDataFromTable();
		System.out.println("SCORE : " + myscore);
		updateTable(myscore);
		myscore = getDataFromTable();
		System.out.println("SCORE : " + myscore);
		showLabel(myscore);
	}

	public void createAndInitializeTables(){
        try{
        	MyTable mytable = new MyTable();
        	String[] tableCreateArray = {mytable.getDatabaseCreateQuery()};
    		dbOperation operation = new dbOperation(CCDirector.sharedDirector().getActivity(),tableCreateArray);
			operation.open();
			operation.close();
        }catch(Exception e){
           System.out.println("Error creating table " + e.getMessage());
        }
        System.out.println("Table successfully created!!");
	}
	public int getDataFromTable(){
		dbOperation operationObj = new dbOperation(CCDirector.sharedDirector().getActivity());
        operationObj.open();
		MyTable mytable = new MyTable();
		int score = 0;
		String  condition2 = mytable.getID() +" = 1 ";
        String[] dbFields4 = {mytable.getScore()};
        Cursor cursor =  operationObj.getTableRow(mytable.getTableName(),dbFields4,condition2,mytable.getID() + " ASC ",1 +"");
        if(cursor.getCount()>0)
        {
        	 cursor.moveToFirst();
        	 do{
        		 score = cursor.getInt(0);
        	 }while(cursor.moveToNext());
        }
        cursor.close();
		cursor.deactivate();
		operationObj.close();

		return score;
	}
	public void insertData(int score){
		MyTable mytable = new MyTable();
		dbOperation operationObj = new dbOperation(CCDirector.sharedDirector().getActivity());
        operationObj.open();
		ContentValues initialValues = new ContentValues();
    	initialValues.put(mytable.getScore(),score+"");
        operationObj.insertTableData(mytable.getTableName(),initialValues);
        int maxID = operationObj.lastInsertedID(mytable.getTableName());
        System.out.println("LAST INSERTED ID : " + maxID);
        operationObj.close();
	}
	public void updateTable(int scr){
		MyTable mytable = new MyTable();
		dbOperation operationObj = new dbOperation(CCDirector.sharedDirector().getActivity());
        operationObj.open();
        String condition = mytable.getID() + " = 1";
		ContentValues initialValues = new ContentValues();
    	initialValues.put(mytable.getScore(),scr+"");
        operationObj.updateTable(mytable.getTableName(),initialValues,condition);
        operationObj.close();
	}
	public void showLabel(int scr){

		if(_label != null){
			this.removeChild(_label,true);
		}
		_label = CCLabel.makeLabel("Score : " + scr, "Verdana", 20);
		_label.setColor(ccColor3B.ccBLACK);
		_label.setPosition(5 5f, winSize.height - 15);
		addChild(_label);
	}
	public void addAndroid(){
		CGSize winSize = CCDirector.sharedDirector().displaySize();
		CCSprite player = CCSprite.sprite("android.png");
		player.setPosition(CGPoint.ccp(player.getContentSize().width / 2.0f, winSize.height / 2.0f));
		addChild(player);

		CCMoveTo actionMove = CCMoveTo.action(3, CGPoint.ccp(winSize.getWidth(), winSize.getHeight()/2.0f));
		CCCallFuncN actionMoveDone = CCCallFuncN.action(this, "spriteMoveFinished");
		CCSequence actions = CCSequence.actions(actionMove, actionMoveDone);

		player.runAction(actions);
	}

	public void spriteMoveFinished(Object sender)
	{
		CCSprite sprite = (CCSprite)sender;
		this.removeChild(sprite, true);
		myscore++;
		updateTable(myscore);
		showLabel(myscore);
		addAndroid();
	}
	@Override
	public boolean ccTouchesBegan(MotionEvent event)
	{
		return true;
	}
}

Note : copy a file named “android.png” into the assets folder.

Now create a file named “GlobalClass.java” and copy this code into it.
GlobalClass.java

package com.coderzheaven.pack;

public class GlobalClass
{
	  public static String DBNAME = "mytest.db";
	  public static final int DATABASE_VERSION = 1;
}

Now this is the main file that calls this gamelayer which is named “SaveDataDemo.java”

package com.coderzheaven.pack;

import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.opengl.CCGLSurfaceView;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class SaveDataDemo extends Activity
{
	protected CCGLSurfaceView _glSurfaceView;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		_glSurfaceView = new CCGLSurfaceView(this);
		setContentView(_glSurfaceView);
	}

	@Override
	public void onStart()
	{
		super.onStart();
		CCDirector.sharedDirector().attachInView(_glSurfaceView);
		CCDirector.sharedDirector().setDeviceOrientation(CCDirector.kCCDeviceOrientationLandscapeLeft);
		CCDirector.sharedDirector().setDisplayFPS(true);
		CCDirector.sharedDirector().setAnimationInterval(1.0f / 60.0f);
		CCScene scene = GameLayer.scene();
		CCDirector.sharedDirector().runWithScene(scene);
	}

	@Override
	public void onPause()
	{
		super.onPause();
		CCDirector.sharedDirector().pause();
	}

	@Override
	public void onResume()
	{
		super.onResume();
		CCDirector.sharedDirector().resume();
	}

	@Override
	public void onStop()
	{
		super.onStop();
		CCDirector.sharedDirector().end();
	}
}

Inside the GameLayer class check these functions that loads the data from the database or insert or update the database.

public void DBOperations(){
		addAndroid();
		createAndInitializeTables();
		insertData(myscore);
		myscore = getDataFromTable();
		System.out.println("SCORE : " + myscore);
		updateTable(myscore);
		myscore = getDataFromTable();
		System.out.println("SCORE : " + myscore);
		showLabel(myscore);
	}

Here are the screenshots.





Download the complete source code from here.

If you find this post useful please leave your valuable comments and +1 this post to share more and give me encouragement for future posts.

Join the Forum discussion on this post

Get All Details from Contacts in ANDROID.

Hi all..

In today’s post I will show you how to get all information from the ANDROID Contacts programatically.
Just copy and paste this code to your mail java file and check the Logcat for output.

package pack.coderzheaven;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;

public class GetContactsDemo extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        readContacts();
    }

    public void readContacts(){
    	 ContentResolver cr = getContentResolver();
    	 Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);

         if (cur.getCount() > 0) {
        	while (cur.moveToNext()) {
		        String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
		        String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
		        if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
		        	System.out.println("name : " + name + ", ID : " + id);

		        	// get the phone number
		        	Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
		         		    			   ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
		         		    			   new String[]{id}, null);
         	        while (pCur.moveToNext()) {
         	        	  String phone = pCur.getString(
         	        			 pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
         	        	  System.out.println("phone" + phone);
         	        }
         	        pCur.close();


         	        // get email and type

         	       Cursor emailCur = cr.query(
         	    			ContactsContract.CommonDataKinds.Email.CONTENT_URI,
         	    			null,
         	    			ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
         	    			new String[]{id}, null);
     	    		while (emailCur.moveToNext()) {
     	    		    // This would allow you get several email addresses
     	    	            // if the email addresses were stored in an array
     	    		    String email = emailCur.getString(
     	    	                      emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
     	    	 	    String emailType = emailCur.getString(
     	    	                      emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));

     	    		  System.out.println("Email " + email + " Email Type : " + emailType);
         	    	}
         	    	emailCur.close();

         	    	// Get note.......
         	    	String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
         	        String[] noteWhereParams = new String[]{id,
         	 		ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
         	                Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null);
	         	 	if (noteCur.moveToFirst()) {
	         	 	    String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
	         	 	  System.out.println("Note " + note);
	         	 	}
	         	 	noteCur.close();

	         	 	//Get Postal Address....

	         	 	String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
	         		String[] addrWhereParams = new String[]{id,
	         			ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
	         		Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,
	         	                null, null, null, null);
	         		while(addrCur.moveToNext()) {
	         			String poBox = addrCur.getString(
	         	                     addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
	         	 		String street = addrCur.getString(
	         	                     addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
	         	 		String city = addrCur.getString(
	         	                     addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
	         	 		String state = addrCur.getString(
	         	                     addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
	         	 		String postalCode = addrCur.getString(
	         	                     addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
	         	 		String country = addrCur.getString(
	         	                     addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
	         	 		String type = addrCur.getString(
	         	                     addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));

	         	 		// Do something with these....

	         	 	}
	         	 	addrCur.close();

	         	 	// Get Instant Messenger.........
	         	 	String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
	         	 	String[] imWhereParams = new String[]{id,
	         	 	    ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE};
	         	 	Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI,
	         	            null, imWhere, imWhereParams, null);
	         	 	if (imCur.moveToFirst()) {
	         	 	    String imName = imCur.getString(
	         	                 imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
	         	 	    String imType;
	         	 	    imType = imCur.getString(
	         	                 imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
	         	 	}
	         	 	imCur.close();

	         	 	// Get Organizations.........

	         	 	String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
	         	 	String[] orgWhereParams = new String[]{id,
	         	 		ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
	         	 	Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI,
	         	                null, orgWhere, orgWhereParams, null);
	         	 	if (orgCur.moveToFirst()) {
	         	 		String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
	         	 		String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
	         	 	}
	         	 	orgCur.close();
	 	        }
	        }
 	   }
    }

}

Note : Make sure you add this permission to the AndroidManifest File.

Download the complete android java source code from the link below.

coderzheaven.com/uploads/GetContactsTwo.rar

Posts to come ……..

How to add and delete contacts programatically. keep visiting coderzheaven….

Some of the posts you want to see are located here
Please leave your valuable comments on this post.

Working with SQLite Database in ANDROID.

Below is a straight forward example of how to deal with SQLite database in ANDROID.
Go ahead and copy and paste the following code to your java file.
The example has one database and performs functions like insert delete and listing of values in a textView.

package com.database;
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.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class databaseactivity extends Activity {
    /** Called when the activity is first created. */

    private static String DBNAME = "mydb.db";
    private static String TABLE = "myTable";

    Button butAdd,butdel;
    EditText nam,mail;
    LinearLayout lay;
    TableLayout layout;
    TextView tev,tev1;
    int f=0;
    Integer ind;
   ScrollView sv;
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tev=(TextView)findViewById(R.id.tv);
        tev1=(TextView)findViewById(R.id.tv1);
        layout=(TableLayout)findViewById(R.id.layout);
        lay = (LinearLayout) findViewById(R.id.linear);
        butAdd = (Button) findViewById(R.id.add);
        nam=(EditText)findViewById(R.id.names);
        mail=(EditText)findViewById(R.id.emails);

       SQLiteDatabase mydb;
       mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
       mydb.execSQL("create table if not exists "+TABLE+" (_id integer primary key autoincrement,name text not null,email text not null);");
       mydb.close();
       sv = new ScrollView(this);
       setContentView(sv);
       sv.addView(lay);

       butAdd.setOnClickListener(new View.OnClickListener()
       {
      @Override
      public void onClick(View v)
      {
                  f=0;
                  addTask();
      }
      });
    }

    public void addTask()
    {
                SQLiteDatabase mydb;
                mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
                ContentValues newrow = new ContentValues();
                String a=nam.getText().toString();
                String b=mail.getText().toString();
                if(a.trim().length()!=0 && b.trim().length()!=0)
                {
                                newrow.put("name", nam.getText().toString());
                                newrow.put("email", mail.getText().toString());
                                mydb.insert(TABLE, null, newrow);
                }
                else
                {
                                if(f==0)
                                      Toast.makeText(getApplicationContext(), "Fields cannot be left blank",
                                                                                                               Toast.LENGTH_SHORT).show();
                }
                nam.setText(null);
                mail.setText(null);
                String[] result = new String[]{"_id","name","email"};
                Cursor allrows  = mydb.query(TABLE, result, null, null, null, null, null);
                Integer cindex = allrows.getColumnIndex("name");
                Integer cindex1 = allrows.getColumnIndex("email");
                Integer cindex2 = allrows.getColumnIndex("_id");
                if(allrows.moveToFirst())
                {
                layout.removeAllViews();
                do
                {
                                TableRow row= new TableRow(this);
                                final TextView tv = new TextView(this);
                                final TextView tv1 = new TextView(this);
                                final Button but=new Button(this);
                                but.setText("Delete");
                                final Button butt=new Button(this);
                                butt.setText("Edit");                                ind=Integer.parseInt(allrows.getString(cindex2)) ;
                                but.setId(ind);
                                butt.setId(ind);
                                nam.setId(ind);
                                but.setOnClickListener(new View.OnClickListener() {
                                                public void onClick(View v)
                                                {
                                                                f=1;
                                                                int i=but.getId();
                                                                SQLiteDatabase mydb;
                                                                mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
                                                                mydb.delete(TABLE,"_id="+i, null);
                                                                mydb.close();
                                                                Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_SHORT).show();
                                                                addTask();
                                                }
                                });


                                butt.setOnClickListener(new View.OnClickListener() {
                                                public void onClick(View v)
                                                {
                                                               butt.setText("Save");
                                                               nam.setText(tv.getText());
                                                               mail.setText(tv1.getText());
                                                               butt.setOnClickListener(new View.OnClickListener() {
                                                               public void onClick(View v)   {
                                                                             f=1;
                                                                             int j=but.getId();
                                                                             SQLiteDatabase mydb;
                                                                             mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
;
                                                                             ContentValues newrow1 = new ContentValues();
                                                                             String a=nam.getText().toString();
                                                                             String b=mail.getText().toString();
                                                                             if(a.trim().length()!=0&& b.trim().length()!=0)                                                                                {                                                                                                newrow1.put("name", nam.getText().toString());
                                                                                                  newrow1.put("email", mail.getText().toString());
                                                                                                  mydb.update(TABLE,newrow1, "_id="+j, null);
                                       
                                                                                                  Toast.makeText(getApplicationContext(), "Updated",
                                                                                                                            Toast.LENGTH_SHORT).show();
                                                                                                  nam.setText(null);
                                                                                                  mail.setText(null);
                                                                                                  butt.setText("Edit");
                                                                                                  addTask();
                                                                               }    else                                                                                {
                                                                                         //if(f==0)
                                                                                           Toast.makeText(getApplicationContext(), "Fields cannot be left blank",
                                                                                                                                 Toast.LENGTH_SHORT).show();
                                                                         }                                                                                mydb.close();
                                                                    }
                                                            });
                                                }
                                });
                                tv.setText(allrows.getString(cindex));
                                row.addView(tv);
                                tv1.setText(allrows.getString(cindex1));
                                row.addView(tv1);
                                row.addView(butt);
                                row.addView(but);
                                layout.addView(row);
                }while(allrows.moveToNext());
                }
                else
                {
                                layout.removeAllViews();
                                Toast.makeText(getApplicationContext(), "Table is empty", Toast.LENGTH_SHORT).show();
                }
                mydb.close();
    }
}

In the XML file set up a TableLayout with android:stretchColumns=”0,1″
and other buttons also and proceed.

Please leave your valuable comments.