Android 2.1 How to get Phone Numbers of contacts [duplicate] - java

I'm using this code to retrieve all contact names and phone numbers:
String[] projection = new String[]
{
People.NAME,
People.NUMBER
};
Cursor c = ctx.getContentResolver().query(People.CONTENT_URI, projection, null, null, People.NAME + " ASC");
c.moveToFirst();
int nameCol = c.getColumnIndex(People.NAME);
int numCol = c.getColumnIndex(People.NUMBER);
int nContacts = c.getCount();
do
{
// Do something
} while(c.moveToNext());
However, this will only return the primary number for each contact, but I want to get the secondary numbers as well. How can i do this?

Following code shows an easy way to read all phone numbers and names:
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
NOTE: getContentResolver is a method from the Activity context.

You can read all of the telephone numbers associated with a contact in the following manner:
Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, personId);
Uri phonesUri = Uri.withAppendedPath(personUri, People.Phones.CONTENT_DIRECTORY);
String[] proj = new String[] {Phones._ID, Phones.TYPE, Phones.NUMBER, Phones.LABEL}
Cursor cursor = contentResolver.query(phonesUri, proj, null, null, null);
Please note that this example (like yours) uses the deprecated contacts API. From eclair onwards this has been replaced with the ContactsContract API.

This code shows how to get all phone numbers for each contact.
ContentResolver cr = getActivity().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 pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
int phoneType = pCur.getInt(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.TYPE));
String phoneNumber = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
switch (phoneType) {
case Phone.TYPE_MOBILE:
Log.e(name + "(mobile number)", phoneNumber);
break;
case Phone.TYPE_HOME:
Log.e(name + "(home number)", phoneNumber);
break;
case Phone.TYPE_WORK:
Log.e(name + "(work number)", phoneNumber);
break;
case Phone.TYPE_OTHER:
Log.e(name + "(other number)", phoneNumber);
break;
default:
break;
}
}
pCur.close();
}
}
}

In case it helps, I've got an example that uses the ContactsContract API to first find a contact by name, then it iterates through the details looking for specific number types:
How to use ContactsContract to retrieve phone numbers and email addresses

You can get all phone contacts using this:
Cursor c = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.RawContacts.ACCOUNT_TYPE },
ContactsContract.RawContacts.ACCOUNT_TYPE + " <> 'google' ",
null, null);
check complete example HERE...........

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 <span id="IL_AD4" class="IL_AD">phone
// number</span>
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();

Accepted answer working but not given unique numbers.
See this code, it return unique numbers.
public static void readContacts(Context context) {
if (context == null)
return;
ContentResolver contentResolver = context.getContentResolver();
if (contentResolver == null)
return;
String[] fieldListProjection = {
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
ContactsContract.Contacts.HAS_PHONE_NUMBER
};
Cursor phones = contentResolver
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
, fieldListProjection, null, null, null);
HashSet<String> normalizedNumbersAlreadyFound = new HashSet<>();
if (phones != null && phones.getCount() > 0) {
while (phones.moveToNext()) {
String normalizedNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));
if (Integer.parseInt(phones.getString(phones.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
if (normalizedNumbersAlreadyFound.add(normalizedNumber)) {
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d("test", " Print all values");
}
}
}
phones.close();
}
}

In the same way just get their other numbers using the other "People" references
People.TYPE_HOME
People.TYPE_MOBILE
People.TYPE_OTHER
People.TYPE_WORK

This one finally gave me the answer I was looking for. It lets you retrieve all the names and phone numbers of the contacts on the phone.
package com.test;
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 != null && cur.getCount() > 0) {
while (cur.moveToNext()) {
if (Integer.parseInt.equals(cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)))) {
String id = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
int i = 0;
int pCount = pCur.getCount();
String[] phoneNum = new String[pCount];
String[] phoneType = new String[pCount];
while (pCur != null && pCur.moveToNext()) {
phoneNum[i] = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneType[i] = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.TYPE));
i++;
}
}
}
}
}
}

I fixed my need belove
manifest permissions
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<!-- Read Contacts from phone -->
<uses-permission android:name="android.permission.read_contacts" />
<uses-permission android:name="android.permission.read_phone_state" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
Note: After giving permissions at manifest some mobile phones can deny if so you need to go Settings--> Applications--> find your application click on it and
turn On the permissions needed
btn_readallcontacks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
List<User> userList = new ArrayList<User>();
while (phones.moveToNext()) {
User user = new User();
user.setNamee(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
user.setPhone(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
userList.add(user);
Log.d(TAG, "Name : " + user.getNamee().toString());
Log.d(TAG, "Phone : " + user.getPhone().toString());
}
phones.close();
}
});

