Sms Retrieving not working? - android

I am using 2.1 platform.Trying to retrieve all the SMS from the Emulator. No Compile error, NO Logcat Error in my code.I included the permission for ReadSMS in manifest file.When I run the code no display in the ListView. In my XML file there is only one ListView. On that ListView I am trying to display all the SMS of format ( Number : Sms Body) from the Emulator.
Code
public class SMSActivity extends Activity {
/** Called when the activity is first created. */
ListView lview;
String Body = "" ;
int Number;
ArrayList<String> smslist=new ArrayList<String>();
ArrayAdapter<String> itemAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lview =(ListView)findViewById(R.id.lv);
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,smslist);
lview.setAdapter(itemAdapter);
ContentResolver cr = getContentResolver();
Cursor c = cr.query(Uri.parse("content://sms/"), new String[] { "_id", "address", "date", "body","read" },"_id = "+null, null, null);
while(c.moveToNext()){
Number = c.getInt(c.getColumnIndexOrThrow("address"));
Body = c.getString(c.getColumnIndexOrThrow("body")).toString();
smslist.add( Number + "\n" + Body);
}
itemAdapter.notifyDataSetChanged();
c.close();
}
}
How to solve this problem ?

The error you are doing is you just mentioning that you want to read sms but you forgot to say
from which folder you need them.e.g from inbox,outbox etc..
If you need to read SMS from inbox use following.
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
You can also query column names using
for (int i = 0; i < cursor.getColumnCount(); i++) {
Log.i("info", cursor.getColumnName(i));
}

Related

Android ContactsContract with AutocompleteTextview too slow

Am trying to use the ContactsProvider with my AutoCompleteTextview using a method that fetches the data (name and phone number) and stores them in a list. As expected, this method will always take time to complete as am calling the method in the onCreateView method of my Fragment class.
This is the method:
...
ArrayList<String> phoneValues;
ArrayList<String> nameValues;
...
private void readContactData() {
try {
/*********** Reading Contacts Name And Number **********/
String phoneNumber = "";
ContentResolver contentResolver = getActivity()
.getContentResolver();
//Query to get contact name
Cursor cursor = contentResolver
.query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
null);
// If data data found in contacts
if (cursor.getCount() > 0) {
int k=0;
String name = "";
while (cursor.moveToNext())
{
String id = cursor
.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
name = cursor
.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//Check contact have phone number
if (Integer
.parseInt(cursor
.getString(cursor
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
//Create query to get phone number by contact id
Cursor pCur = contentResolver
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?",
new String[] { id },
null);
int j=0;
while (pCur
.moveToNext())
{
// Sometimes get multiple data
if(j==0)
{
// Get Phone number
phoneNumber =""+pCur.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Add contacts names to adapter
autocompleteAdapter.add(name);
// Add ArrayList names to adapter
phoneValues.add(phoneNumber.toString());
nameValues.add(name.toString());
j++;
k++;
}
} // End while loop
pCur.close();
} // End if
} // End while loop
} // End Cursor value check
cursor.close();
} catch (Exception e) {
Log.i("AutocompleteContacts","Exception : "+ e);
}
}
Am sure there is a better way to accomplish this, but this method works and the suggestions are presented when I type into the AutocompleteTextview. Am just worried about the time it takes. How can I accomplish this without populating an ArrayList?
I have looked at this question: Getting name and email from contact list is very slow and applied the suggestions in the answer to my code, but now nothing is suggested when I type.How can I improve the performance of my current code?
This is how i have implemented AutoCompleteTextView and it works fine for me ..
final AutoCompleteTextView act=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
ArrayList<String> alContacts = new ArrayList<String>();
ArrayList<String> alNames= new ArrayList<String>();
ContentResolver cr = this.getContentResolver(); //Activity/Application android.content.Context
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));
alNames.add(contactName);
alContacts.add(contactNumber);
break;
}
pCur.close();
}
} while (cursor.moveToNext()) ;
}
String[] array=new String[alNames.size()];
array=(String[]) alNames.toArray(array);
ArrayAdapter<String> myArr= new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,array);
act.setAdapter(myArr);
act.setThreshold(1);
I got rid of the slow response by placing the method inside an AsynTask.
public class AutocompleteAsyncTask extends AsyncTask<Void, Void, Void> {
public Void doInBackground(Void...params) {
try {
/*********** Reading Contacts Name And Number **********/
String phoneNumber = "";
ContentResolver contentResolver = getActivity()
.getContentResolver();
//Query to get contact name
Cursor cursor = contentResolver
.query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
null);
// If data data found in contacts
if (cursor.getCount() > 0) {
int k=0;
String name = "";
while (cursor.moveToNext())
{
//...Rest of the same code as above
and then calling this in my onCreateView():
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
new AutocompleteAsyncTask().execute();
return rootView;
}
Now the task of inflating my view and fetching the data are separated into two different threads.
The CursorLoader option mentioned by Eugen Pechanec is kinda the best option, so I'll update this answer with that option when I can.

need advice in designing sms aplication for android

i am designing a sms application for android. i have been successful in sending and receiving the sms. The only problem i have been facing is the layout of the inbox and outbox of my app. I am putting up a image of what i want output like and what i am actually getting right now. Can anyone guide me in achieving the desired result.
The code i have used to fill the inbox is as below
public class Inbox extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inbox);
ListView list = (ListView) findViewById(R.id.list);
List<String> msgList = getSMS();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, msgList);
list.setAdapter(adapter);
}
public List<String> getSMS() {
List<String> sms = new ArrayList<String>();
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
while (cur.moveToNext()) {
String address = cur.getString(cur.getColumnIndex("address"));
String body = cur.getString(cur.getColumnIndexOrThrow("body"));
sms.add("Number: " + address + " .Message: " + body);
}
return sms;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_inbox, menu);
return true;
}
}
Create two activities or fragments and get only the number from database in the first and in the second get the messages related to that number and learn how to create custom listviews
Suggested links:
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
http://www.ezzylearning.com/tutorial.aspx?tid=1763429
http://www.thepcwizard.in/2012/09/android-creating-custom-listview-for.html

