How to sort Uri Array by Date/Time? - java

Is it possible to sort an Array containing Uri's by date/time?
An Uri in my array looks like:
content://media/external/images/media/65
I have tried Collections.sort() but it wasn't possible with an Uri[]
Edit:
My Uri points to an image stored on the device. I want to sort the images by date and time and show it sorted in an GridView.

You can query the content resolver for modified time.
Uri uri = Uri.parse("content://media/external/images/media/65");
String projection [] = {
MediaStore.Images.Media.DATA
, MediaStore.Images.Media.DISPLAY_NAME
, MediaStore.Images.Media.SIZE
, MediaStore.Images.Media.MIME_TYPE
, MediaStore.Images.Media.DATE_MODIFIED
, DocumentsContract.Document.COLUMN_LAST_MODIFIED
};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if ( cursor==null)
{
return;
}
cursor.moveToFirst();
String data = cursor.getString(0);
String displayName = cursor.getString(1);
String size = cursor.getString(2);
String mimeType = cursor.getString(3);
String dateModified = cursor.getString(4); // null
String dateModified2 = cursor.getString(5);
Toast.makeText(context,
"DISPLAY_NAME: " + displayName
+ "\nDATA: " + data
+ "\nSIZE: " + size
+ "\nmimeType: " + mimeType
+ "\n" +MediaStore.Images.Media.DATE_MODIFIED + ": " + dateModified
+ "\n" +DocumentsContract.Document.COLUMN_LAST_MODIFIED + ": " + dateModified2
, Toast.LENGTH_LONG).show();
cursor.close();
Even uris from the media store deliver null for
MediaStore.Images.Media.DATE_MODIFIED ("date_modified")
hence DocumentsContract.Document.COLUMN_LAST_MODIFIED ("last_modified")
which is good for all.
Add a try and some catch blocks.

Related

Never entering in cursor.moveToNext() in Android SQLite

