about getContentResolver() query CallLog - android

Cursor c = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, null);
for (int i = 0; i < c.getColumnCount(); i++) {
Log.i(getClass().getName(), "retrieveCall(): " + c.getColumnName(i));
}
I can get all colume names in 4.0.x, but only got _id under 4.0.x. What 's the matter with my code? Thx in advance!
Cursor c = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, null);
for (int i = 0; i < c.getColumnCount(); i++) {
Log.i(getClass().getName(), "retrieveCall(): " + c.getColumnName(i));
}
while (c.moveToNext()) {
for (int i = 0; i < c.getColumnCount(); i++) {
Log.i(getClass().getName(), "retrieveCall(): " + c.getColumnName(i) + " = " + c.getInt(i) + "/" + c.getString(i));
} ...
code above works well in 4.0.x, I guess there are some differences of database?
#Anu, this is my complete code, please kindly tell me if you found somthing wrong:
private void retrieveCall()
{
Cursor c = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, null);
if (c != null) {
while (c.moveToNext()) {
String number = c.getString(c.getColumnIndex("number"));
String name = c.getString(c.getColumnIndex("name"));
long date = c.getLong(c.getColumnIndex("date"));
if (number.length() > 0) {
LogDetail log = null;
if (_callTable.containsKey(number)) {
log = (LogDetail) _callTable.get(number);
log.name = name;
log.date = date;
log.amount++;
} else {
log = new LogDetail();
log.name = name;
log.date = date;
log.amount = 1;
}
_callTable.put(number, log);
}
}
c.close();
}
}

try this ..... It worked for me...
Cursor c1 = getContentResolver().query(CallLog.Calls.CONTENT_URI,null,null,null,null);
for(int i=0;i<c1.getColumnCount();i++){
Log.i("Column name", ""+c1.getColumnName(i));
}

Don't forget to move the position of the Cursor
Use:
Cursor c = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, null);
while (c.moveToNext()) {
Log.i(getClass().getName(), "retrieveCall(): " + c.getColumnName(i));
}

Related

Android programatically getting device default phone number from contacts

