How to read last 3 sms from inbox in Android? - android

I used this code
String msgData = "";
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
cursor.moveToFirst();
do{
for(int idx=0;idx<cursor.getColumnCount();idx++)
{
msgData += " " + cursor.getColumnName(idx) + ":" + cursor.getString(idx);
}
}while(cursor.moveToNext());
..and it works, but it returns more data than I want.
How to read 3 last sms (only msg and sender)?

Simply sort the results by date and use the limit clause:
getContentResolver().query(SMS_INBOX, new String[] {body, address},
null, null, "date desc limit 3");

Related

Reading contact phone numbers works for some and not others?

I am reading contact names and phone numbers from the contacts list in Android. I am reading the names successfully. However, when I go to look up a contact phone number by name (which are all unique in this case, it's just a test), it works perfectly for only one contact, gets no phone number for others, and gets the wrong phone number for one.
Here is the code in my getNumbers method:
private String getNumber(String name){
String returnMe="";
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null,
"DISPLAY_NAME = '" + getIntent().getStringExtra("name") + "'", null, null);
if(cursor.moveToFirst()){
String identifier = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Phone._ID + " = " + identifier, null, null);
while(phones.moveToNext()){
returnMe = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
switch(type){
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
System.out.println("mobile number found"); break;
default:
System.out.println("nothing found."); break;
}
}
}
return returnMe;
}
You're doing a few things wrong:
1) The second query must target the Data table, not the Phone table:
Cursor phones = contentResolver.query(ContactsContract.Data.CONTENT_URI, ...
and specify that you want the Phone number in the DATA1 column in the where clause:
Data.MIMETYPE = Phone.CONTENT_ITEM_TYPE
2) You need to filter the results by the RawContact's _ID
This compares the _ID of the Contact row with the _ID of the Phone row, which have very little chance to be the same:
ContactsContract.CommonDataKinds.Phone._ID + " = " + identifier
This compares the Data.CONTACT_ID with the cursor's Contact._ID property
Data.CONTACT_ID + " = " + identifier
The example on the Data javadoc page gives a more complete example:
Finding all Data of a given type for a given contact
Cursor c = getContentResolver().query(Data.CONTENT_URI,
new String[] {Data._ID, Phone.NUMBER, Phone.TYPE, Phone.LABEL},
Data.CONTACT_ID + "=?" + " AND "
+ Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'",
new String[] {String.valueOf(contactId)}, null);
See my answer:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//Query phone here
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()) {
// Get phone numbers here
}
pCur.close();
}
}
}
}

Android sqlite return number of rows from query

I am trying to build a method to determine if a user exists in an Android sqlite database before inserting, I have tried to build this method to return the number of rows, however If I try a search for like matches like this
String[] columns = new String[] { SCREEN_NAME, NAME, PROFILE_IMAGE_URL,
USER_ID };
Cursor c = friendsDatabase.query(DATABASE_TABLE, columns, SCREEN_NAME
+ " LIKE '" + screenName + "%'", null, null, null, null);
c.moveToFirst();
Integer count= c.getCount();
c.close();
return count;
I get the number of rows returned no problem however the minute I look for an exact match like this
String[] columns = new String[] { SCREEN_NAME, NAME, PROFILE_IMAGE_URL,
USER_ID };
Cursor c = friendsDatabase.query(DATABASE_TABLE, columns, SCREEN_NAME
+ " = '" + screenName + "'", null, null, null, null);
c.moveToFirst();
Integer count= c.getCount();
c.close();
return count;
I get 0 rows every time no matter if it matches or not, Im not sure if theres something wrong with my SQL or maybe im using the wrong arguments to make the statement, any help would go a long way thanks
Try this code it might work
Using Raw Query
Cursor mCount= db.rawQuery("select count(*) from "+ DATABASE_TABLE +" where "+SCREEN_NAME+"='" + SCREEN_NAME + "'", null);
mCount.moveToFirst();
int count= mCount.getInt(0);
mCount.close();
Or using the same code but differently
db.query(DATABASE_TABLE , columns, SCREEN_NAME=?, new String[] { SCREEN_NAME}, null, null, null);
c.moveToFirst();
Integer count= c.getCount();
c.close();

Android sms reading by number