You can get all the contact all those which have no number and all those which have no name from this piece of code
public void readContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY + " ASC");
ContactCount = cur.getCount();
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));
String phone = null;
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()) {
phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("phone" + phone);
}
pCur.close();
}
if (phone == "" || name == "" || name.equals(phone)) {
if (phone.equals(""))
getAllContact.add(new MissingPhoneModelClass("No Number", name, id));
if (name.equals("") || name.equals(phone))
getAllContact.add(new MissingPhoneModelClass(phone, "No Name", id));
} else {
if(TextUtils.equals(phone,null)){
getAllContact.add(new MissingPhoneModelClass("No Number", name, id));
}
else {
getAllContact.add(new MissingPhoneModelClass(phone, name, id));
}
}
}
}
}
One thing can be done you have to give the permission in the manifest for contact READ and WRITE
After that you can create the model class for the list which can be use to add all the contact here is the model class
public class PhoneModelClass {
private String number;
private String name;
private String id;
private String rawId;
public PhoneModelClass(String number, String name, String id, String rawId) {
this.number = number;
this.name = name;
this.id = id;
this.rawId = rawId;
}
public PhoneModelClass(String number, String name, String id) {
this.number = number;
this.name = name;
this.id = id;
}
public String getRawId() {
return rawId;
}
public void setRawId(String rawId) {
this.rawId = rawId;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Enjoy :)

Load contacts in background using CursorLoader:
CursorLoader cursor = new CursorLoader(this, ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
Cursor managedCursor = cursor.loadInBackground();
int number = managedCursor.getColumnIndex(ContactsContract.Contacts.Data.DATA1);
int name = managedCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int index = 0;
while (managedCursor.moveToNext()) {
String phNumber = managedCursor.getString(number);
String phName = managedCursor.getString(name);
}

Here's how to use ContentsContract API to fetch your contacts in your Phone Book.
You'll need to add these permissions in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
Then, you can run this method to loop through all your contacts.
Here's an example to query fields like Name and Phone Number, you can configure yourself to use CommonDataKinds, it query other fields in your Contact.
https://developer.android.com/reference/android/provider/ContactsContract.CommonDataKinds
private fun readContactsOnDevice() {
val context = requireContext()
if (ContextCompat.checkSelfPermission(
context, Manifest.permission.WRITE_CONTACTS
) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(
context, Manifest.permission.READ_CONTACTS
) != PackageManager.PERMISSION_GRANTED
) {
requestPermissions(
arrayOf(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS), 1
)
return
}
val contentResolver = context.contentResolver
val contacts = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null
)
while (contacts?.moveToNext() == true) {
val name = contacts.getString(
contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
)
val phoneNumber = contacts.getString(
contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
)
Timber.i("Name: $name, Phone Number: $phoneNumber")
}
}

package com.example.readcontacts;
import java.util.ArrayList;
import android.app.Activity; import android.app.ProgressDialog;
import android.content.ContentResolver; import
android.database.Cursor; import android.net.Uri; import
android.os.Bundle; import android.os.Handler; import
android.provider.ContactsContract; import android.view.View; import
android.widget.AdapterView; import
android.widget.AdapterView.OnItemClickListener; import
android.widget.ArrayAdapter; import android.widget.ListView; import
android.widget.Toast;
public class MainActivity extends Activity { private ListView
mListView; private ProgressDialog pDialog; private Handler
updateBarHandler;
ArrayList<String> contactList; Cursor cursor; int counter;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(this); pDialog.setMessage("Reading
contacts..."); pDialog.setCancelable(false); pDialog.show();
mListView = (ListView) findViewById(R.id.list); updateBarHandler
=new Handler();
// Since reading contacts takes more time, let's run it on a separate thread. new Thread(new Runnable() {
#Override public void run() {
getContacts(); } }).start();
// Set onclicklistener to the list item.
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> parent, View
view,
int position, long id) {
//TODO Do whatever you want with the list data
Toast.makeText(getApplicationContext(), "item clicked : \n"+contactList.get(position), Toast.LENGTH_SHORT).show(); }
}); }
public void getContacts() {
contactList = new ArrayList<String>();
String phoneNumber = null; String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI; String
_ID = ContactsContract.Contacts._ID; String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME; String HAS_PHONE_NUMBER =
ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI =
ContactsContract.CommonDataKinds.Phone.CONTENT_URI; String
Phone_CONTACT_ID =
ContactsContract.CommonDataKinds.Phone.CONTACT_ID; String NUMBER =
ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI =
ContactsContract.CommonDataKinds.Email.CONTENT_URI; String
EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null,null, null,
null);
// Iterate every contact in the phone if (cursor.getCount() > 0)
{
counter = 0; while (cursor.moveToNext()) {
output = new StringBuffer();
// Update the progress message
updateBarHandler.post(new Runnable() {
public void run() {
pDialog.setMessage("Reading contacts : "+ counter++ +"/"+cursor.getCount());
}
});
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(
HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
//This is to read multiple phone numbers associated with the same contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
// Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID+ " =
?", new String[] { contact_id }, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\n Email:" + email);
}
emailCursor.close();
}
// Add the contact to the ArrayList
contactList.add(output.toString()); }
// ListView has to be updated using a ui thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item,
R.id.text1, contactList);
mListView.setAdapter(adapter);
} });
// Dismiss the progressbar after 500 millisecondds
updateBarHandler.postDelayed(new Runnable() {
#Override
public void run() {
pDialog.cancel();
} }, 500); }
}
}
List item