I'm trying Official Documentation for Android this article. Creating Database, Table and inserting data is working fine. But I'm unable to get data from database. Here is the piece of code to retrieve data from table.
public Person searchDataInDB(String personCellString) {
SQLiteDatabase db = getReadableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
PersonTable.COLUMN_NAME_ID,
PersonTable.COLUMN_NAME_NAME,
PersonTable.COLUMN_NAME_CELL_NO,
PersonTable.COLUMN_NAME_ADDRESS
};
// Filter results WHERE "cell#" = 'Person Cell #'
String selection = SQLiteDBHelper.PersonTable.COLUMN_NAME_CELL_NO + " = ?";
String[] selectionArgs = {"'" + personCellString + "'"};
// How you want the results sorted in the resulting Cursor
// String sortOrder = SQLiteDBHelper.PersonTable.COLUMN_NAME_ID + " DESC";
Cursor cursor = db.query(
SQLiteDBHelper.PersonTable.TABLE_NAME, // The table to query
null, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
String [] names = cursor.getColumnNames();
Log.e("SQLiteDB", "cursorCount = " + cursor.getCount() + ", cursorColumnCount = " + cursor.getColumnCount() + ", Column = " + names[0]);
Person person = null;
while (cursor.moveToNext()) {
int id = (int) cursor.getLong(
cursor.getColumnIndexOrThrow(PersonTable.COLUMN_NAME_ID));
Log.e("SQLiteDB", "moveToNext id = " + id);
String name = cursor.getString(
cursor.getColumnIndexOrThrow(SQLiteDBHelper.PersonTable.COLUMN_NAME_NAME));
Log.e("SQLiteDB", "moveToNext name = " + name);
String cellNo = cursor.getString(
cursor.getColumnIndexOrThrow(SQLiteDBHelper.PersonTable.COLUMN_NAME_CELL_NO));
Log.e("SQLiteDB", "moveToNext cell = " + cellNo);
String address = cursor.getString(
cursor.getColumnIndexOrThrow(SQLiteDBHelper.PersonTable.COLUMN_NAME_ADDRESS));
Log.e("SQLiteDB", "moveToNext address = " + address);
person = new Person(id, name, cellNo, address);
}
cursor.close();
return person;
}
It seems like my app does not enter in while loop i.e. while(cursor.moveToNext() So this method always returns initial value of person which is null. As a result, the first condition is always true from below code
Person person = dbHelper.searchDataInDB(personCellString);
if (person == null) {
Toast.makeText(mContext, "no such record exists in database!", Toast.LENGTH_LONG).show();
} else {
String personDetails = "Name = " + person.getName()
+ "Cell Number = " + person.getCellNumber()
+ "Address = " + person.getAddress();
personDetailsTV.setText(personDetails);
}
I'm using DB Browser for SQLite so I can see the records are successfully adding in the database.
What should I do with the above code to make it work?
What you are doing with this:
String[] selectionArgs = {"'" + personCellString + "'"};
is searching for the string value of personCellString enclosed inside single quotes and not for the actual value of the string personCellString.
Remove the single quotes:
String[] selectionArgs = {personCellString};
You don't have to worry about the string representation of personCellString in the final sql statement that will be constructed and executed which will contain them without explicitly setting them.

Get some contact info data from phone

I need to get list of id, first name, last name, number(or numbers), email, website of an android device contacts. I know by getting id I can query about phone numbers this is not a big deal. But I don't know how I should make query to get all these columns correctly.
I supposed for names I need ContactsContract.CommonDataKinds.StructuredName for email I need ContactsContract.CommonDataKinds.Email.ADDRESS ,for id Contacts and for website ContactsContract.CommonDataKinds.Website.URL.
My code returns strange values like a single digit number for GIVEN_NAME, null for FAMILY_NAME, one of contact numbers for Email.ADDRESS.
However I think the problem is query URI, which one should I use?
ContentResolver cr = getActivity().getContentResolver();
String[] projection = new String[] {
Contacts._ID,
ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME,
ContactsContract.CommonDataKinds.Website.URL,
ContactsContract.CommonDataKinds.Email.ADDRESS};
Cursor nameCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
null,
null,
null);
while (nameCur.moveToNext()) {
String given = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
String family = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
String email = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
Integer id= nameCur.getInt(nameCur.getColumnIndex(Contacts._ID));
String website = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
//do some work with strings...
}
The problem is that all the sub-tables you're trying to access (Email, Phone, Website, etc.) are actually all stored in a single big table called Data.
All those sub-tables share the same fields Data1-Data15, so by querying on the Phone.CONTENT_URI table, you're only getting Phone info, that's why trying to access StructuredName.GIVEN_NAME on the result is wrong.
Instead you query over the Data.CONTENT_URI table that contains all info, and you differentiate between rows of different data type via the value at Data.MIMETYPE.
See docs here: https://developer.android.com/reference/android/provider/ContactsContract.Data
I'm not sure if you needed the contact's info for all contacts on the device, or for a specific one.
Here's the code to get info of a single contact (you need to assign value to the contactId variable there)
String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3};
// query only emails/phones/events
String selection = Data.CONTACT_ID + "=" + contactId + " AND " +
Data.MIMETYPE + " IN ('" + StructuredName.CONTENT_ITEM_TYPE + "', '" + Phone.CONTENT_ITEM_TYPE + "', '" + Email.CONTENT_ITEM_TYPE"', '" + Website.CONTENT_ITEM_TYPE + "')";
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(Data.CONTENT_URI, projection, selection, null, null);
while (cur.moveToNext()) {
long id = cur.getLong(0);
String name = cur.getString(1); // full name
String mime = cur.getString(2); // type of data (phone / birthday / email)
String data = cur.getString(3); // the actual info, e.g. +1-212-555-1234
String kind = "unknown";
switch (mime) {
case StructuredName.CONTENT_ITEM_TYPE:
String firstName = cur.getString(4);
String lastName = cur.getString(5);
Log.d(TAG, "got name: " + data + " - " + firstName + " " + lastName);
break;
case Phone.CONTENT_ITEM_TYPE:
Log.d(TAG, "got phone: " + data);
break;
case Email.CONTENT_ITEM_TYPE:
Log.d(TAG, "got email: " + data);
break;
case Website.CONTENT_ITEM_TYPE:
Log.d(TAG, "got website: " + data);
break;
}
}
cur.close();
To convert it to run over ALL contacts, simply remove the Data.CONTACT_ID + "=" + contactId part from the selection, and then you'll need to create some HashMap from contactId to an object containing the info about that contact (use the id variable for the key)
here is my solution:
first we need a query for getting all contact id in the table of "raw_contacts"
List<Integer> ret = new ArrayList<Integer>();
ContentResolver contentResolver = getActivity().getContentResolver();
// Row contacts content uri( access raw_contacts table. ).
Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI;
// Return _id column in contacts raw_contacts table.
String queryColumnArr[] = {ContactsContract.RawContacts._ID};
// Query raw_contacts table and return raw_contacts table _id.
Cursor cursor = contentResolver.query(rawContactUri, queryColumnArr, null, null, null);
then we query table "data" for extra information for each contact id:
// Data content uri (access data table. )
Uri dataContentUri = ContactsContract.Data.CONTENT_URI;
// Build query columns name array.
List<String> queryColumnList = new ArrayList<String>();
// ContactsContract.Data.CONTACT_ID = "contact_id";
queryColumnList.add(ContactsContract.Data.CONTACT_ID);
// ContactsContract.Data.MIMETYPE = "mimetype";
queryColumnList.add(ContactsContract.Data.MIMETYPE);
queryColumnList.add(ContactsContract.Data.DATA1);
queryColumnList.add(ContactsContract.Data.DATA2);
queryColumnList.add(ContactsContract.Data.DATA3);
queryColumnList.add(ContactsContract.Data.DATA4);
queryColumnList.add(ContactsContract.Data.DATA5);
queryColumnList.add(ContactsContract.Data.DATA6);
queryColumnList.add(ContactsContract.Data.DATA7);
queryColumnList.add(ContactsContract.Data.DATA8);
queryColumnList.add(ContactsContract.Data.DATA9);
queryColumnList.add(ContactsContract.Data.DATA10);
queryColumnList.add(ContactsContract.Data.DATA11);
queryColumnList.add(ContactsContract.Data.DATA12);
queryColumnList.add(ContactsContract.Data.DATA13);
queryColumnList.add(ContactsContract.Data.DATA14);
queryColumnList.add(ContactsContract.Data.DATA15);
// Translate column name list to array.
String queryColumnArr[] = queryColumnList.toArray(new String[queryColumnList.size()]);
// Build query condition string. Query rows by contact id.
StringBuffer whereClauseBuf = new StringBuffer();
whereClauseBuf.append(ContactsContract.Data.RAW_CONTACT_ID);
whereClauseBuf.append("=");
whereClauseBuf.append(rawContactId);
// Query data table and return related contact data.
Cursor cursor = contentResolver.query(dataContentUri, queryColumnArr, whereClauseBuf.toString(), null, null);
last cursor contains all the data of any contact and for get that data we need switch case:
String mimeType =cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
switch (mimeType) {
// Get email data.
case ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE:
// Email.ADDRESS == data1
String emailAddress = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
int emailType = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
data.setDataType(emailType);
data.setDataValue(emailAddress);
ret1.add(data);
con.setEmailList(ret1);
break;
// Get organization data.
case ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE:
// Organization.COMPANY == data1
String company = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
con.setCompany(company);
break;
// Get phone number.
case ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE:
// Phone.NUMBER == data1
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Phone.TYPE == data2
int phoneTypeInt = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
data.setDataType(phoneTypeInt);
data.setDataValue(phoneNumber);
ret1.add(data);
con.addPhoneList(ret1);
break;
// Get display name.
case ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE:
// StructuredName.DISPLAY_NAME == data1
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
// StructuredName.GIVEN_NAME == data2
String givenName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
// StructuredName.FAMILY_NAME == data3
String familyName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
ret.add("Display Name : " + displayName);
ret.add("Given Name : " + givenName);
ret.add("Family Name : " + familyName);
break;
// Get website.
case ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE:
// Website.URL == data1
String websiteUrl = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
// Website.TYPE == data2
int websiteTypeInt = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Website.TYPE));
String websiteTypeStr = getEmailTypeString(websiteTypeInt);
ret.add("Website Url : " + websiteUrl);
ret.add("Website Type Integer : " + websiteTypeInt);
ret.add("Website Type String : " + websiteTypeStr);
break;
}
this is not my compelete code just for getting idea. hope this will help someone!