I am working on a sms application. in my App I have to list all the convrsation .SO i use the following Uri.
content://mms-sms/conversations/
Its working fine.And the following is my code snippet.
Uri uri = Uri.parse("content://mms-sms/conversations/");
Cursor c= getContentResolver().query(uri, null, null ,null,null);
startManagingCursor(c);
if(c.moveToFirst()){
for(int i=0;i<c.getCount();i++){
body[i]= c.getString(c.getColumnIndexOrThrow("body")).toString();
number[i]=c.getString(c.getColumnIndexOrThrow("address")).toString();
c.moveToNext();
}
}
c.close();
for (int i = 0; i < body.length; i++) {
System.out.println("body ="+body[i]);
System.out.println("number ="+number[i]);
}
The number prints each conversations number and body prints the each conversations last message. But i want to get each conversations whole message and also help me to conversation for a specific number.
From Conversationscursor, You can get thread_id. Once you got thread_id, continue query from sms provider to return all message which has the same thread_id
Example : thread_id = 2
Uri SMS_INBOX = Uri.parse("content://sms");
Cursor c = getContentResolver().query(SMS_INBOX, null, "thread_id" + " = "
+ "2", null,
"date" + " ASC");
while (c.moveToNext()){
Log.v("BODY", c.getString(11).toString()); // 11 is the index of body with project URI
}

Is it possible to have sqlite query that seraches for two keys?

All the examples I see for doing a query show only using one key. Is it possible to use two keys. I have tried the code below and it does not work. I am trying to find the row where date and time match the date and time in the table
public String getPrimaryID(int date, int time )
{
Cursor c= db.query(DB_TABLE, new String[]{KEY_ROWID}, "date="+date+ "time=" + time, null, null, null, null);
int id=c.getColumnIndex(KEY_ROWID);
String result=c.getString(id);
return result;
}
I think you need to AND your query:
Cursor c= db.query(DB_TABLE, new String[]{KEY_ROWID}, "date="+date+ " AND time=" + time, null, null, null, null);
try this :
Cursor c = db.query(TABLENAME, null, "date = ? AND time = ?", new String[] { date, time }, null, null, null, null);
or :
String query ="SELECT * FROM " + TABLENAME + " " + "WHERE "
"date = ? " +
"AND time = ? ";
Cursor c = db.rawQuery(query, new String[] {date, time});
Explanation : variables date and time will replace the ? characters on the query

Android; I only have 2 contacts, yet I can obtain 5 from a query, why?

I have setup 2 test contacts in my emulator.
I'm running the following query, it should pick them both out, populate my domain object, and add to a list. The output at the bottom should therefore be 2, but it is 5, why is this? (cursor.getCount() is 5 instead of 2)
I have stepped through each iteration of the while loop and it is retreving the same contact multiple times, but with different values for POSTCODE, such as the phone number
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI,
null, null, null, null);
List<MeCercanaContact> contacts = new ArrayList<MeCercanaContact>();
if (cursor.getCount() > 0)
{
while (cursor.moveToNext())
{
MyContact myContact = new MyContact();
String givenName = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
String postcode = cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
myContact.setFirstName(givenName);
myContact.setLastName(postcode);
contacts.add(myContact);
}
}
System.out.println(contacts.size());
After API 21 We Write this Query for remove contact duplicacy.
String select = ContactsContract.Data.HAS_PHONE_NUMBER + " != 0 AND " +
ContactsContract.Data.MIMETYPE
+ " = " + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "
AND "+ ContactsContract.Data.RAW_CONTACT_ID + " = " +
ContactsContract.Data.NAME_RAW_CONTACT_ID;
Cursor cursor = mContent.query(ContactsContract.Data.CONTENT_URI, null, select,
null, null);
You are querying ContactsContract.Data, which is a generic container that holds a list of various contact details, such as phone numbers, postal codes etc.. You must filter the results for the rows whose ContactsContract.Data.MIMETYPE column equals StructuredPostal.CONTENT_ITEM_TYPE:
So change the query to:
Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI,
null, null, ContacsContract.Data.MIMETYPE + "='" +
ContactsContract.StructuredPostal.CONTENT_ITEM_TYPE + "'", null);
See ContactsContract.Data
a contact that is registered to multiple groups will show up multiple times
if you query the Uri CONTENT_URI = ContactsContract.Data.CONTENT_URI
Add this to your SELECTION:
+ ContactsContract.Data.DATA1 + " = 1 " ; //show only contacts in group 1

Categories

Resources