Wednesday, 10 August 2011

Send Sms From android

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.SMSMessaging"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SMS"
                  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.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>


main.xml
<?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="Enter the phone number of recipient"
        />     
    <EditText 
        android:id="@+id/txtPhoneNo"  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"        
        />
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"         
        android:text="Message"
        />     
    <EditText 
        android:id="@+id/txtMessage"  
        android:layout_width="fill_parent" 
        android:layout_height="150px"
        android:gravity="top"         
        />          
    <Button 
        android:id="@+id/btnSendSMS"  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:text="Send SMS"
        />    
</LinearLayout>


SMS.java Activity

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
public class SMS extends Activity 
{
    Button btnSendSMS;
    EditText txtPhoneNo;
    EditText txtMessage;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
 
        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);
 
        btnSendSMS.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {                
                String phoneNo = txtPhoneNo.getText().toString();
                String message = txtMessage.getText().toString();                 
                if (phoneNo.length()>0 && message.length()>0)                
                    sendSMS(phoneNo, message);                
                else
                    Toast.makeText(getBaseContext(), 
                        "Please enter both phone number and message.", 
                        Toast.LENGTH_SHORT).show();
            }
        });        
    }    
//---sends an SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {        
        PendingIntent pi = PendingIntent.getActivity(this, 0,
            new Intent(this, SMS.class), 0);                
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, pi, null);        
    }    
//or to get delivery report....
/---sends an SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {        
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";
 
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);
 
        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);
 
        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));
 
        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;                        
                }
            }
        }, new IntentFilter(DELIVERED));        
 
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);        
    }

//send message using intent

                String number = "6508570720";
          startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", number, null)));

      
}

Audio Recordiing


AudioDemo.java
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class AudioDemo extends Activity implements OnClickListener {
	private static final String TAG = "AudioDemo";
	private static final String isPlaying = "Media is Playing"; 
	private static final String notPlaying = "Media has stopped Playing"; 
	
	MediaPlayer player;
	Button playerButton;

	public void onClick(View v) {
		Log.d(TAG, "onClick: " + v);
		if (v.getId() == R.id.play) {
			playPause();
		}
	}

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

		player = MediaPlayer.create(this, R.raw.robotrock);
		player.setLooping(false); // Set looping

		// Get the button from the view
		playerButton = (Button) this.findViewById(R.id.play);
		playerButton.setText(R.string.stop_label);
		playerButton.setOnClickListener(this);

		// Begin playing selected media
		demoPlay();

		// Release media instance to system
		player.release();
		
	}

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

	// Initiate media player pause
	private void demoPause(){
            player.pause();
            playerButton.setText(R.string.play_label);
            Toast.makeText(this, notPlaying, Toast.LENGTH_LONG).show();
            Log.d(TAG, notPlaying);
	}
	
	// Initiate playing the media player
	private void demoPlay(){
            player.start();
            playerButton.setText(R.string.stop_label);
            Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
            Log.d(TAG, isPlaying);
	}
	
	// Toggle between the play and pause
	private void playPause() {
		if(player.isPlaying()) {
		  demoPause();
		} else {
		  demoPlay();
		}	
	}
}
main.xml
<?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:layout_width="wrap_content"
		android:layout_height="wrap_content" android:id="@+id/play"
		android:text="@string/play_label"></Button>
</LinearLayout>
strings.xml
resources>
    <string name="hello">Hello World, AudioDemo</string>
    <string name="app_name">Audio Demo</string>
<string name="play_label">Play</string>
<string name="stop_label">Stop</string>
</resources>

Contact Details


Android Contact API For 2.0

Granting Access

Before an application can query the contact records access must be granted through the AndroidManifest.xml file stored in the root of the project. Add the following uses-permission belows the uses-sdk statement.

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

Querying The Android Contact Database

Retrieving Contact Details

Basic contact information stored in Contacts table with detailed information stored in individual tables for normalization. In Android 2.0 to query the base contact records the URI to query is stored in ContactsContract.Contacts.CONTENT_URI.

package higherpass.TestContacts;

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

public class TestContacts extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        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) {
 		    //Query phone here.  Covered next
 	        }
            }
 	}
    }
}

This application starts off as any other Android application. First create a ContentResolver isntance in cr. Then use the ContentResolver instance to query the database and return a Cursor with the contacts list. The query is perofrmed against the URI stored in ContactsContract.Contacts.CONTENT_URI. Next check if the cursor contains records and if so loop through them. The record ID field is stored in the id variable. This will be used as a where parameter later. Also the display name field is stored in the string name. For more details about working with cursors see Android Cursors Tutorial.

Phone Numbers