I got name and contact id from android "my" contact by using this method
String[] columnNames = new String[] { Phone._ID,
Phone.DISPLAY_NAME };
Cursor c = LoginActivity.this.getContentResolver().query(
ContactsContract.Profile.CONTENT_URI, columnNames,
null, null, null);
int count = c.getCount();
boolean b = c.moveToFirst();
int position = c.getPosition();
if (count == 1 && position == 0) {
for (int j = 0; j < columnNames.length; j++) {
contact_id = c.getString(0);
namee = c.getString(1);
}
}
How to get phone number of the device too?
Add following permission in manifest.
<uses-permission android:name="android.permission.READ_CONTACTS" />
Use Following code to get "Me" contact.
public Loader<Cursor> onCreateLoader(int id, Bundle arguments) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath( ContactsContract.Profile.CONTENT_URI,ContactsContract.Contacts.Data.CONTENT_DIRECTORY),
ProfileQuery.PROJECTION,
//Don't select anything here null will return all available fields
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
ArrayList<String> DataArray = new ArrayList<String>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
//here where you get your data and its type
TypeName=cursor.getString(ProfileQuery.ADDRESS);//this will give you field name
Data=cursor.getString(ProfileQuery.NUMBER);//this will give you field data
cursor.moveToNext();
}
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.Contacts.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.ADDRESS ,
ContactsContract.CommonDataKinds.Email.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Organization.DATA3,
};
int ADDRESS = 0;
int NUMBER = 1;
}
Try this:
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
int contactIdIdx = cursor.getColumnIndex(Phone._ID);
int nameIdx = cursor.getColumnIndex(Phone.DISPLAY_NAME);
int phoneNumberIdx = cursor.getColumnIndex(Phone.NUMBER);
int photoIdIdx = cursor.getColumnIndex(Phone.PHOTO_ID);
cursor.moveToFirst();
do {
String idContact = cursor.getString(contactIdIdx);
String name = cursor.getString(nameIdx);
String phoneNumber = cursor.getString(phoneNumberIdx);
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
And in manifest:
<uses-permission android:name="android.permission.READ_CONTACTS" />
This is the proper way of doing it
1) call the intent
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
if(intent.resolveActivity(getActivity().getPackageManager()) != null) {
getParentFragment().startActivityForResult(intent, CONTACT_REQUEST_CODE);
}
2) Implement onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CONTACT_REQUEST_CODE) {
uriContact = data.getData();
// replaceAll("\\D", "") : Remove everything that is not a digit
String number = retrieveContactNumber();
if (Connectivity.isConnected(getActivity())) {
if (number != null) {
String contact_number = number.replaceAll("\\D", "");
}
}
}
}
}
3) implement retrieveContactNumber()
private String retrieveContactNumber() {
String contactNumber = null;
// getting contacts ID
Cursor cursorID = getActivity().getContentResolver().query(uriContact,
new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
// Using the contact ID to get contact phone number
Cursor cursorPhone = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactID},
null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
return contactNumber;
}
4) Enjoy :)
Try this...
String[] columnNames = new String[] { Phone._ID,
Phone.DISPLAY_NAME };
Cursor c = LoginActivity.this.getContentResolver().query(
ContactsContract.Profile.CONTENT_URI, columnNames,
null, null, null);
int count = c.getCount();
boolean b = c.moveToFirst();
int position = c.getPosition();
if (count == 1 && position == 0) {
for (int j = 0; j < columnNames.length; j++) {
contact_id = c.getString(0);
namee = c.getString(1);
if(Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?",new String[] { contact_id }, null);
while (pCur.moveToNext()) {
String noo = pCur.getString(pCur.getColumnIndex(CommonDataKinds.Phone.NUMBER));
}
}
}
}
I think you should use ContactsContract.CommonDataKinds.Phone.CONTENT_URI and there is column called ContactsContract.CommonDataKinds.Phone.NUMBER using which you may get contact number.
Have a look this code
public ArrayList<String> getContactList(){
ArrayList<String> list= new ArrayList<String>();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] columns = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor people = getContentResolver().query(uri, columns, null, null, null);
int _nameIndex = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int _numberIndex = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
people.moveToFirst();
do {
String name = people.getString(_nameIndex);
String number = people.getString(_numberIndex);
list.add(name+" :"+number);
// Do work...
} while (people.moveToNext());
return list;
}
This worked for me.
String[] columnNames = new String[] { Phone._ID,
Phone.DISPLAY_NAME, Phone.NUMBER };
Cursor c = LoginActivity.this.getContentResolver().query(
ContactsContract.Profile.CONTENT_URI, columnNames,
null, null, null);
int count = c.getCount();
boolean b = c.moveToFirst();
int position = c.getPosition();
if (count == 1 && position == 0) {
for (int j = 0; j < columnNames.length; j++) {
contact_id = c.getString(0);
name = c.getString(1);
number= c.getString(2);
}
}

Android fetch all contact list (name, email, phone) takes more then a minute for about 700 contacts