Code to get contact name (Ascending order) and number
For more reference: show contact in listview
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" ASC");
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();

Related

database records not updating android studio , sql-lite

Could someone help me? my records are not updating.
I guess the edittext stay the same but not too sure.
How to change the view values that is being put in the edittext to change to the values in updating edittexts.
Would appreciate some help with this
Thank you.
DatabaseManager
public Cursor selectRow(String ID) {
String query = "Select * from " + TABLE_NAME + " where studentID = " + ID;
Cursor cursor = db.rawQuery(query, null);
return cursor;
}
public boolean updateData(String id, String fn, String ln, String ge, String cs, String a, String loc) {
ContentValues contentValues = new ContentValues();
contentValues.put("studentID", id);
contentValues.put("first_name", fn);
contentValues.put("last_name", ln);
contentValues.put("gender", ge);
contentValues.put("course_study", cs);
contentValues.put("age", a);
contentValues.put("location", loc);
db.update(TABLE_NAME, contentValues, "studentID = ?", new String[]{id});
return true;
}
The above is parts of my database that I use in this activity.
activity main.java
private void UpdateData() {
u.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
uptable.setVisibility(View.VISIBLE);
again.setVisibility(View.VISIBLE);
Cursor res = mydManager.selectRow(text);
if (res != null && res.moveToFirst()) {
String id = Integer.toString(res.getInt(0));
String nme = res.getString(1);
String lnme = res.getString(2);
String gen = res.getString(3);
String corse = res.getString(4);
String ag = Integer.toString(res.getInt(5));
String lo = res.getString(6);
studid.setText(id);
fname.setText(nme);
lname.setText(lnme);
gender.setText(gen);
course.setText(corse);
age.setText(ag);
loc.setText(lo);
}
}
}
);
}
public void UpdateData1() {
again.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
uptable.setVisibility(View.GONE);
String id = studid.getText().toString();
String nme = fname.getText().toString();
String lnme = lname.getText().toString();
String gen = gender.getText().toString();
String corse = course.getText().toString();
String ag = age.getText().toString();
String lo = loc.getText().toString();
boolean isUpdated = mydManager.updateData(id, nme , lnme, gen, corse ,ag , lo);
if (isUpdated == true)
Toast.makeText(Main4Activity.this, "Data Updated", Toast.LENGTH_LONG).show();
else
Toast.makeText(Main4Activity.this, "Data Not Updated", Toast.LENGTH_LONG).show();
}
}
);
}
I tried having a button to set the data but it still stays the same.
Sorry din't read the code, take the sample if it helps
Just the logic..
public long updateNote(NoteModel noteModel) {
if (LOG_DEBUG) UtilLogger.showLogUpdate(TAG, noteModel, noteModel.getRow_pos());
long updatedRow = 0;
try {
ContentValues contentValues = new ContentValues();
contentValues.put(DBSchema.DB_TITLE, noteModel.getTitle());
contentValues.put(DBSchema.DB_IMAGE_PATH, noteModel.getImgUriPath());
contentValues.put(DBSchema.DB_SUB_TEXT, noteModel.getSub_text());
contentValues.put(DBSchema.DB_CREATE_DATE, noteModel.getCreateDate());
contentValues.put(DBSchema.DB_UPDATE_DATE, noteModel.getUpdateDate());
contentValues.put(DBSchema.DB_SCHEDULED_TIME_LONG, noteModel.getScheduleTimeLong());
contentValues.put(DBSchema.DB_SCHEDULED_TIME_WHEN, noteModel.getScheduledWhenLong());
contentValues.put(DBSchema.DB_SCHEDULED_TITLE, noteModel.getScheduledTitle());
contentValues.put(DBSchema.DB_IS_ALARM_SCHEDULED, noteModel.getIsAlarmScheduled());
contentValues.put(DBSchema.DB_IS_TASK_DONE, noteModel.getIsTaskDone());
contentValues.put(DBSchema.DB_IS_ARCHIVED, noteModel.getIsArchived());
updatedRow = mSqLiteDatabase.updateWithOnConflict(
DBSchema.DB_TABLE_NAME,
contentValues,
DBSchema.DB_ROW_ID + " =?", new String[]{String.valueOf(noteModel.get_id())}, mSqLiteDatabase.CONFLICT_REPLACE);
return updatedRow;
} catch (SQLException e) {
e.printStackTrace();
}
return updatedRow;
}
then take the cursor
public Cursor getCursorForAlarmScheduled(String passAlarmScheduledStatus) {
if (LOG_DEBUG)
Log.w(TAG, " pick all record with alarmScheduled 1 : " + passAlarmScheduledStatus);
return mSqLiteDatabase.rawQuery(DBSchema.DB_SELECT_ALL +
" WHERE " + DBSchema.DB_IS_ALARM_SCHEDULED + " = " + passAlarmScheduledStatus, null);
}
and then extract
//common operation for all,
public static List<NoteModel> extractCommonData(Cursor cursor, List<NoteModel> noteModelList) {
noteModelList = new ArrayList<>();
if (LOG_DEBUG) Log.i(TAG, "inside extractCommonData()");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
NoteModel noteModel = new NoteModel();
noteModel.set_id(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_ROW_ID)));
noteModel.setTitle(cursor.getString(cursor.getColumnIndex(DBSchema.DB_TITLE)));
noteModel.setImgUriPath(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IMAGE_PATH)));
noteModel.setSub_text(cursor.getString(cursor.getColumnIndex(DBSchema.DB_SUB_TEXT)));
noteModel.setCreateDate(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_CREATE_DATE)));
noteModel.setUpdateDate(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_UPDATE_DATE)));
noteModel.setScheduleTimeLong(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TIME_LONG)));
noteModel.setScheduledWhenLong(cursor.getLong(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TIME_WHEN)));
noteModel.setScheduledTitle(cursor.getString(cursor.getColumnIndex(DBSchema.DB_SCHEDULED_TITLE)));
noteModel.setIsAlarmScheduled(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_ALARM_SCHEDULED)));
noteModel.setIsTaskDone(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_TASK_DONE)));
noteModel.setIsArchived(cursor.getInt(cursor.getColumnIndex(DBSchema.DB_IS_ARCHIVED)));
noteModelList.add(noteModel);
} while (cursor.moveToNext());
}
cursor.close();
}
return noteModelList;
}
Again, I din't read,just copied from my old samples
Please do find the needful, cheers