Phone numbers are stored in their own table and need to be queried separately. To query the phone number table use the URI stored in the SDK variable ContactsContract.CommonDataKinds.Phone.CONTENT_URI. Use a WHERE conditional to get the phone numbers for the specified contact.

if (Integer.parseInt(cur.getString(
                   cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                Cursor pCur = cr.query(
 		    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
 		    null, 
 		    ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
 		    new String[]{id}, null);
 	        while (pCur.moveToNext()) {
 		    // Do something with phones
 	        } 
 	        pCur.close();
 	    }

Perform a second query against the Android contacts SQLite database. The phone numbers are queried against the URI stored in ContactsContract.CommonDataKinds.Phone.CONTENT_URI. The contact ID is stored in the phone table as ContactsContract.CommonDataKinds.Phone.CONTACT_ID and the WHERE clause is used to limit the data returned.

Email Addresses

Querying email addresses is similar to phone numbers. A query must be performed to get email addresses from the database. Query the URI stored in ContactsContract.CommonDataKinds.Email.CONTENT_URI to query the email address table.

	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)); 
 	} 
 	emailCur.close();

As with the phone query the field names for the email table are also stored under ContactsContract.CommonDataKinds. The email query is performed on the URI in ContactsContract.CommonDataKinds.Email.CONTENT_URI and the WHERE clause has to match the ContactsContract.CommonDataKinds.Email.CONTACT_ID field. Since multiple email addresses can be stored loop through the records returned in the Cursor.

Notes

Custom notes can be attached to each contact record. As before these are stored in a separate table and are related based on the contact ID.

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));
 	} 
 	noteCur.close();

Notes are stored in the Android Contacts generic data table. When accessing specific data the WHERE clause will need 2 conditionals. First the standard contact ID, second a MIMETYPE for the data that is being requested. The Android SDK comes with a series of auto-generated variables that take care of this. Use the ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE variable to limit the query to note records. The data table URI is stored at ContactsContract.Data.CONTENT_URI. Finally the note field name is stored in ContactsContract.CommonDataKinds.Note.NOTE.

Postal Addresses

Android can store multiple postal addresses per contact. Addresses are also stored in the data table like notes and queried via the URI stored in ContactsContract.Data.CONTENT_URI. Similar to the notes query a MIMETYPE must be added to the WHERE conditional. Also in Android 2.0 the Address record was split into multiple fields containing different parts of the address (PO-Box, stree, city, region, postal code). In earlier versions of the Android SDK this was a free-form string storage.

	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, where, whereParameters, 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));
 	} 
 	addrCur.close();

This code is similar to the previous example. Notice the field names for the address pieces are stored in ContactsContract.CommonDataKinds.StructuredPostal.

Instant Messenger (IM)

The instant messenger query performs just as the notes and address queries. Important field names for IM related data are stored in ContactsContract.CommonDataKinds.Im.

	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();

Organizations

The last part of the contact record to be covered is the Organizations data. The Android contact record can contain information about Employment, professional, and social memberships as well as roles and titles. These records are queried from the URI stored in ContactsContract.Data.CONTENT_URI. Important field names for the organization data are stored in ContactsContract.CommonDataKinds.Organization.

	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();

Notification Example


import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;



/**
 * This class create status bar notification and cancel it
 *
 */
public class NotificationExample extends Activity implements OnClickListener{

private NotificationManager mNotificationManager;
private int SIMPLE_NOTFICATION_ID;
Button start, cancel;
Notification notifyDetails;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notification_manager);

// Create object object of notification manager
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

// set properties to notification object
notifyDetails = new Notification(R.drawable.icon,
"Notification, Click Me!", System.currentTimeMillis());

// Set vibration when notify and assign defaults
long[] vibrate = { 100, 100, 200, 300 };
notifyDetails.vibrate = vibrate;
notifyDetails.defaults = Notification.DEFAULT_ALL;

// create buttons
start = (Button) findViewById(R.id.btnShowNotification);
cancel = (Button) findViewById(R.id.btnClear);

// set buttons listeners
start.setOnClickListener(this);
cancel.setOnClickListener(this);

}

@Override
public void onClick(View v) {
if(v == start){

Context context = getApplicationContext();
CharSequence contentTitle = "Notification Test";
CharSequence contentText = "Get back to Application on clicking me.";

Intent notifyIntent = new Intent(context, NotificationExample.class);

PendingIntent intent = PendingIntent.getActivity(NotificationExample.this, 0,
notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);

// Set properties to notify object - its title, text
notifyDetails.setLatestEventInfo(context, contentTitle,
contentText, intent);

// Notify user in status bar
mNotificationManager.notify(SIMPLE_NOTFICATION_ID,
notifyDetails);
}
else if(v == cancel){
// Cancel notification
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
}
}
}

