Pages

Tuesday 17 April 2012

Learning Content Provider

Following code show how to read contacts and sms from our phone.


package com.myphonebook;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class MyPhoneBookActivity extends Activity implements OnClickListener {
Button btnPhone,btnSMS;
ListView lv;
SimpleCursorAdapter adp;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        btnSMS = (Button) findViewById(R.id.btnSMS);
       
        btnPhone = (Button) findViewById(R.id.btnPhone);
        btnPhone.setOnClickListener(this);
        btnSMS.setOnClickListener(this);
    }
@Override
public void onClick(View v) {

if(v==btnPhone)
{
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)
{
Cursor c = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
while(c.moveToNext())
{
String phone = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d("My Phone Book", " Name : "+name + " Phone : "+phone);
}
}
}
}


}
if(v==btnSMS)
{
Cursor c =  getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
String[] nm = new String[]{"body"};
int[] id = new int[]{R.id.lblMsg};

adp = new SimpleCursorAdapter(this, R.layout.row, c, nm, id);
lv.setAdapter(adp);
}
}
}

No comments:

Post a Comment