I am Trying to loop through a list of numbers and send them a message but somehow my code is throwing a null pointer exception and i can't figure out where is the problem.
here the code
import java.util.ArrayList;
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.telephony.SmsManager;
import android.widget.Toast;
public class MSGHandler {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
public BroadcastReceiver smsDeliveredReceiver,smsSentReceiver;
public MSGHandler(Context c,List<String> Name,List<String> Number,String Message)
{
int Limit = Name.size();
for(int i = 0; i < Limit;i++)
{
if(Number.get(i).length() > 0)
{
SmsManager sms = SmsManager.getDefault();
PendingIntent piSent=PendingIntent.getBroadcast(c, 0, new Intent(SENT), 0);
PendingIntent piDelivered=PendingIntent.getBroadcast(c, 0, new Intent(DELIVERED),0);
//---when the SMS has been sent---
smsSentReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
break;
}
}
};
//---when the SMS has been delivered---
smsDeliveredReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
break;
case Activity.RESULT_CANCELED:
break;
}
}
};
c.registerReceiver(smsSentReceiver, new IntentFilter("SMS_SENT"));
c.registerReceiver(smsDeliveredReceiver, new IntentFilter("SMS_DELIVERED"));
sms.sendTextMessage(Number.get(i), null, Name.get(i)+Message, piSent, piDelivered);
}
}
}
}
I am Calling this classes in an activity on a button click. Like this
Dialog Alert = new Dialog(MainActivity.this);
try
{
MSGHandler sms = new MSGHandler(MainActivity.this,DBHandler.Contacts_Name_List,DBHandler.Contacts_Number_List,"HII!!!!");
}catch(Exception e)
{
Alert.setTitle(e.toString());
}
Alert.show();
I am Using Eclipse and using my device as an emulator
here's log
error opening trace file: No such file or directory (2)
loaded /system/lib/egl/libEGL_mali.so
loaded /system/lib/egl/libGLESv1_CM_mali.so
loaded /system/lib/egl/libGLESv2_mali.so
Enabling debug mode 0
(When the exception is thrown in the app .. log displays nothing )
Here are the ADb logs after i try to send the msg and the exception is thrown
Any Solutions?
Well a nice sleep helped me alot and i found out that the exception was being thrown because i was trying to message on a blank number i.e " " a space
and the solution was using
if(Number.get(i).trim().length() > 0)
instead of
if(Number.get(i).length() > 0)