Reputation: 129
I'm newbie to android please help me in my problem. I want to send message to multiple numbers. The numbers are saved in SQLite database. I want to send the message to all the numbers saved in database table.
Here's my code so far it only send sms to only one number in my database. It only send to the first number in my table.
private void sendSMS(String message) {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.SEND_SMS},
MY_PERMISSION_REQUEST_SEND_SMS);
}else{
SmsManager sms = SmsManager.getDefault();
SQLiteDatabase db = myDB.getWritableDatabase();
Cursor res = db.rawQuery("select * from recipients_tbl", null);
if(res != null && res.moveToFirst()) {
String num = res.getString(1);
sms.sendTextMessage(num, null, message, sentPI, deliveredPI);
}
}
}
Upvotes: 0
Views: 299
Reputation:
All you need to do is iterate through the Cursor e.g.
private void sendSMS(String message) {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.SEND_SMS},
MY_PERMISSION_REQUEST_SEND_SMS);
}else{
SmsManager sms = SmsManager.getDefault();
SQLiteDatabase db = myDB.getWritableDatabase();
Cursor res = db.rawQuery("select * from recipients_tbl", null);
while (res.moveToNext()) { //<<<<<<<<<< CHANGED
String num = res.getString(1);
sms.sendTextMessage(num, null, message, sentPI, deliveredPI);
}
res.close();
}
}
if(res.moveToFirst()) .....
is better than if(res != null && res.moveToFirst()) .....
.Upvotes: 1
Reputation: 22437
First thing first, change:
SQLiteDatabase db = myDB.getWritableDatabase();
to:
SQLiteDatabase db = myDB.getReadableDatabase();
Because you are not writing to database.
Then, what you have to do is, iterate through each and every row:
while(res.moveToNext())
{
String num = res.getString(1);
sms.sendTextMessage(num, null, message, sentPI, deliveredPI);
}
res.close();
You know, Cursor is pointing at the first row and you have to get that cursor to next row by moveToNext()
. And lastly donot forget to close the Cursor
.
FYK: What's the best way to iterate an Android Cursor?
Upvotes: 1
Reputation: 1368
The reason it is only sending it to the first number is you are not looping trough your result. In order for it to work you will need to write your code like this:
if(res != null){
for(res.moveToFirst(); !res.isAfterLast(); res.moveToNext())
{
String num = res.getString(1);
sms.sendTextMessage(num, null, message, sentPI, deliveredPI);
}
}
Upvotes: 1