I have a ListView in which there are 20 items . 10 items are contacts of my phone and rest of the 10 are bookmars url of my default browser . What i want is that:
1) when i click on the contacts(first 10) it should take me to that partular contact in contact app.
2)when i click on the bookmark url(rest of the 10) , it should open that url in the browser .
I implemented the first requirement of mine with the following code below :
ArrayList<HashMap<String, Object>> listitem = new ArrayList<HashMap<String, Object>>();
mSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
Boolean contact_check = mSharedPrefs.getBoolean("contact_check", true);
Boolean bookmark_check = mSharedPrefs
.getBoolean("bookmark_check", true);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (contact_check) {
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 pCur = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id },
null);
while (pCur.moveToNext()) {
String phoneNo = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", name);
map.put("phone no", phoneNo);
// map.put("Bookmarks", faves.getString(titleIdx));
listitem.add(map);
}
pCur.close();
}
}
}
}
SimpleAdapter listitemAdapter = new SimpleAdapter(this, listitem,
R.layout.list_style, new String[] { "name", "phone no" },
new int[] { R.id.topTextView, R.id.bottomTextView });
lv.setAdapter(listitemAdapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
RelativeLayout lr = (RelativeLayout) arg1;
TextView mText = (TextView) lr.getChildAt(1);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setAction(ContactsContract.Intents.SHOW_OR_CREATE_CONTACT);
i.setData(Uri
.fromParts("tel", mText.getText().toString(), null));
startActivity(i);
}
});
The above code is adding the contacts in my listview on handling the click event .
For my second requirement i extended my listview with bookmarks , with the following code:
String[] requestedColumns = { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
#SuppressWarnings("deprecation")
final Cursor faves = managedQuery(Browser.BOOKMARKS_URI, requestedColumns,
Browser.BookmarkColumns.BOOKMARK + "=1", null, null);
Log.d("Bookmarks", "Bookmarks count: " + faves.getCount());
faves.moveToFirst();
int titleIdx = faves.getColumnIndex(Browser.BookmarkColumns.TITLE);
final int urlIdx = faves.getColumnIndex(Browser.BookmarkColumns.URL);
if (bookmark_check) {
while (!faves.isAfterLast()) {
Log.d("SimpleBookmarks", faves.getString(titleIdx));
Log.d("SimpleBookmarks url", " " + faves.getString(urlIdx));
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", faves.getString(titleIdx));
map.put("phone no", faves.getString(urlIdx));
listitem.add(map);
faves.moveToNext();
}
Its getting populated but i am not able to handle its click event . I want to open the url in the browser when the user click on it.
with some adaptation to your method:
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
if (arg2 < 10)
{
RelativeLayout lr = (RelativeLayout) arg1;
TextView mText = (TextView) lr.getChildAt(1);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setAction(ContactsContract.Intents.SHOW_OR_CREATE_CONTACT);
i.setData(Uri.fromParts("tel", mText.getText().toString(), null));
startActivity(i);
}
else
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getCurrentUri));
//getCurrentUri is the uri at position arg2-10
startActivity(browserIntent);
}
}
});
Related
Contact list are retrieved from Contacts and displayed in listView. When a single contact is clicked from listview it starts a new activity i.e DetailActivity.java(code provided below). I need to show the clicked contact's birthday in DetailActivity's TextView field. How to do it?
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView1 ;
ArrayList<String> nameArray, phoneArray;
ArrayAdapter<String> arrayAdapter;
Cursor cursor, birthdayCur ;
String name, birthday ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
listView1 = (ListView)findViewById(listView);
nameArray = new ArrayList<String>();
GetContactsIntoArrayList();
arrayAdapter = new ArrayAdapter<String>(
MainActivity.this,
R.layout.contact_items,
textView, nameArray
);
listView1.setAdapter(arrayAdapter);
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
String data = (String) adapter.getItemAtPosition(position);
Intent appInfo = new Intent(MainActivity.this, DetailActivity.class);
appInfo.putExtra("data", data);
startActivity(appInfo);
}
});
}
public void GetContactsIntoArrayList(){
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null, null, null);
while (cursor.moveToNext()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
nameArray.add(name);
}
cursor.close();
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
birthdayCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, where, null, null);
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
phoneArray.add(birthday);
}
}
birthdayCur.close();
}
DetailActivity.java
public class DetailActivity extends AppCompatActivity {
TextView tv1, tv2;
String data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent i = getIntent();
data = i.getStringExtra("data");
tv1 = (TextView) findViewById(R.id.name);
tv1.setText(data);
}
you can get the birthday date of contacts, try this:
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));
ContentResolver bd = getContentResolver();
Cursor bdc = bd.query(android.provider.ContactsContract.Data.CONTENT_URI, new String[] { Event.DATA }, android.provider.ContactsContract.Data.CONTACT_ID+" = "+id+" AND "+Data.MIMETYPE+" = '"+Event.CONTENT_ITEM_TYPE+"' AND "+Event.TYPE+" = "+Event.TYPE_BIRTHDAY, null, android.provider.ContactsContract.Data.DISPLAY_NAME);
if (bdc.getCount() > 0) {
while (bdc.moveToNext()) {
String birthday = bdc.getString(0);
// now "id" is the user's unique ID, "name" is his full name and "birthday" is the date and time of his birth
}
}
}
}
cur.close();
I'm new to android and using sqlite rawquery dynamic where clause condition for the first time and didn't know how to use it. I want to give dynamic value to where clause to get the listview according to particular "mid". How to provide the mid value from SubjectActivty
Here is my code:
TestTable:
public long insert(String id, String time, int mid, String cmarks, String nmarks,
String questions, String testType, String test,String marks) {
log("insert test : " + test);
ContentValues values = new ContentValues();
values.put(KEY_TESTID, id);
values.put(KEY_MID,mid);
values.put(KEY_TEST, test);
values.put(KEY_TIME, time);
values.put(KEY_CMARK, cmarks);
values.put(KEY_NMARK, nmarks);
values.put(KEY_TESTTYPE, testType);
values.put(KEY_QUESTION, questions);
values.put(KEY_Total_Marks, marks);
return db.insert(TABLE_NAME2, null, values);
}
public ArrayList<NotificationListItem> getAllList(
ArrayList<NotificationListItem> privateArrayList) {
openToRead();
privateArrayList.clear();
Cursor cursor = null;
String sql ="SELECT * FROm test_list WHERE mid=?";
cursor= db.rawQuery(sql, null);
log("getAlllist() cursor : " + cursor.getCount());
if (cursor != null) {
log("getAlllist() cursor not null ");
int index = 0;
cursor.moveToFirst();
while (index < cursor.getCount()) {
NotificationListItem item = new NotificationListItem();
int idIndex = cursor.getColumnIndex(TestTable.KEY_TESTID);
int subid= cursor.getColumnIndex(TestTable.KEY_MID);
int nameIndex = cursor.getColumnIndex(TestTable.KEY_TEST);
int idTime = cursor.getColumnIndex(TestTable.KEY_TIME);
int cMarks = cursor.getColumnIndex(TestTable.KEY_CMARK);
int nMarks = cursor.getColumnIndex(TestTable.KEY_NMARK);
int testTypeIndex = cursor.getColumnIndex(TestTable.KEY_TESTTYPE);
int questions = cursor.getColumnIndex(TestTable.KEY_QUESTION);
item.name = cursor.getString(nameIndex);
item.testID = cursor.getString(idIndex);
item.mid=cursor.getInt(subid);
item.time = cursor.getString(idTime);
item.cmark = cursor.getString(cMarks);
item.nmark = cursor.getString(nMarks);
item.testType = cursor.getString(testTypeIndex);
item.questions = cursor.getString(questions);
index++;
privateArrayList.add(item);
cursor.moveToNext();
}
log(" query(): cursor closing");
cursor.close();
db.close();
db = null;
}
return privateArrayList;
}
SubjectActvity.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subject);
privateListLV = (ListView) findViewById(R.id.privateListLV);
privatelistTable = new SubjectTable(SubjectActivity.this);
testTableStatic = new StaticTestTable(this);
testTable = new TestTable(SubjectActivity.this);
privatelistTable.openToWrite();
privatelistTable.deleteAll();
privatelistTable.insert(10, "Biology");
privatelistTable.insert(20, "Chemistry");
privatelistTable.insert(30, "English");
privatelistTable.insert(40, "Maths");
privatelistTable.insert(50, "GK");
testTable.openToWrite();
testTable.deleteAll();
testTable.insert("1", "10", 10, "5", "2", "2", "Both", "Anatomy", "10");
testTable.insert("2", "10", 20, "5", "2", "2", "Both", "Paper1", "10");
privateArrayList = new ArrayList<NotificationListItem>();
listAdapter = new SubjectCustomListAdapter(this, privateArrayList,
privatelistTable);
privateListLV.setAdapter(listAdapter);
privateListLV.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> adapter, View arg1,
int position, long arg3) {
NotificationListItem selection = (NotificationListItem) adapter
.getItemAtPosition(position);
String item = selection.getName();
System.out.println("item" +item);
if (!item.contentEquals(" ")) {
subjectid = privatelistTable.getSinlgeEntry(item);
Log.e("selected Value", " " + subjectid);
Intent testact = new Intent(getApplicationContext(),
TestsActivity.class);
testact.putExtra("subject", item);
testact.putExtra("mid",subjectid);
startActivity(testact);
} else {
return;
}
}
});
}
#Override
protected void onResume() {
super.onResume();
updateList();
}
private void updateList() {
privatelistTable.getAllList(privateArrayList);
listAdapter.notifyDataSetChanged();
}
Do as #Der Golem answer OR another way is
Cursor c =db.rawQuery("SELECT * FROM " + tableName + " where mid=" + mid , null);
In my app I am fetching all the bookmarks available in the default browser and populating it in the list view . What i want is that when i click on a particular listItem(bookmark) , It should directly open that bookmark in the default browser .
String[] requestedColumns = { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.VISITS,
Browser.BookmarkColumns.BOOKMARK };
#SuppressWarnings("deprecation")
Cursor faves = managedQuery(Browser.BOOKMARKS_URI, requestedColumns,
Browser.BookmarkColumns.BOOKMARK + "=1", null,
Browser.BookmarkColumns.VISITS);
Log.d("Bookmarks", "Bookmarks count: " + faves.getCount());
int titleIdx = faves.getColumnIndex(Browser.BookmarkColumns.TITLE);
String url[] = new String[] {android.provider.Browser.BookmarkColumns.URL};
Log.d("SimpleBookmarks url", url[0]);
//int url_column_index = faves.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
faves.moveToFirst();
if (bookmark_check) {
while (!faves.isAfterLast()) {
Log.d("SimpleBookmarks", faves.getString(titleIdx));
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("bookmark", faves.getString(titleIdx));
map.put("url", "");
listitem.add(map);
faves.moveToNext();
}
}
Log.v("data", "" + listitem);
SimpleAdapter listitemAdapter = new SimpleAdapter(this, listitem,
R.layout.list_style, new String[] { "bookmark", "url" },
new int[] { R.id.topTextView, R.id.bottomTextView });
lv.setAdapter(listitemAdapter);
Finally got the solution .
String[] requestedColumns = { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
#SuppressWarnings("deprecation")
final Cursor faves = managedQuery(Browser.BOOKMARKS_URI,
requestedColumns, Browser.BookmarkColumns.BOOKMARK + "=1",
null, null);
faves.moveToFirst();
int titleIdx = faves.getColumnIndex(Browser.BookmarkColumns.TITLE);
final int urlIdx = faves.getColumnIndex(Browser.BookmarkColumns.URL);
if (bookmark_check) {
while (!faves.isAfterLast()) {
faves.getString(urlIdx));
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", faves.getString(titleIdx));
map.put("phone no", faves.getString(urlIdx));
listitem.add(map);
faves.moveToNext();
}
}
SimpleAdapter listitemAdapter = new SimpleAdapter(this, listitem,
R.layout.list_style, new String[] { "name", "phone no" },
new int[] { R.id.topTextView, R.id.bottomTextView });
lv.setAdapter(listitemAdapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
RelativeLayout lr = (RelativeLayout) arg1;
TextView mText = (TextView) lr.getChildAt(1);
String st = mText.getText().toString();
if (!st.startsWith("https://") && !st.startsWith("http://")) {
st = "http://" + mText.getText().toString();
}
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(st));
startActivity(i);
}
});
i Have two activities A and B. i used intent to jump from A to B. now in B.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_main);
LoadData();
}
now in LoadData(), i have to load a lot of data, wo i want that when it B starts, it show a Progress bar and after loading the data, it jumps back to my activity B. how can I do this???
here is my load function
public void LoadData(Context context)
{
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
ContentResolver cr = getContentResolver();
// ContactsContract.Contacts.
// Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
// null, null, ContactsContract.Contacts.DISPLAY_NAME);
// Find the ListView resource.
Cursor cur;
cur = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
null,
selection + " AND "
+ ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
null, sortOrder);
mainListView = (ListView) findViewById(R.id.mainListView);
// When item is tapped, toggle checked properties of CheckBox and
// Planet.
mainListView
.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View item,
int position, long id)
{
ContactsList planet = listAdapter.getItem(position);
planet.toggleChecked();
PlanetViewHolder viewHolder = (PlanetViewHolder) item
.getTag();
viewHolder.getCheckBox().setChecked(planet.isChecked());
}
});
// Create and populate planets.
planets = (ContactsList[]) getLastNonConfigurationInstance();
// planets = new Planet[10];
// planets.Add("asdf");
ArrayList<ContactsList> planetList = new ArrayList<ContactsList>();
String phoneNumber = null;
String phoneType = null;
count = cur.getCount();
contacts = new ContactsList[count];
if (planets == null)
{
if (cur.getCount() > 0)
{
planets = new ContactsList[cur.getCount()];
int i = 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
Cursor pCur = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[]
{ id }, null);
// WHILE WE HAVE CURSOR GET THE PHONE NUMERS
while (pCur.moveToNext())
{
// Do something with phones
phoneNumber = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
phoneType = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
Log.i("Pratik", name + "'s PHONE :" + phoneNumber);
Log.i("Pratik", "PHONE TYPE :" + phoneType);
}
pCur.close();
}
if (phoneNumber != null
&& !planetList.contains(new ContactsList(name,
phoneNumber)))
{
planets = new ContactsList[]
{ new ContactsList(name, phoneNumber) };
contacts[i] = planets[0];
planetList.addAll(Arrays.asList(planets));
}
phoneNumber = null;
i++;
}
}
// for (int i = 0; i < count; i++)
// {
// Log.d("New Selected Names : ", contacts[i].getName());
// }
}
// Set our custom array adapter as the ListView's adapter.
listAdapter = new PlanetArrayAdapter(this, planetList);
mainListView.setAdapter(listAdapter);
Adapter adptr;
adptr = mainListView.getAdapter();
}
Please try this
//////////////////////////////////////////////////////////////////
Edit Check It
public class LoadData extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog;
//declare other objects as per your need
#Override
protected void onPreExecute()
{
progressDialog= new ProgressDialog(YourActivity.this);
progressDialog.setTitle("Please Wait..");
progressDialog.setMessage("Loading");
progressDialog.setCancelable(false);
progressDialog.show();
//do initialization of required objects objects here
};
#Override
protected Void doInBackground(Void... params)
{
LoadData();
//do loading operation here
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
progressDialog.dismiss();
};
}
You can call this using
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_main);
LoadData task = new LoadData();
task.execute();
}
for more help read android document
http://developer.android.com/reference/android/os/AsyncTask.html
I am agree with Kanaiya's answer because upto the API level-10 it is fine to call long running tasks on UI thread. But from API-11, any task that takes longer time (nearly more than 5 sec) to complete must be done on background thread. The reason behind this is any task that takes 5 seconds or more on UI thread then ANR(Application Not Responding) i.e. force close happens. To do that we have create some background thread or simply make use of AsyncTask.
You just need to call your LoadData() method in another thread.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_main);
mDailog = ProgressDialog.show(ActivityA.this, "",
"Loading data....!!!", true);
mDailog.show();
new Thread() {
#Override
public void run() {
try {
LoadData();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}.start();
}
Inside your LoadData(), at the end of the method use a handler to send a message to dismiss the progress bar dialog.
Hope this will help you to avoid the complex logic using AsyncTask.
Try this.
public class BActivtiy extends Activity implements Runnable{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_main);
mainListView = (ListView) findViewById(R.id.mainListView);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View item, int position, long id) {
ContactsList planet = listAdapter.getItem(position);
planet.toggleChecked();
PlanetViewHolder viewHolder = (PlanetViewHolder) item.getTag();
viewHolder.getCheckBox().setChecked(planet.isChecked());
}
});
pd = ProgressDialog.show(BActivity.this, "Title", "Description", true);
Thread t = new Thread(BActivity.this);
t.start();
}
public void LoadData() {
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + ("1") + "'";
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
ContentResolver cr = getContentResolver();
Cursor cur;
cur = this.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, selection + " AND " + ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1", null, sortOrder);
// Create and populate planets.
planets = (ContactsList[]) getLastNonConfigurationInstance();
// planets = new Planet[10];
// planets.Add("asdf");
ArrayList<ContactsList> planetList = new ArrayList<ContactsList>();
String phoneNumber = null;
String phoneType = null;
count = cur.getCount();
contacts = new ContactsList[count];
if (planets == null) {
if (cur.getCount() > 0) {
planets = new ContactsList[cur.getCount()];
int i = 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
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
// WHILE WE HAVE CURSOR GET THE PHONE NUMERS
while (pCur.moveToNext()) {
// Do something with phones
phoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
phoneType = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
Log.i("Pratik", name + "'s PHONE :" + phoneNumber);
Log.i("Pratik", "PHONE TYPE :" + phoneType);
}
pCur.close();
}
if (phoneNumber != null && !planetList.contains(new ContactsList(name, phoneNumber))) {
planets = new ContactsList[] { new ContactsList(name, phoneNumber) };
contacts[i] = planets[0];
planetList.addAll(Arrays.asList(planets));
}
phoneNumber = null;
i++;
}
}
// for (int i = 0; i < count; i++)
// {
// Log.d("New Selected Names : ", contacts[i].getName());
// }
}
}
#Override
public void run() {
LoadData();
mHandler.sendEmptyMessage(0);
}
public Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
pd.dismiss();
listAdapter = new PlanetArrayAdapter(BActivtiy.this, planetList);
mainListView.setAdapter(listAdapter);
Adapter adptr;
adptr = mainListView.getAdapter();
}
};
}
This Code shows the List of Contact Numbers, but i want to select cell number from selected contact display name--->
Cursor cursor= managedQuery(intent.getData(), null, null, null, null);
while(cursor.moveToNext()) {
String contactId=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
System.out.println("---------ContactId---------"+contactId);
String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println("---------NAME---------"+name);
String hasPhone=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
System.out.println("---------HAS Phone---------"+hasPhone);
ArrayList one= new ArrayList();
ArrayList two= new ArrayList();
// if(Boolean.parseBoolean(hasPhone)) {
Cursor phones=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+" = "+ contactId, null, null);
while(phones.moveToNext()) {
phoneNumber= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("---------Number---------"+phoneNumber);
one.add(phoneNumber);
System.out.println("---------email Address---------"+one);
} phones.close();
// }
Display Names
public class ContentProviderActivity extends Activity {
ListView lv;
Map<String, List<String>> mymap;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.listContact);
mymap = new HashMap<String, List<String>>();
Uri allContacts = Uri.parse("content://contacts/people/");
Cursor mCursor = managedQuery(allContacts, null, null, null, ContactsContract.Contacts._ID + " ASC");
final String[] contacts = new String[]{ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts._ID};
int [] view = new int[]{R.id.txtName,R.id.txtID};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.main, mCursor, contacts, view);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
//displayContacts(position+1);
int id1 = (int) adapter.getItemId(position);
Intent i = new Intent(getApplicationContext(),ShowContactNo.class);
i.putExtra("ID", id1);
startActivity(i);
}
});
}
}
ShowContactNo: TO display associated contact numbers
public class ShowContactNo extends ListActivity{
Map<String, List<String>> mymap;
String name;
List<String> Phone_No;
String select_Number;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mymap = new HashMap<String, List<String>>();
ListView listView = getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_NONE);
Intent i = getIntent();
int position = i.getIntExtra("ID", 0);
displayContacts(position);
Phone_No = new ArrayList<String>();
Phone_No = mymap.get(name);
System.out.println(Phone_No);
if(Phone_No!=null)
{
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, Phone_No));
}
final String [] items = new String [] {"Make Call", "Send Text SMS"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Option");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
if (item == 0) {
Intent i = new
Intent(android.content.Intent.ACTION_CALL,
Uri.parse("tel:"+select_Number));
startActivity(i);
dialog.cancel();
} else {
Intent i = new
Intent(android.content.Intent.ACTION_SENDTO,
Uri.parse("smsto:"+select_Number));
i.putExtra("sms_body", "Krishnakant Dalal");
startActivity(i);
}
}
} );
final AlertDialog dialog = builder.create();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
select_Number = String.valueOf(Phone_No.get(arg2));
dialog.show();
}
});
}
private void displayContacts(int position) {
if(position!=0)
{
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, ContactsContract.Contacts._ID +" = ?",
new String[]{String.valueOf(position)}, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
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);
List<String> numberlist = new ArrayList<String>();
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Toast.makeText(this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
numberlist.add(phoneNo);
}
pCur.close();
mymap.put(name, numberlist);
}
}
}
}
}
}
Dont forget to add Permissions:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
Try this,
public void getPhoneNumber(String conatctname)
{
try
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
FirstName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if(FirstName!=null)
{
try
{
String[] splitval=FirstName.split(" ");
if(splitval.length>=1)
{
FirstName=splitval[0];
if(FirstName.equals(conatctname))
{
if(Integer.parseInt(cursor.getString(cursor.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())
{
PhoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
PhoneNumberArray.add(PhoneNumber);
}
pCur.close();
}
}
}
catch(Exception error)
{
Log.d("SplitError", error.getMessage());
}
}
cursor.close();
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
}