not getting songs from album

I was trying to get songs from album in my app. I wrote code below with some help on internet but now I'm getting all items as 0. I dont know why I'm getting 0.
public void songs()
{
String name;
long genreId;
Uri uri;
Cursor genrecursor;
Cursor tempcursor;
String[] proj1 = { android.provider.MediaStore.Audio.Albums._ID,
android.provider.MediaStore.Audio.Albums.ALBUM};
String[] proj2 = {MediaStore.Audio.Media.DISPLAY_NAME,MediaStore.Audio.Media.ALBUM_ID
,MediaStore.Audio.Media.DATA};
genrecursor = managedQuery(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, proj1, null, null, null);
if (genrecursor.moveToFirst()) {
do {
name = String.valueOf(genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM));
Log.i("Tag-album name", genrecursor.getString(Integer.parseInt(name)));
name = String.valueOf(genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Albums._ID));
genreId = Long.parseLong(genrecursor.getString(Integer.parseInt(name)));
uri = MediaStore.Audio.Genres.Members.getContentUri("external", genreId);
tempcursor = managedQuery(uri, proj2, null, null, null);
Log.i("Tag-Number of songs for this album", tempcursor.getCount() + "");
if (tempcursor.moveToFirst()) {
do {
name = String.valueOf(tempcursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
String art = String.valueOf(tempcursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
String path = String.valueOf(tempcursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
Log.i("Tag-Song name", tempcursor.getString(Integer.parseInt(name)));
albumInfo s = new albumInfo(name,art,path);
albumSongList.add(s);
} while (tempcursor.moveToNext());
}
} while (genrecursor.moveToNext());
}
}
i did this.
Uri uri= MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
String[] columns = {
MediaStore.Audio.Albums.ALBUM};
Cursor cursor =getApplicationContext().getContentResolver().
query(uri, columns, null,
null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
Log.v("bbb",
cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Albums.ALBUM)));
v=cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Albums.ALBUM));
} while (cursor.moveToNext());
}
// I want to list down song in album Rolling Papers (Deluxe Version)
String[] column = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.DISPLAY_NAME,
};
Intent i=getIntent();
final String value=i.getStringExtra("sol");
String [] x=new String[]{value};
String where = MediaStore.Audio.Albums.ALBUM + "=?";
Log.e("syn",v);
String whereVal[] = {v};
String orderBy = android.provider.MediaStore.Audio.Media.TITLE;
cursor =getApplicationContext().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
column, where, x,null);
if (cursor != null && cursor.moveToFirst()) {
do {
Log.v("Vipul",
cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
String name=cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
String art=cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
String path=cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
albumInfo s = new albumInfo(name,art,path); // EXCLUDED
albumSongList.add(s);
} while (cursor.moveToNext());
}
}

android-make whatsapp call