Is there any way to shorten this time?
I'm running with the cursor and takes the name, phone numbers and emails
if I remove the phone numbers query from the query loop it ends in 3 seconds
any idea how can I improve that query?
Maybe I'm doing something wrong in my query?
(Obviously I'm doing it async but still... it's a very long time that a user can't wait)
Hope someone can share his thoughts about this
this is my code
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
AddressBookEntity adr = new AddressBookEntity();
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
adr.fullName = name;
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));
if (!Utils.IsNullOrEmptyString(email)) {
adr.email = email;
}
}
emailCur.close();
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);
int phoneIndex = 0;
while (pCur.moveToNext()) {
String number = pCur.getString(pCur
.getColumnIndex(Phone.NUMBER));
String country = Utils.GetCountryFromNumber(
number, app);
number = Utils.GetFullPhoneNumber(number, app);
if (phoneIndex == 0) {
if (!Utils.IsNullOrEmptyString(number)) {
adr.contactAdressBookId = id;
adr.phoneNumber = number;
adr.userInsertedId = app.userCred.userId;
adr.country = country;
myContacts.add(adr);
}
} else {
if (!Utils.IsNullOrEmptyString(number)) {
AddressBookEntity adrMore = new AddressBookEntity();
adrMore.fullName = adrMore.fullName;
adrMore.country = adrMore.country;
adrMore.email = adrMore.email;
adrMore.phoneNumber = number;
adrMore.contactAdressBookId = id;
adrMore.country = country;
myContacts.add(adrMore);
}
}
}
pCur.close();
}
}
cur.close();
with the following code for 59 contacts i got the following results on the emulator:
D ╔══════ query execution stats ═══════
D ║ got 59 contacts
D ║ query took 0.012 s (12 ms)
D ╚════════════════════════════════════
ok, that was the best time, but the average is 25-35 ms (for 59 contacts), add the following code in some onClick callback and run in several times in order to get the average time, in your case you should get 30 * 700 / 59 = ~300-400 ms, not 3 seconds, let alone one minute ;)
it uses Uri set to Contactables.CONTENT_URI added in API level 18 but you can use ContactsContract.Data.CONTENT_URI when building for pre 18 API devices
List<AddressBookContact> list = new LinkedList<AddressBookContact>();
LongSparseArray<AddressBookContact> array = new LongSparseArray<AddressBookContact>();
long start = System.currentTimeMillis();
String[] projection = {
ContactsContract.Data.MIMETYPE,
ContactsContract.Data.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Contactables.DATA,
ContactsContract.CommonDataKinds.Contactables.TYPE,
};
String selection = ContactsContract.Data.MIMETYPE + " in (?, ?)";
String[] selectionArgs = {
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
};
String sortOrder = ContactsContract.Contacts.SORT_KEY_ALTERNATIVE;
Uri uri = ContactsContract.CommonDataKinds.Contactables.CONTENT_URI;
// we could also use Uri uri = ContactsContract.Data.CONTENT_URI;
// ok, let's work...
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
final int mimeTypeIdx = cursor.getColumnIndex(ContactsContract.Data.MIMETYPE);
final int idIdx = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
final int nameIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int dataIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.DATA);
final int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.TYPE);
while (cursor.moveToNext()) {
long id = cursor.getLong(idIdx);
AddressBookContact addressBookContact = array.get(id);
if (addressBookContact == null) {
addressBookContact = new AddressBookContact(id, cursor.getString(nameIdx), getResources());
array.put(id, addressBookContact);
list.add(addressBookContact);
}
int type = cursor.getInt(typeIdx);
String data = cursor.getString(dataIdx);
String mimeType = cursor.getString(mimeTypeIdx);
if (mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
// mimeType == ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
addressBookContact.addEmail(type, data);
} else {
// mimeType == ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
addressBookContact.addPhone(type, data);
}
}
long ms = System.currentTimeMillis() - start;
cursor.close();
// done!!! show the results...
int i = 1;
for (AddressBookContact addressBookContact : list) {
Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));
}
final String cOn = "<b><font color='#ff9900'>";
final String cOff = "</font></b>";
Spanned l1 = Html.fromHtml("got " + cOn + array.size() + cOff + " contacts<br/>");
Spanned l2 = Html.fromHtml("query took " + cOn + ms / 1000f + cOff + " s (" + cOn + ms + cOff + " ms)");
Log.d(TAG, "\n\n╔══════ query execution stats ═══════" );
Log.d(TAG, "║ " + l1);
Log.d(TAG, "║ " + l2);
Log.d(TAG, "╚════════════════════════════════════" );
SpannableStringBuilder msg = new SpannableStringBuilder().append(l1).append(l2);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(this);
tv.setTextSize(20);
tv.setBackgroundColor(0xff000033);
tv.setPadding(24, 8, 24, 24);
tv.setText(msg);
ll.addView(tv);
ListView lv = new ListView(this);
lv.setAdapter(new ArrayAdapter<AddressBookContact>(this, android.R.layout.simple_list_item_1, list));
ll.addView(lv);
new AlertDialog.Builder(this).setView(ll).setPositiveButton("close", null).create().show();
the helper AddressBookContact class:
class AddressBookContact {
private long id;
private Resources res;
private String name;
private LongSparseArray<String> emails;
private LongSparseArray<String> phones;
AddressBookContact(long id, String name, Resources res) {
this.id = id;
this.name = name;
this.res = res;
}
#Override
public String toString() {
return toString(false);
}
public String toString(boolean rich) {
SpannableStringBuilder builder = new SpannableStringBuilder();
if (rich) {
builder.append("id: ").append(Long.toString(id))
.append(", name: ").append("\u001b[1m").append(name).append("\u001b[0m");
} else {
builder.append(name);
}
if (phones != null) {
builder.append("\n\tphones: ");
for (int i = 0; i < phones.size(); i++) {
int type = (int) phones.keyAt(i);
builder.append(ContactsContract.CommonDataKinds.Phone.getTypeLabel(res, type, ""))
.append(": ")
.append(phones.valueAt(i));
if (i + 1 < phones.size()) {
builder.append(", ");
}
}
}
if (emails != null) {
builder.append("\n\temails: ");
for (int i = 0; i < emails.size(); i++) {
int type = (int) emails.keyAt(i);
builder.append(ContactsContract.CommonDataKinds.Email.getTypeLabel(res, type, ""))
.append(": ")
.append(emails.valueAt(i));
if (i + 1 < emails.size()) {
builder.append(", ");
}
}
}
return builder.toString();
}
public void addEmail(int type, String address) {
if (emails == null) {
emails = new LongSparseArray<String>();
}
emails.put(type, address);
}
public void addPhone(int type, String number) {
if (phones == null) {
phones = new LongSparseArray<String>();
}
phones.put(type, number);
}
}
try this code ,use a progress dialouge
public void getAllContacts() {
new AsyncTask<String, String, ArrayList<UserInfo>>() {
ArrayList<UserInfo> infos = new ArrayList<>();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<UserInfo> doInBackground(String... params) {
ContentResolver contactResolver = context.getContentResolver();
Cursor cursor = contactResolver.query(ContactsContract.Contacts.CONTENT_URI, new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER }, null, null, null);
if(cursor.getCount()>0)
while ( cursor.moveToNext()) {
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// String photoUri = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
// String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Log.d("TAG", " Name: " + displayName);
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = contactResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { contactId }, null);
while (pCur.moveToNext())
{
String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String type = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(), Integer.parseInt(type), "");
Log.d("TAG", s + " phone: " + phone);
}
pCur.close();
}
Cursor emailCursor = contactResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { contactId }, null);
while (emailCursor.moveToNext())
{
String phone = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
int type = emailCursor.getInt(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(context.getResources(), type, "");
Log.d("TAG", s + " email: " + phone);
}
emailCursor.close();
} cursor.close();
return null;
}
#Override
protected void onPostExecute(ArrayList<UserInfo> aVoid) {
super.onPostExecute(aVoid);
// EventBus.getDefault().post(aVoid);
}
}.execute();
}
You retrieve all columns in your query:
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
This makes the data processing much slower. If you define an array of columns which you really need to retrieve, it will be much faster.