Android SQLite error on cursor

I'm currently working on an android project and am stuck on this method. The cursor query works but anything after that does not. If I take out the 'returnCompany' method it runs so I'm guessing the error is inside the cursor query. The method is taking in a string parameter called 'companyNameParemeter'. FYI Android Studio is the text editor I'm using.
SQLiteDatabase db = this.getReadableDatabase();
String returnString = "";
Cursor cursor = db.rawQuery("Select * from " + CONTANT_INFO_AND_GPS_TABLE + " where " +
KEY_COMPANY_NAME + " = ? ", new String[] {companyNameParamater});
company returnCompany = new company(Integer.parseInt(cursor.getString(0)), cursor.getString(1),
cursor.getString(2), cursor.getString(3),Double.parseDouble(cursor.getString(4) ),
Double.parseDouble(cursor.getString(5)));
/* returnString = ("Company is:\t" + returnCompany.getCompanyName() + ",\nContact name:\t" +
returnCompany.getContactName() + ",\tContact No:\t" + returnCompany.getContactNumber()
+ ",\nGPS:\tLat:\t"
+ returnCompany.getGPS_Latitude() + "\tLong:\t" + returnCompany.getGPS_Longitude() );*/
return returnString;
I checked LogCat and the only relevant error I could find was this
04-04 12:06:38.237 2032-1714/? E/GCoreUlr: Received null location result
Try using
cursor.moveToFirst()
Right AFTER creating and filling it with db.rawquery or wichever call you use to get your data from your DB,
It will make sure your cursor is pointing at the first element you received, i may be wrong but i remember it's always pointing at the end of the data it contains when you fill it.
The error you show doesn't reflect the error you would typically get. However the code you have shown is clearly wrong and would result in an error because you are trying read a row when you are positioned at the start position of the cursor (aka beforeFirstRow).
You have to move to a row before you can get the data. As you only appear to have a single row, then using the Cursor method moveToFirst will either position you at the first (only) row. If the move cannot be made (no rows) then like all the Cursor move????? methods (moveTolast, moveToNext etc) a boolean false is returned (true if the move was made) hence it's use in within the if.
SQLiteDatabase db = this.getReadableDatabase();
String returnString = "";
Cursor cursor = db.rawQuery("Select * from " + CONTANT_INFO_AND_GPS_TABLE + " where " + KEY_COMPANY_NAME + " = ? ", new String[] {companyNameParamater});
if (cursor.moveToFirst()) { //<<<< Move the cursor to a row
company returnCompany = new company(Integer.parseInt(cursor.getString(0)),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
Double.parseDouble(cursor.getString(4)),
Double.parseDouble(cursor.getString(5)));
/* returnString = ("Company is:\t" + returnCompany.getCompanyName() + ",\nContact name:\t" +
returnCompany.getContactName() + ",\tContact No:\t" +
returnCompany.getContactNumber()
+ ",\nGPS:\tLat:\t"
+ returnCompany.getGPS_Latitude() + "\tLong:\t" +
returnCompany.getGPS_Longitude() );
*/
}
return returnString;
P.S. Double.parseDouble(cursor.getString(4)) could be cursor.getDouble(4)