I want to make a WhatsApp call to a specific user. I tried this and it doesn't work:
Uri uri = Uri.parse("callto:" + phoneNUmber);
Intent i = new Intent(Intent.ACTION_CALL, uri);
i.setPackage("com.whatsapp");
startActivity(i);
I know how to create a WhatsApp message, the code is similar and it works:
Uri uri = Uri.parse("smsto:" + phoneNUmber);
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.setPackage("com.whatsapp");
startActivity(i);
Simple solution is, Query ContactContract.Data for the _id and MIME type.
ContentResolver resolver = context.getContentResolver();
cursor = resolver.query(
ContactsContract.Data.CONTENT_URI,
null, null, null,
ContactsContract.Contacts.DISPLAY_NAME);
//Now read data from cursor like
while (cursor.moveToNext()) {
long _id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data._ID));
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
String mimeType = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
Log.d("Data", _id+ " "+ displayName + " " + mimeType );
}
The output will be like the following
12561 Snow vnd.android.cursor.item/vnd.com.whatsapp.profile
12562 Snow vnd.android.cursor.item/vnd.com.whatsapp.voip.call
Now save in DB or somewhere else only those _Ids whose MIME type is vnd.android.cursor.item/vnd.com.whatsapp.voip.call
And then you initiate Whatsapp call with those contacts like this way
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
// the _ids you save goes here at the end of /data/12562
intent.setDataAndType(Uri.parse("content://com.android.contacts/data/_id"),
"vnd.android.cursor.item/vnd.com.whatsapp.voip.call");
intent.setPackage("com.whatsapp");
startActivity(intent);
To make WhatsApp video call use below mime-string:
String mimeString = "vnd.android.cursor.item/vnd.com.whatsapp.video.call";
To make WhatsApp voice call use below mime-string:
String mimeString = "vnd.android.cursor.item/vnd.com.whatsapp.voip.call";
Use Below Code:
String displayName = null;
String name="ABC" // here you can give static name.
Long _id;
ContentResolver resolver = getApplicationContext().getContentResolver();
cursor = resolver.query(ContactsContract.Data.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME);
while (cursor.moveToNext()) {
_id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data._ID));
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
String mimeType = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
if (displayName.equals(name)) {
if (mimeType.equals(mimeString)) {
String data = "content://com.android.contacts/data/" + _id;
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_VIEW);
sendIntent.setDataAndType(Uri.parse(data), mimeString);
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
}
}
}
this code is to check number has whatsapp or not and make whatsapp audio and video call
first check wether number have whatsapp or not ...if you dont know
if rowContactId (return type of hasWhatsapp) is not equal to '0' then this number has whatsapp.
.
public String hasWhatsapp( getContactIDFromNumber(795486179).toString(),MAinactivity.this )
{
String rowContactId = null;
boolean hasWhatsApp;
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.Data.CONTACT_ID + " = ? AND account_type IN (?)";
String[] selectionArgs = new String[]{contactID, "com.whatsapp"};
Cursor cursor = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
if (cursor != null) {
hasWhatsApp = cursor.moveToNext();
if (hasWhatsApp) {
rowContactId = cursor.getString(0);
}
cursor.close();
}
return rowContactId;
}
public static int getContactIDFromNumber( contactNumber,Context context)
{
contactNumber = Uri.encode(contactNumber);
int phoneContactID = new Random().nextInt();
Cursor contactLookupCursor = context.getContentResolver().query(Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,contactNumber),new String[] {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID}, null, null, null);
while(contactLookupCursor.moveToNext())
{
phoneContactID = contactLookupCursor.getInt(contactLookupCursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
}
contactLookupCursor.close();
return phoneContactID;
}
//your number is support for whatsapp then come to here to make whatsapp call
// this is for whatsapp call
wtsapp_call.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String mimeString = "vnd.android.cursor.item/vnd.com.whatsapp.voip.call";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
//here you have to pass whatsApp contact number as contact_number ..
String name= getContactName( contact_number, MainActivity.this);
int whatsappcall=getContactIdForWhatsAppCall(name,MainActivity.this);
if (whatsappcall!=0) {
intent.setDataAndType(Uri.parse("content://com.android.contacts/data/" +whatsappcall),
"vnd.android.cursor.item/vnd.com.whatsapp.voip.call");
intent.setPackage("com.whatsapp");
startActivityForResult(intent, WHATSAPP_NUMMBER);
}
}
});
//for whatsapp video call
wtsapp_video.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
//here you have to pass whatsApp contact number as number..
String name= getContactName( number, MainActivity.this);
int videocall=getContactIdForWhatsAppVideoCall(name,MainActivity.this);
if (videocall!=0)
{
intent.setDataAndType(Uri.parse("content://com.android.contacts/data/" +videocall),
"vnd.android.cursor.item/vnd.com.whatsapp.video.call");
intent.setPackage("com.whatsapp");
startActivity(intent);
}
}
});
public String getContactName(final String phoneNumber, Context context)
{
Uri uri=Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phoneNumber));
String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME};
String contactName="";
Cursor cursor=context.getContentResolver().query(uri,projection,null,null,null);
if (cursor != null) {
if(cursor.moveToFirst()) {
contactName=cursor.getString(0);
}
cursor.close();
}
return contactName;
}
public int getContactIdForWhatsAppCall(String name,Context context)
{
cursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[]{ContactsContract.Data._ID},
ContactsContract.Data.DISPLAY_NAME + "=? and "+ContactsContract.Data.MIMETYPE+ "=?",
new String[] {name,"vnd.android.cursor.item/vnd.com.whatsapp.voip.call"},
ContactsContract.Contacts.DISPLAY_NAME);
if (cursor.getCount()>0)
{
cursor.moveToNext();
int phoneContactID= cursor.getInt(cursor.getColumnIndex(ContactsContract.Data._ID));
System.out.println("9999999999999999 name "+name+" id "+phoneContactID);
return phoneContactID;
}
else
{
System.out.println("8888888888888888888 ");
return 0;
}
}
public int getContactIdForWhatsAppVideoCall(String name,Context context)
{
Cursor cursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[]{ContactsContract.Data._ID},
ContactsContract.Data.DISPLAY_NAME + "=? and "+ContactsContract.Data.MIMETYPE+ "=?",
new String[] {name,"vnd.android.cursor.item/vnd.com.whatsapp.video.call"},
ContactsContract.Contacts.DISPLAY_NAME);
if (cursor.getCount()>0)
{
cursor.moveToFirst();
int phoneContactID= cursor.getInt(cursor.getColumnIndex(ContactsContract.Data._ID));
return phoneContactID;
}
else
{
System.out.println("8888888888888888888 ");
return 0;
}
}
If we pass rawContactId, then we can use that to directly fetch the ID associated with the whatsapp call URI.
private void whatsAppCall(Context context, String rawContactId) {
try {
int id = whatsAppCallId(context, rawContactId);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
String uriString = "content://com.android.contacts/data/" + id;
intent.setDataAndType(Uri.parse(uriString), "vnd.android.cursor.item/vnd.com.whatsapp.voip.call");
intent.setPackage("com.whatsapp");
startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "whatsAppCall Exception: " + e);
}
}
private long whatsAppCallId(Context context, String rawContactId){
ContentResolver resolver = context.getContentResolver();
String selection = ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.Data.RAW_CONTACT_ID + " = ? ";
String[] selectionArgs = new String[] { "vnd.android.cursor.item/vnd.com.whatsapp.voip.call", rawContactId };
Cursor cursor = resolver.query(
ContactsContract.Data.CONTENT_URI,
null, selection, selectionArgs,
ContactsContract.Contacts.DISPLAY_NAME);
long _id=0;
while (cursor.moveToNext()) {
_id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data._ID));
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
String mimeType = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
Log.d(TAG, "Data: " + _id+ " "+ displayName + " " + mimeType );
}
return _id;
}
Answer provided by #Adnan Khan works in Android 11, but I wanted to provide the Kotlin version of his answer:
val resolver: ContentResolver = requireContext().contentResolver
val cursor: Cursor? = resolver.query(
ContactsContract.Data.CONTENT_URI,
null, null, null,
ContactsContract.Contacts.DISPLAY_NAME)
while(cursor!!.moveToNext()) {
val _id: Long = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data._ID))
val displayName: String = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME))
val mimeType: String = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE))
Log.i("Intents", "$_id $displayName $mimeType")
Now, the intent in Kotlin goes like this:
_id is the value you get from the previous routing
val intent = Intent()
intent.action = Intent.ACTION_VIEW
intent.setDataAndType(Uri.parse("content://com.android.contacts/data/_id"),
"vnd.android.cursor.item/vnd.com.whatsapp.voip.call")
intent.setPackage("com.whatsapp")
startActivity(intent)
Last but not least add the following to the AndroidManifest.xml:
<uses-permission
android:name="android.permission.CALL_PHONE"
androd:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.READ_CONTACTS"
androd:maxSdkVersion="30" />
After this, you need to go to Settings -> Apps -> Select your app and mark the two permissions as allowed.
There should be a way that the app ask you the first time it is run, but that is another topic.
// first check wether number have whatsapp or not ...if you dont know
//if rowContactId (return type of hasWhatsapp) is not equal to '0' then this number has whatsapp..
public String hasWhatsapp( getContactIDFromNumber(795486179).toString(),MAinactivity.this )
{
String rowContactId = null;
boolean hasWhatsApp;
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.Data.CONTACT_ID + " = ? AND account_type IN (?)";
String[] selectionArgs = new String[]{contactID, "com.whatsapp"};
Cursor cursor = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
if (cursor != null) {
hasWhatsApp = cursor.moveToNext();
if (hasWhatsApp) {
rowContactId = cursor.getString(0);
}
cursor.close();
}
return rowContactId;
}
public static int getContactIDFromNumber( contactNumber,Context context)
{
contactNumber = Uri.encode(contactNumber);
int phoneContactID = new Random().nextInt();
Cursor contactLookupCursor = context.getContentResolver().query(Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,contactNumber),new String[] {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID}, null, null, null);
while(contactLookupCursor.moveToNext())
{
phoneContactID = contactLookupCursor.getInt(contactLookupCursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
}
contactLookupCursor.close();
return phoneContactID;
}
//your number is support for whatsapp then come to here to make whatsapp call
// this is for whatsapp call
wtsapp_call.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String mimeString = "vnd.android.cursor.item/vnd.com.whatsapp.voip.call";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
//here you have to pass whatsApp contact number as contact_number ..
String name= getContactName( contact_number, MainActivity.this);
int whatsappcall=getContactIdForWhatsAppCall(name,MainActivity.this);
if (whatsappcall!=0) {
intent.setDataAndType(Uri.parse("content://com.android.contacts/data/" +whatsappcall),
"vnd.android.cursor.item/vnd.com.whatsapp.voip.call");
intent.setPackage("com.whatsapp");
startActivityForResult(intent, WHATSAPP_NUMMBER);
}
}
});
//for whatsapp video call
wtsapp_video.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
//here you have to pass whatsApp contact number as number..
String name= getContactName( number, MainActivity.this);
int videocall=getContactIdForWhatsAppVideoCall(name,MainActivity.this);
if (videocall!=0)
{
intent.setDataAndType(Uri.parse("content://com.android.contacts/data/" +videocall),
"vnd.android.cursor.item/vnd.com.whatsapp.video.call");
intent.setPackage("com.whatsapp");
startActivity(intent);
}
}
});
public String getContactName(final String phoneNumber, Context context)
{
Uri uri=Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phoneNumber));
String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME};
String contactName="";
Cursor cursor=context.getContentResolver().query(uri,projection,null,null,null);
if (cursor != null) {
if(cursor.moveToFirst()) {
contactName=cursor.getString(0);
}
cursor.close();
}
return contactName;
}
public int getContactIdForWhatsAppCall(String name,Context context)
{
cursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[]{ContactsContract.Data._ID},
ContactsContract.Data.DISPLAY_NAME + "=? and "+ContactsContract.Data.MIMETYPE+ "=?",
new String[] {name,"vnd.android.cursor.item/vnd.com.whatsapp.voip.call"},
ContactsContract.Contacts.DISPLAY_NAME);
if (cursor.getCount()>0)
{
cursor.moveToNext();
int phoneContactID= cursor.getInt(cursor.getColumnIndex(ContactsContract.Data._ID));
System.out.println("9999999999999999 name "+name+" id "+phoneContactID);
return phoneContactID;
}
else
{
System.out.println("8888888888888888888 ");
return 0;
}
}
public int getContactIdForWhatsAppVideoCall(String name,Context context)
{
Cursor cursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[]{ContactsContract.Data._ID},
ContactsContract.Data.DISPLAY_NAME + "=? and "+ContactsContract.Data.MIMETYPE+ "=?",
new String[] {name,"vnd.android.cursor.item/vnd.com.whatsapp.video.call"},
ContactsContract.Contacts.DISPLAY_NAME);
if (cursor.getCount()>0)
{
cursor.moveToFirst();
int phoneContactID= cursor.getInt(cursor.getColumnIndex(ContactsContract.Data._ID));
return phoneContactID;
}
else
{
System.out.println("8888888888888888888 ");
return 0;
}
}
iv_whatsapp_call.setOnClickListener {
// val dialIntent = Intent(Intent.ACTION_DIAL)
// dialIntent.data = Uri.parse("tel:" + et_whatsapp.text.toString())
// startActivity(dialIntent)
val mimeString = "vnd.android.cursor.item/vnd.com.whatsapp.voip.call"
val resolver: ContentResolver = applicationContext.contentResolver
val cursor: Cursor? = resolver.query(ContactsContract.Data.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME)
while(cursor!!.moveToNext()) {
var Col_Index = cursor!!.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)
val _id = cursor.getLong(Col_Index)
Col_Index = cursor!!.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
var number = cursor.getString(Col_Index)
Col_Index = cursor!!.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
val displayName = cursor.getString(Col_Index)
Col_Index = cursor!!.getColumnIndex(ContactsContract.CommonDataKinds.Phone.MIMETYPE)
val mimeType = cursor.getString(Col_Index)
// println("Data: " + _id.toString() + " ---" + displayName + "---" + number + "---" + mimeType )
var my_number = et_whatsapp.text.toString()
my_number = my_number.replace(" ","")
my_number = my_number.replace("+","")
if(number.isNullOrBlank() == false) {
// println("Number : " + number )
number = number.replace(" ", "")
number = number.replace("+", "")
// my_number.substring(1)
// println(">>" + my_number)
if (number.endsWith(my_number.substring(1) + "#s.whatsapp.net")){
if (mimeType.equals(mimeString)) {
val data = "content://com.android.contacts/data/$_id"
val sendIntent = Intent()
sendIntent.action = Intent.ACTION_VIEW
sendIntent.setDataAndType(Uri.parse(data), mimeString)
sendIntent.setPackage("com.whatsapp")
startActivity(sendIntent)
break;
}
}
}
}
}