Show Alert Dialog


public void Showalert(String msg){
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage(msg)
.setCancelable(false).setNegativeButton("OK",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});

AlertDialog alert = alt_bld.create();
alert.setTitle("Alert");
alert.show();
}

Sqlite External Database Connectivity


DataBaseHelper.java


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;


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.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;


public class DataBaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/PACKAGE_NAME/databases/";  //PACKAGE_NAME= getApplicationContext().getPackageName();
private static String DB_NAME = "contacts.db";
private static SQLiteDatabase myDataBase;
private final Context myContext;


public DataBaseHelper(Context context) {


super(context, DB_NAME, null, 1);
this.myContext = context;
}


//---Create the database---
public void createDataBase() throws IOException {


//---Check whether database is already created or not---
boolean dbExist = checkDataBase();


if (dbExist) {
} else {
this.getReadableDatabase();
try {
//---If not created then copy the database---
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}


}

//--- Check whether database already created or not---
private boolean checkDataBase() {
try {
String myPath = DB_PATH + DB_NAME;
File f = new File(myPath);
if (f.exists())
return true;
else
return false;
} catch (SQLiteException e) {
e.printStackTrace();
return false;
}


}


//--- Copy the database to the output stream---
private void copyDataBase() throws IOException {


InputStream myInput = myContext.getAssets().open(DB_NAME);


String outFileName = DB_PATH + DB_NAME;


OutputStream myOutput = new FileOutputStream(outFileName);


byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}


myOutput.flush();
myOutput.close();
myInput.close();


}


public void openDataBase() throws SQLException {


//--- Open the database---
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);


}


@Override
public synchronized void close() {


if (myDataBase != null)
myDataBase.close();


super.close();


}


@Override
public void onCreate(SQLiteDatabase arg0) {


}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


}


/**
 * Insert new contact detail in ContactMaster table
 * @param name
 * @param phone
 * @return boolean value
 */
public boolean insertContact(String name, String phone) {
boolean inserted = false;
openDataBase();
try {
ContentValues values = new ContentValues();


values.put("name", name);
values.put("phone", phone);

myDataBase.insert("contactMaster", null, values);
inserted = true;


} catch (Exception e) {
e.printStackTrace();
} finally {


myDataBase.close();
SQLiteDatabase.releaseMemory();
}


return inserted;
}


/**
 * Update contact detail
 * @param id
 * @param name
 * @param phone
 * @return boolean value
 */
public boolean updateContact(int id, String name, String phone) {
boolean updated = false;
openDataBase();
try {
ContentValues values = new ContentValues();


values.put("name", name);
values.put("phone", phone);

myDataBase.update("contactMaster", values, "Id = " + id, null);

updated = true;


} catch (Exception e) {
e.printStackTrace();
} finally {


myDataBase.close();
SQLiteDatabase.releaseMemory();
}
return updated;
}

/**
 * Delete the contact detail of the id passed from ContactMaster table 
 * @param id
 * @return booleane value
 */
public boolean deleteContact(int id) {
boolean deleted = false;
openDataBase();
try {

myDataBase.delete("contactMaster", "Id = " + id, null);
deleted = true;


} catch (Exception e) {
e.printStackTrace();
} finally {


myDataBase.close();
SQLiteDatabase.releaseMemory();
}
return deleted;
}

/**
 * Get all the contacts from the ContactMaster table
 * @return ArrayList<ContactModel>
 */
public ArrayList<ContactModel> getContacts() {


ArrayList<ContactModel> contacts = null;
openDataBase();
Cursor c;


String select = "Select * from contactMaster";
try {
c = myDataBase.rawQuery(select, null);
contacts = new ArrayList<ContactModel>();


for (int i = 0; i < c.getCount(); i++) {
c.moveToNext();
ContactModel contact = new ContactModel();


contact.setId(c.getInt(0));
contact.setName(c.getString(1));
contact.setPhone(c.getString(2));

contacts.add(contact);
}
myDataBase.close();
c.close();
SQLiteDatabase.releaseMemory();


} catch (Exception e) {
e.printStackTrace();
}
return contacts;
}


/**
 * Get the contact details from the id passed
 * @param userid
 * @return ContactModel
 */
public ContactModel getUser(int userid) {
ContactModel user = new ContactModel();
openDataBase();
Cursor c;


String select = "Select * from contactMaster " + "where Id =" + userid;
try {
c = myDataBase.rawQuery(select, null);


for (int i = 0; i < c.getCount(); i++) {
c.moveToNext();


user.setId(c.getInt(0));
user.setName(c.getString(1));
user.setPhone(c.getString(2));

}
c.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
myDataBase.close();
SQLiteDatabase.releaseMemory();
}

return user;
}
}




