I want to get a phone number to dial from contacts , here is the code I'm testing:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
// Do something with phones
}
pCur.close();
}
For some reason it gets error at 'new Sting[]{id}, null);
Eclipse error #1 -id cannot be resolved to a variable
Eclipse error #2 -type mismatch: cannot convert from ArrayList to String
It appears maybe, as im a noob, 'id' is already being used by ArrayList ? But when i change 'id' to 'id2' Elcipse still dosent like it...
Please advise?
Thanks,
FlinxSYS
Here is working code for you:
public static void getContacts(ContentResolver cr) {
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
// read id
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
// read names
String displayName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// Phone Numbers
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
while (pCur.moveToNext()) {
String number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String typeStr = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
}
pCur.close();
...
Reference : http://ganeshtiwaridotcomdotnp.blogspot.com/2011/10/android-code-for-reading-phone-contacts.html
Related
Below is the code I am using to fetch contacts in Android.
String[] projectionFields = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
};
CursorLoader cursorLoader = new CursorLoader(context,
ContactsContract.Contacts.CONTENT_URI,
projectionFields, // the columns to retrieve
SELECTION, // the selection criteria (none)
null, // the selection args (none)
null // the sort order (default)
);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor.moveToFirst()) {
int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
do {
String contactDisplayName = cursor.getString(nameIndex);
} while (cursor.moveToNext());
}
I am also getting a lot of email only contacts. I don't want to show email-only contacts. How can I go about this?
I understand from your question that you need to get the contacts that has phone numbers. If this is the case, you can check if the contact has phone number by
ContentResolver contentResolver = getContentResolver();
ContentProviderClient mCProviderClient = contentResolver.acquireContentProviderClient(ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
Cursor cursor = mCProviderClient.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ") ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
Cursor phones = mCProviderClient.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION_PHONE,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
}
mCProviderClient.close();
cursor.close();
}
The value of hasPhoneNumber will be > 0, if there is a phone number assigned to the contact.
Please refer to this answer, it will allow only numbers and will also remove duplication.
Hope you find it helpful and your problem gets resolved.
Thanks.
I want to retrieve a cursor where in one row contains both name and phone number. Is the way to do this pretty, without any loops?
Uri uri = ContactsContract.Data.CONTENT_URI;
getContentResolver().query(uri,
new String[] {ContactsContract.Data._ID, Phone.NUMBER, StructuredName.GIVEN_NAME}, null, null, null)
the code i use to get my contacts is:
Cursor cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,null, null);
String Contactos =" CONTACTOS DEL TELEFONO "+cursor.getCount()+"\n";
while (cursor.moveToNext()) {
String name =cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Contactos+="Nombre: "+name+"\n"+
"Telefono: "+phoneNumber+"\n"+
"----------------------------\n";
}
then add the Contactos to a textview, and that's all!
see ya!
Hello i am using the next code for retrieving phone contacts name,number and its taked to long.
After littel search i found the the cursor.moveToFirst() command is that one who cuz this .
But i couldent find any solution ): may some one help me please ?
Thanks !
public void loadPhoneMembers(){
ContentResolver cr = this.getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if(cursor.moveToFirst())
{
do
{
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
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())
{
String contactNumber=pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contactName =
pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if(!phonesAdded.contains(contactNumber)){
members.add(contactName+","+contactNumber); // members is arrayList
}
break;
}
pCur.close();
}
} while (cursor.moveToNext()) ;
}
}
You are querying one extra Cursor for each Contact from your first query. You can query the Names and TelephoneNumbers in one query and ignore the Contacts without Telephone number.
String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER ,ContactsContract.CommonDataKinds.Phone.PHOTO_URI};
Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,projection, null, null, null);
Also, while (cursor.moveToNext()){
}
has same effect as the following.
if(cursor.moveToFirst())
{
do
{
} while (cursor.moveToNext()) ;
Hi all im using a sqlite helper class, but i have a little problem using a select statement.
I want to get the id of a datebase item by its name.
I use this select method:
public Cursor selectShift (String name){
SQLiteDatabase db = dbHandler.getReadableDatabase();
Cursor c = db.query(TABLE_NAME, null, "name=" + name, null, null, null, null);
c.moveToFirst();
db.close();
return c;
}
And when i call this i use this:
if(handler.selectShift(name)!=null){
Cursor c = handler.selectShift(name);
id = c.getInt(c.getColumnIndex("_id"));
c.close();
}
And then is get this error:
android.database.CursorIndexOutOfBoundsException: Index 0 requested,
with a size of 0
As if its not exists, but i checked the name string is correct, and when i display the names in a listview i see that name, so it exists.
Can someone help me how to fix this?
1 - there shoudld be check is there any data in cursor or not......c.getCount>0 or c.moveToFirst() or c.isAfterLast().......
if(handler.selectShift(name)!=null){
Cursor c = handler.selectShift(name);
if (c.moveToFirst()){ //<--------------
do{ //<---------if you not need the loop you can remove that
id = c.getInt(c.getColumnIndex("_id"));
}while(cursor.moveToNext());
}
c.close();
}
2- not sure but looks in select query as '<variable>' are not there in where clause with variable
"SELECT COUNT(*) FROM " + tableName + " WHERE " + commentFieldName + " = '" + comment + "'";
or better to use parametrized statement
String query = "SELECT COUNT(*) FROM " + tableName + " WHERE columnName = ?";
cursor = db.rawQuery(query, new Sring[] {comment});
The issue appears to be here
"name=" <-It should be "name = "+name
Following should work
Cursor cursor= db.query(TABLE_IMAGES,null, "name" +" = ?", new String[]{name}, null, null, null);
Unless your name variable is already formatted (or not a TEXT) for sql I am guessing you need a little quotation. Maybe something like this
Cursor c = db.query(TABLE_NAME, null, "name= \'" + name + "\'", null, null, null, null);
Thanks for your help, i found the problem. It was in the cursor method, the solution is:
public Cursor selectShift (String name){
SQLiteDatabase db = dbHandler.getReadableDatabase();
Cursor c = db.query(TABLE_NAME, new String[] {"_id"}, "name LIKE '"+name+"%'", null, null, null, null);
c.moveToFirst();
db.close();
return c;
}
when I try to search my database for a specific entry by using 'Washing Machine' as the search string to try and find the Database entry for 'Washing Machine', an error appears saying:
04-16 21:43:28.951: E/AndroidRuntime(545): FATAL EXCEPTION: main
04-16 21:43:28.951: E/AndroidRuntime(545): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lukeorpin.theappliancekeeper/com.lukeorpin.theappliancekeeper.EntryStatis tics}: android.database.sqlite.SQLiteException: near "Machine": syntax error: , while compiling: SELECT _id, appliance_name, appliance_wattage, energy_rates FROM ApplianceDetails WHERE appliance_name=Washing Machine
and more specifically to:
at com.lukeorpin.theappliancekeeper.Database.getWattage(Database.java:122)
04-16 21:43:28.951: E/AndroidRuntime(545): at com.lukeorpin.theappliancekeeper.EntryStatistics.onCreate(EntryStatistics.java:47)
Here is the code for the search query for the Database:
public String getWattage(String spinnerChoice) {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_WATTAGE, KEY_ENERGY};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=" + spinnerChoice, null, null, null, null);
if (c != null){
c.moveToFirst();
String wattage = c.getString(2);
return wattage;
}
return null;
}
public String getEnergyRate(String spinnerChoice) {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_WATTAGE, KEY_ENERGY};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=" + spinnerChoice, null, null, null, null);
if (c != null){
c.moveToFirst();
String energyRate = c.getString(3);
return energyRate;
}
return null;
}
and this is the original class where the method was created:
final String spinnerChoice = getIntent().getStringExtra("Name");
if(spinnerChoice==null){
return;
}
Database data = new Database(this);
data.open();
String returnedWattage = data.getWattage(spinnerChoice);
String returnedEnergyRate = data.getEnergyRate(spinnerChoice);
data.close();
Does anyone have any ideas why this error message is appearing? Thanks
EDIT: Here is the line of code that the error is pointing too (line 122):
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=" + spinnerChoice, null, null, null, null);
Given the error message, it seems like you don't have quotes denoting a string for the appliance_name value comparison. It should be
WHERE appliance_name = 'Washing Machine'
I'm not familiar with the api, but you can try changing line 122 to
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "='" + spinnerChoice + "'", null, null, null, null);
You need to enclose you search string in single quotes (in your SQL query).