How to retrieve "ME" contact details coming in Contact list of Android phone

I am developing an app,which will use phoneOwner details(like name, phoneNo, Email Id etc) which is coming under "ME" header of Contact List.
Is there any way to get all these details?
This code will retrive all contactDetails of all contact Inside ContactList
public class MainActivity extends Activity {
TextView textDetail;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textDetail = (TextView) findViewById(R.id.textView1);
readContacts();
}
public void readContacts() {
StringBuffer sb = new StringBuffer();
sb.append("your contacts");
ContentResolver content = getContentResolver();
Cursor c = content.query(ContactsContract.Contacts.CONTENT_URI, null,null, null, null);
String phone = null;
String emailContact = null;
String emailType = null;
String name = null;
if (c.getCount() > 0) {
while (c.moveToNext()) {
String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(c.getString(c
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
System.out.println("ContactName : " + name + ", ID : " + id);
sb.append("\n Contact Name:" + name);
Cursor phoneno = content.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
while (phoneno.moveToNext()) {
phone = phoneno.getString(phoneno.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
sb.append("\n Phone number:" + phone);
System.out.println("phone" + phone);
}
phoneno.close();
Cursor emailid = content.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[] { id }, null);
while (emailid.moveToNext()) {
emailContact = emailid.getString(emailid.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
emailType = emailid.getString(emailid.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
sb.append("\nEmail:" + emailContact + "Email type:"
+ emailType);
System.out.println("Email " + emailContact
+ " Email Type : " + emailType);
}
emailid.close();
}
sb.append("\n");
sb.append("Next");
}
textDetail.setText(sb);
}
}
}
To retrive only one contact add line as below,
if(name.equals("ME"){
// whatever you want to do
}
It will display only that contact detail..
Cursor c = activity.getContentResolver().query(
ContactsContract.Profile.CONTENT_URI, null, null, null, null);
int count = c.getCount();
String[] columnNames = c.getColumnNames();
c.moveToFirst();
int position = c.getPosition();
if (count == 1 && position == 0) {
for (int i = 0; i < count; i++) {
for (int j = 0; j < columnNames.length; j++) {
String columnName = columnNames[j];
System.out.println(">>"+columnName+" = "+cursorContacts.getString(cursorContacts.getColumnIndex(columnName)));
}
c.moveToNext();
}
}
c.close();

Get contact name given a phone number in Android

I am trying to retrieve contact names given the contact phone number. I made a function that should work in all API versions, by I can't make it work in 1.6 and I can't see the problem, maybe someone can spot it?
Note that, I've replaced the API constants for strings so I don't have deprecated warning problems.
public String getContactName(final String phoneNumber)
{
Uri uri;
String[] projection;
if (Build.VERSION.SDK_INT >= 5)
{
uri = Uri.parse("content://com.android.contacts/phone_lookup");
projection = new String[] { "display_name" };
}
else
{
uri = Uri.parse("content://contacts/phones/filter");
projection = new String[] { "name" };
}
uri = Uri.withAppendedPath(uri, Uri.encode(phoneNumber));
Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null);
String contactName = "";
if (cursor.moveToFirst())
{
contactName = cursor.getString(0);
}
cursor.close();
cursor = null;
return contactName;
}
This seems to work fine in the latest versions:
private String getContactName(Context context, String number) {
String name = null;
// define the columns I want the query to return
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup._ID};
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
if(cursor != null) {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
Log.v(TAG, "Started uploadcontactphoto: Contact Found # " + number);
Log.v(TAG, "Started uploadcontactphoto: Contact name = " + name);
} else {
Log.v(TAG, "Contact Not Found # " + number);
}
cursor.close();
}
return name;
}
Use reflections instead of comparing sdk version.
public String getContactName(final String phoneNumber)
{
Uri uri;
String[] projection;
mBaseUri = Contacts.Phones.CONTENT_FILTER_URL;
projection = new String[] { android.provider.Contacts.People.NAME };
try {
Class<?> c =Class.forName("android.provider.ContactsContract$PhoneLookup");
mBaseUri = (Uri) c.getField("CONTENT_FILTER_URI").get(mBaseUri);
projection = new String[] { "display_name" };
}
catch (Exception e) {
}
uri = Uri.withAppendedPath(mBaseUri, Uri.encode(phoneNumber));
Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null);
String contactName = "";
if (cursor.moveToFirst())
{
contactName = cursor.getString(0);
}
cursor.close();
cursor = null;
return contactName;
}
public static String getContactName(Context context, String phoneNumber)
{
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor == null)
{
return null;
}
String contactName = null;
if(cursor.moveToFirst())
{
contactName = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
}
if(cursor != null && !cursor.isClosed()) {
cursor.close();
}
return contactName;
}
private String getContactNameFromNumber(String number) {
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor cursor = context.getContentResolver().query(uri, new String[]{PhoneLookup.DISPLAY_NAME},null,null,null);
if (cursor.moveToFirst())
{
name = cursor.getString(cursor.getColumnIndex(PhoneLookup.D

Categories

Resources