Android - SQlite insert not inserting

So i am trying to insert some data in the internal sqlite database but after i run the insert no data has been added. There are, as far as i can see no errors in the logs and every debug log i put into it is shown. If i try to run the query that is returned in the log in sqlitestudio it works without a problem so i haven't got a clue as to what is going wrong.
#Override
public void onCreate(SQLiteDatabase db) {
String SQL = pictureTable();
db.execSQL(SQL);
}
private String pictureTable() {
return "CREATE TABLE geophoto_db_pictures ( picid integer,"
+ "name varying character(50),"
+ "city varying character(20) NOT NULL,"
+ "zipcode varying character(20) NOT NULL,"
+ "country varying character(20) NOT NULL,"
+ "picdate datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,"
+ "tags varying character(200),"
+ "image varying character(200) NOT NULL,"
+ "uploaded integer NOT NULL DEFAULT 0, PRIMARY KEY (picid))";
}
#Override
public void savePicture(Picture pic) {
Log.d(LOG_TAG, "saving picture started. Data: " + pic.getName());
// clean the inputs
String name = pic.getName();
String city = pic.getCity();
if (city != null) {
city = "'" + city + "'";
}
String country = pic.getCountry();
if (country != null) {
country = "'" + country + "'";
}
String zip = pic.getZipcode();
if (zip != null) {
zip = "'" + zip + "'";
}
String tags = tagsToString(pic.getTags());
String image = pic.getImage();
// Insert Query, all possible null values on "not null" rows will be
// replaced by a default value.
String SQL = "INSERT INTO geophoto_db_pictures(name, city, zipcode, country, tags, image)"
+ "VALUES('"
+ name
+ "',"
+ "IFNULL("
+ city
+ ", 'Unknown')"
+ ","
+ "IFNULL("
+ zip
+ ", 'Unknown')"
+ ","
+ "IFNULL("
+ country + ",'Unknown')" + ",'" + tags + "','" + image + "')";
Log.d(LOG_TAG, SQL);
executeWriteQuery(SQL);
ArrayList<Picture> list = getAllPictures();
Log.d(LOG_TAG, "Size :"+list.size());
}
private Cursor executeWriteQuery(String query){
Log.d(LOG_TAG, "execute write query");
SQLiteDatabase db = getWritableDatabase();
Cursor response = db.rawQuery(query, null);
Log.d(LOG_TAG, "write query executed");
return response;
}
All tips/help greatly appreciated!
Thomas
Try to put a semicolon at the end of table creation query. In your case as show below
private String pictureTable() {
return "CREATE TABLE geophoto_db_pictures ( picid integer,"
+ "name varying character(50),"
+ "city varying character(20) NOT NULL,"
+ "zipcode varying character(20) NOT NULL,"
+ "country varying character(20) NOT NULL,"
+ "picdate datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,"
+ "tags varying character(200),"
+ "image varying character(200) NOT NULL,"
+ "uploaded integer NOT NULL DEFAULT 0, PRIMARY KEY (picid));";
}
While providing a query through an external String, you will need to provide SQL query with an end of statement ;. Using the primitive SQLite does not require ; as it just takes arguments and create function query itself. I have experienced both cases and I ended up understanding the way I have put it here.
The problem you are facing is that you are trying to use rawQuery() to insert a record, when you should be using execSQL() instead (see this answer).
So, the correct code for executeWriteQuery would be as follows:
private void executeWrite(String command){
Log.d(LOG_TAG, "execute write");
SQLiteDatabase db = getWritableDatabase();
db.execSQL(command);
Log.d(LOG_TAG, "write executed");
}
Also, consider using insert() instead as that will allow you to get a return value to determine whether or not the data was inserted successfully.