Search sms Inbox

How can I search the sms inbox and show latest message from a special number. For example search for "999999999" and show last message received from this number. Is any way to do this?
I have use this code to return the count of messages my inbox
TextView view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = (TextView) findViewById(R.id.textView1);
final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(SMS_INBOX, null, null, null, null);
int unreadMessagesCount = c.getCount();
c.deactivate();
view.setText(String.valueOf(unreadMessagesCount));
If you only want the last message sent by a specific number use this:
final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(SMS_INBOX, null, "address = ?",
new String[] {"9999999999"}, "date desc limit 1");
if(cursor.moveToFirst()) {
// Do something
Log.v("Example", cursor.getString(cursor.getColumnIndex("body")));
}
cursor.close();
The second answer to How many database columns associated with a SMS in android? is a great reference for different columns in an SMS.
try as:
final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(SMS_INBOX,null,null, null,"DATE desc");
if(c.moveToFirst()){
for(int i=0;i<c.getCount();i++){
String body= c.getString(c.getColumnIndexOrThrow("body")).toString();
String number=c.getString(c.getColumnIndexOrThrow("address")).toString();
if(number=="999999999")
{
//get message body here
break;
}
else
c.moveToNext();
}
}
c.close();

android: Query SMS Unique DisplayName(s) Efficiently

I'm trying to write an activity that shows the DisplayNames of contacts evolved in SMS conversations.
Unfortunately:
The SMS database doesn't contain the DisplayName
so I used a function that uses the address "phone number" to get the DisplayName
I don't know how to query unique addresses from the SMS database
so I used sorted query, used a loop to find unique DisplayNames, and then put them in an array
If not, is it better to run this process in the background? but how will the activity open if the list is not prepared yet?!
Finally, I used this array in an ArrayAdapter to populate my ListView (pretty much trying to mimic the native Messaging app)
The activity turned out to take a lot of time to open up (around 2-3 seconds, and I don't have much messages)
Is there a way to solve any or both of my problems efficiently?
Here's my code
public class MessagesPicker extends Activity {
Cursor myCursor;
ListView pickerListView;
public static final String MessageAddress = address;
public static final String MessageID = _id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.picker);
ContentResolver cr = getContentResolver();
myCursor = cr.query(Uri.parse(contentsms), null, null, null, MessageAddress + ASC); //getting sorted data to easy finding uniqueness
/**setting up unique DisplayNames array**/
int allCount = myCursor.getCount(), uniqueCount = 0;
String[] uniqueNames = new String[allCount];
String temp1,temp2;
myCursor.moveToFirst();
temp1 = getContactDiplayNameByAddr();
uniqueNames[uniqueCount++] = temp1;
do {
temp2 = getContactDiplayNameByAddr();
if (temp1.compareTo(temp2) != 0){
uniqueNames[uniqueCount++] = temp2;
temp1 = temp2;
}
}while(myCursor.moveToNext());
String [] valuesArray = new String[uniqueCount]; //filling the array
for (int i = 0 ; i uniqueCount ; i++)
valuesArray[i] = uniqueNames[i];
/**setting up the ListView**/
ArrayAdapterString adapter = new ArrayAdapterString(this, android.R.layout.simple_list_item_multiple_choice, valuesArray);
pickerListView = (ListView)findViewById(R.id.PickerLV); //linking the object to the interface
pickerListView.setAdapter(adapter); //setting the adapter
pickerListView.setItemsCanFocus(false); //allowing to check the checkbox
pickerListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); //allowing multiple choices
}
String getContactDiplayNameByAddr() { //this function returns DisplayName, or if not available, returns the address
String Address = myCursor.getString(myCursor.getColumnIndex(address));
Uri personUri = Uri.withAppendedPath( ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Address);
Cursor cur = getContentResolver().query(personUri,
new String[] {PhoneLookup.DISPLAY_NAME},
null, null, null );
if( cur.moveToFirst() ) {
String DisplayName = cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME));
cur.close();
return DisplayName;
}
return Address;
}
}

SMS Sender's Name Shows as labuser in Default SMS App

I installed the following code on my Android 2.2 phone and the sender's name shows as labuser for some messages when it is actually something else :-
public class SMSReaderActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView myListView = (ListView) findViewById(R.id.myListView);
final ArrayList<String> smses = new ArrayList<String>();
final ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, smses);
myListView.setAdapter(aa);
Context context = getApplicationContext();
Cursor cursor = context.getContentResolver().query(
Uri.parse("content://sms/inbox"),
new String[] { "address", "person", "date", "body" }, null,
null, "date desc");
cursor.moveToFirst();
int count = cursor.getCount();
for (int j = 0; j < count; j++) {
String msg = cursor.getString(0) + ", " + cursor.getString(1)
+ ", " + cursor.getLong(2) + ", " + cursor.getString(3);
Log.w("SMS", "Read SMS:" + msg);
if (cursor.getString(3).indexOf("rbs") >= 0) {
smses.add(msg);
Log.w("SMS", "Added");
}
cursor.moveToNext();
}
cursor.close();
aa.notifyDataSetChanged();
}
labuser is not an a/c on my development machine and this happens with only matching smses. I cannot figure out the source of this.
Thanks
Himanshu
Giving it the READ_CONTACTS permission fixed it. That my app, reading SMS's without appropriate permissions, could screw up the default one was strange.

Categories

Resources