ContactModel.java





public class ContactModel {

private int id;
private String name;
private String phone;

//--- Set ID of contact---
public void setId(int id) {
this.id = id;
}
//--- Get ID of contact---
public int getId() {
return id;
}
//--- Set name of contact---
public void setName(String name) {
this.name = name;
}
//--- Get name of contact---
public String getName() {
return name;
}
//--- Set phone of contact---
public void setPhone(String phone) {
this.phone = phone;
}
//--- Get name of contact---
public String getPhone() {
return phone;
}

}



ContactList.java

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;



public class ContactList extends Activity implements OnClickListener{
/**
 * Intialize variables
 */
DataBaseHelper myDatabase;
ArrayList<ContactModel> contacts;
LinearLayout linearMain;
Button btnadd;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);

setContentView(R.layout.sqlite_contactlist);
linearMain = (LinearLayout) findViewById(R.id.linearmainLayout);
//---Database initialize and create database---
myDatabase = new DataBaseHelper(this);
try {
myDatabase.createDataBase();
} catch (IOException e1) {
e1.printStackTrace();
}
btnadd = (Button) findViewById(R.id.btnadd);
btnadd.setOnClickListener(this);
}
@Override
protected void onResume() {
super.onResume();

linearMain.removeAllViews();
linearMain.invalidate();
 //---display the dynamic list of contacts---
AddLayout();
}

/**
 * Get all the contacts from the database
 */
public void AddLayout() {
contacts = myDatabase.getContacts();
if (contacts.size() > 0) {
for (int i =0; i < contacts.size(); i++)
createLayout(contacts.get(i));
}
}
/**
 * Create dynamic layout to display contact list
 * @param contact 
 */
public void createLayout(final ContactModel contact) {

LinearLayout.LayoutParams lp_l = new LinearLayout.LayoutParams(
(LayoutParams.FILL_PARENT), (LayoutParams.WRAP_CONTENT));
lp_l.setMargins(5, 5, 5, 5);

RelativeLayout relative = new RelativeLayout(getApplicationContext());
relative.setLayoutParams(lp_l);
relative.setBackgroundColor(Color.GRAY);
relative.setPadding(5, 5, 5, 5);
RelativeLayout.LayoutParams rel_lp1 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rel_lp1.setMargins(0, 15, 0, 0);
final TextView tvname = new TextView(getApplicationContext());
tvname.setLayoutParams(rel_lp1);
tvname.setTextColor(Color.WHITE);
tvname.setText(contact.getName());
relative.addView(tvname);

RelativeLayout.LayoutParams rel_lp2 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rel_lp2.setMargins(150, 15, 0, 0);
final TextView tvPhone = new TextView(getApplicationContext());
tvPhone.setLayoutParams(rel_lp2);
tvPhone.setTextColor(Color.WHITE);
tvPhone.setText(contact.getPhone());
relative.addView(tvPhone);
final Button edit = new Button(getApplicationContext());
RelativeLayout.LayoutParams rel_lp3 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rel_lp3.addRule(RelativeLayout.ALIGN_RIGHT);
rel_lp3.setMargins(280, 0, 0, 0);
edit.setLayoutParams(rel_lp3);
edit.setTextColor(Color.BLACK);
edit.setText("Edit");
edit.setClickable(true);
relative.addView(edit);

final Button delete = new Button(getApplicationContext());
RelativeLayout.LayoutParams rel_lp4 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rel_lp4.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rel_lp4.setMargins(50, 0, 0, 0);
delete.setLayoutParams(rel_lp4);
delete.setTextColor(Color.BLACK);
delete.setText("Delete");
delete.setClickable(true);
relative.addView(delete);
linearMain.addView(relative);
/**
 * On edit button click EditContact activity is called
 */
edit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(ContactList.this,EditContact.class);
i.putExtra("id", contact.getId());
startActivity(i);
}
});
/**
 * On delete button click selected contact will be deleted.
 */
delete.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new AlertDialog.Builder(ContactList.this)

.setMessage("Are you sure, want to delete this record?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
//---Delete contact from ContactMaster----
myDatabase.deleteContact(contact.getId());
//---Create the dynamic layout again after deletion of record---
linearMain.removeAllViews();
linearMain.invalidate();
AddLayout();
}
}).setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
})

.create().show();
}
});
}

@Override
public void onClick(View v) {
/**
 * Add new contact so called AddContact activity
 */
if(v == btnadd){
Intent i = new Intent(ContactList.this,AddContact.class);
startActivity(i);
}
}
}