Can get ID from received phone number, but not group

I have succeded in getting the ID and name from a phone number that is calling in. What I would like to to is to see which groups this ID belongs to. I have tried the following:
//Search for the information about the phone number, save the goupID(s)
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(aNumber));
ContentResolver cr = mService.getContentResolver();
Cursor myCursor = cr.query(uri, new String[]{PhoneLookup._ID, PhoneLookup.DISPLAY_NAME},null, null, null);
myCursor.moveToFirst();
//String contactID = myCursor.getString(myCursor.getColumnIndex(PhoneLookup._ID));
String contactID = myCursor.getString(myCursor.getColumnIndex(ContactsContract.Contacts._ID));
myCursor.close();
//Use the cursor to query for group with help of ID from the Phone look up
myCursor = cr.query(ContactsContract.Groups.CONTENT_URI,
new String[]{ContactsContract.Groups._ID},
ContactsContract.Groups._ID + " = ?",
new String[]{contactID},
null);
//Contact may be in more than one group
nbrOfGroups = myCursor.getCount();
groupName = new String [nbrOfGroups];
The problem is tha second query, where I would like to use the contactID that i found in the phone lookup, to see which groups that contacID belongs to. The result is no group, although the contact is added to a group in my contacs.
Any ideas? :)
Groups._ID is not same as Contact ID, instead it is the index for the table storing all the group information. After you get the contact ID you should get all the group membership for that contact from the data table by using the Group membership mimetype.
After getting the group ids you can query the Groups table to get the TITLE for all the groups
try with this code
//Search for the information about the phone number, save the goupID(s)
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode("123123"));
ContentResolver cr = this.getContentResolver();
Cursor myCursor = cr.query(uri, new String[]{PhoneLookup._ID, PhoneLookup.DISPLAY_NAME},null, null, null);
myCursor.moveToFirst();
//String contactID = myCursor.getString(myCursor.getColumnIndex(PhoneLookup._ID));
String contactID = myCursor.getString(myCursor.getColumnIndex(ContactsContract.Contacts._ID));
myCursor.close();
//Use the cursor to query for group with help of contact ID from the Phone look up
myCursor = cr.query(ContactsContract.Data.CONTENT_URI,
new String[]{ContactsContract.Data.CONTACT_ID,
ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID},
ContactsContract.Data.CONTACT_ID + " = ? " +
Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'",
new String[]{contactID},
null);
//Contact may be in more than one group
int nbrOfGroups = myCursor.getCount();
int[] groupIds = new int[nbrOfGroups];
int index = 0;
// unfortunately group names are stored in Groups table
// so we need to query again
if (myCursor.moveToFirst()) {
do {
groupIds[index] = myCursor.getInt(1); // Group_row_id column
} while (myCursor.moveToNext());
}
myCursor.close();
// construct the selection
StringBuffer sb = new StringBuffer();
for (int i = 0; i < nbrOfGroups; i++) {
if (i != 0) {
sb.append(",");
}
sb.append(groupIds[i]);
}
String[] groupName = new String [nbrOfGroups];
myCursor = cr.query(ContactsContract.Groups.CONTENT_URI,
new String[]{ContactsContract.Groups.TITLE},
ContactsContract.Groups._ID + " IN (" + sb.toString() + ")",
null, null);
// finally got the names
if (myCursor.moveToFirst()) {
do {
groupName[index] = myCursor.getString(0); // Group_row_id column
} while (myCursor.moveToNext());
}
myCursor.close();

Categories

Resources