Reputation: 1312
I am trying to make android app that read the content of a sms and when the phone get new sms the app do notification. This is what i have(i took it from a website):
public class SMSRead extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView view = new TextView(this);
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
String sms = "";
while (cur.moveToNext()) {
sms += "From :" + cur.getString(2) + " : " + cur.getString(11)+"\n";
}
view.setText(sms);
setContentView(view);
}
}
Currently, the code prints the originating number of the SMS, but it does not display the body of the message cur.getString(11)
, instead displaying null
I have also implemented the following permission:
<uses-permission android:name="android.permission.READ_SMS"/>
Upvotes: 0
Views: 253
Reputation: 970
Here is a sample that, in an ideal world, should work:
public List<Sms> getAllSms(String folderName) {
List<Sms> lstSms = new ArrayList<Sms>();
Sms objSms = new Sms();
Uri message = Uri.parse("content://sms/"+folderName);
ContentResolver cr = mActivity.getContentResolver();
Cursor c = cr.query(message, null, null, null, null);
mActivity.startManagingCursor(c);
int totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int i = 0; i < totalSMS; i++) {
objSms = new Sms();
objSms.setId(c.getString(c.getColumnIndexOrThrow("_id")));
objSms.setAddress(c.getString(c
.getColumnIndexOrThrow("address")));
objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
objSms.setReadState(c.getString(c.getColumnIndex("read")));
objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
lstSms.add(objSms);
c.moveToNext();
}
}
// else {
// throw new RuntimeException("You have no SMS in " + folderName);
// }
c.close();
return lstSms;
}
This example reads all the messages in the inbox. With a little fiddle, you should be able to get it to read a single message.
Upvotes: 0
Reputation: 93668
Because it doesn't have 11 columns. Do a getColumnCount and you'll see that.
Basically, you should not depend on the order of columns unless you're providing them. You aren't. Instead, use getColumnIndex(String columnName) to figure out which column is the body.
Upvotes: 1