Getting all the contacts from the phone sometimes returns NULL

I have made an app in which I need all the contacts available in the phone-book. I display these numbers in a list.The app works fine but some times the app force closes because the cursor returns null.This does not happens always but it happens some times.Now how do I handle this ????
Code
public static JSONArray getAllContactList(Context context) {
Cursor c = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
alAllContacts = new ArrayList<ContactModel>();
while (!(c == null) && c.moveToNext()) {
String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String number = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (number.equalsIgnoreCase("1")) {
// Cursor phones = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
// ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = '" + id + "'", null, null);
Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
while (phones.moveToNext()) {
String contactName = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String contactNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactNumber = contactNumber.replace("+", "");
if (contactNumber.length() > 10) {
contactNumber = contactNumber.substring(2);
}
// contactNumber.replace("+91", "");
alAllContacts.add(new ContactModel(contactName, contactNumber));
//
}
}
}
c.close();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < alAllContacts.size(); i++) {
jsonArray.put(alAllContacts.get(i).getJSONObject());
}
return jsonArray;
}
the logcat says that i am getting null pointer at this line
while (phones.moveToNext()) {
Also some times i get force close because by dialog is running,So is my code for showing the progress bar correct
public static void showProgress(Context context, String msg, boolean isVisible) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage(msg);
progressDialog.setCancelable(false);
}
if (isVisible) {
progressDialog.show();
} else if (isVisible == false) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
I use this code for getting all contacts and it does the job.
private static void backupContacts(Context context) {
String[] pCurProjection = new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.LABEL,
ContactsContract.CommonDataKinds.Phone.IS_PRIMARY
};
String contactSelection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'";
String[] contactProjection = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME
};
Cursor contactCursor = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
contactProjection,
contactSelection,
null,
ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
int contactId;
String contactName;
if (null != contactCursor) {
while (contactCursor.moveToNext()) {
contactId = contactCursor.getInt(
contactCursor.getColumnIndex(ContactsContract.Contacts._ID));
contactName = contactCursor.getString(
contactCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println(contactId + ": " + contactName);
Cursor pCur = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
pCurProjection,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{String.valueOf(contactId)},
null);
if (null != pCur) {
while (pCur.moveToNext()) {
int id = pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone._ID);
String number = (pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
String type = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));//this line returns Null but it does not effect on the code(Does not Throws NullPointerException). if you found fix for it please let me know
int isPrimary = pCur.getInt(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.IS_PRIMARY));
System.out.println(id + ": " + number + "\n" + type + "\n" + isPrimary);
}
pCur.close();
}
}
contactCursor.close();
}
}
if you have any question let me know :)

How do i get the SMS Sender Contact (Person) saved name using "content://sms/inbox"

In my App i want to retrieve the SMS sender saved Name using below code but it always return null. Please suggest me whats the convenient way to get the sender name.
Uri SMS_INBOX = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(SMS_INBOX, null, null, null, null);
android.util.Log.i("COLUMNS", Arrays.toString(c.getColumnNames()));
try {
if(c.getCount()>0)
{
while (c.moveToNext()){
Log.d("SMSss", "Contact : "+c.getString(2)+"\n"
+"msg : "+c.getString(11)+"\n"
+"ID : "+c.getString(0)+"\n"
+"Person : "+c.getString(3));
}
}
} catch (Exception e) {
Log.d("mmmmmmmmm"," "+ e.getStackTrace());
}
i am using following permission in menifest
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
Please suggest me how to get. Thanks in advance.
By this way you can get the saved contact name from inbox..
call the method getAllSms() to get the details..
public void getAllSms() {
Uri message = Uri.parse("content://sms/");
ContentResolver cr = getContentResolver();
Cursor c = cr.query(message, null, null, null, null);
startManagingCursor(c);
int totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int i = 0; i < totalSMS; i++) {
Log.d("SMSss",
"Contact number : "
+ c.getString(c
.getColumnIndexOrThrow("address"))
+ "\n"
+ "msg : "
+ c.getColumnIndexOrThrow("body")
+ "\n"
+ "ID : "
+ c.getString(c.getColumnIndexOrThrow("_id"))
+ "\n"
+ "Person : "
+ getContactName(
getApplicationContext(),
c.getString(c
.getColumnIndexOrThrow("address"))));
c.moveToNext();
}
}
c.close();
}
public 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;
}
Uri uriInbox = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uriInbox, null, null, null, null);
if (c.moveToFirst()) {
for (int i = 0; i < c.getCount(); i++) {
String name = null;
String phone = "";
String _id = c.getString(c.getColumnIndexOrThrow("_id"));
String thread_id = c.getString(c.getColumnIndexOrThrow("thread_id"));
String msg = c.getString(c.getColumnIndexOrThrow("body"));
String type = c.getString(c.getColumnIndexOrThrow("type"));
String timestamp = c.getString(c.getColumnIndexOrThrow("date"));
phone = c.getString(c.getColumnIndexOrThrow("address"));
name = Function.getContactbyPhoneNumber(getApplicationContext(), c.getString(c.getColumnIndexOrThrow("address")));
c.moveToNext();
}
}
c.close();
Finally your getContactbyPhoneNumber method:
public String getContactbyPhoneNumber(Context c, String phoneNumber) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String[] projection = {ContactsContract.PhoneLookup.DISPLAY_NAME};
Cursor cursor = c.getContentResolver().query(uri, projection, null, null, null);
if (cursor == null) {
return phoneNumber;
}else {
String name = phoneNumber;
try {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
} finally {
cursor.close();
}
return name;
}
}
Courtesy: http://www.androstock.com/tutorials/create-sms-app-android-android-studio-part-2.html

Create graph in achartengine from SQLite

I'm trying to build a graph in achartengine with data from my SQLite database. Getting the data from the database works, but it does always build just one point and not a graph. What am I doing wrong?
Here is my code:
public String getValue1(long l) {
String[] columns = new String[]{ KEY_Value1, KEY_Value2 };
Cursor c = Database.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value1 = c.getString(0);
return value1;
}
return null;
}
public String getValue2(long l) {
String[] columns = new String[]{ KEY_Value1, KEY_Value2 };
Cursor c = Database.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value2 = c.getString(1);
return value2;
}
return null;
}
DB getData = new DB(this);
getData.open();
for (int i = 1; value1 == null; i++) {
Stirng value1 = getData.getValue1(i);
String value2 = getData.getValue2(i);
}
getData.close();
x = Double.parseDouble(value1);
y = Double.parseDouble(value2);
mCurrentSeries.add(x, y);
if (mChartView != null) {
mChartView.repaint();
}
}
Edit the second part to this code:
DB getData = new DB(this);
getData.open();
for (int i = 1; value1 == null; i++) {
String value1 = getData.getValue1(i);
String value2 = getData.getValue2(i);
x = Double.parseDouble(value1);
y = Double.parseDouble(value2);
mCurrentSeries.add(x, y); //*** this has to be inside the loop in order to draw more than one point ***
}
getData.close();
if (mChartView != null) {
mChartView.repaint();
}
}

Categories

Resources