I have a code on android that using fragments but when I add an onclick on the code which the sendSMS function will be called an error occured on executing it on a dual sim phone saying "Unfortunately, has stopped" when I click the button btnSendSMS . No error found on LogCat.
Here is my code on the sendSms:
private void sendSMS(String phoneNumber, String message)
{
SmsManager sms = SmsManager.getDefault();
String SENT = "SMS_SENT";
PendingIntent sentPI = PendingIntent.getBroadcast(getActivity(), 0, new Intent(
SENT), 0);
getActivity().registerReceiver(new BroadcastReceiver() {
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getActivity(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getActivity(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getActivity(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getActivity(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getActivity(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
Code on the button:
btnSendSMS = (Button) myFragmentView.findViewById(R.id.button2);
btnSendSMS.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String phoneNo = txtPhoneNo.getText().toString();
String message = txtMessage.getText().toString();
smsGateway = "<my number>";
if(phoneNo.length() == 0) {
Toast.makeText(getActivity(), "Please enter a number!", Toast.LENGTH_LONG).show();
} else if(message.length() == 0) {
Toast.makeText(getActivity(), "Please enter a message!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Message has been sent", Toast.LENGTH_LONG).show();
sendSMS(smsGateway,message);
}
}
});
Please help dont know where is my error. This code works when I extends Activity instead of Fragments and changing getActivity() to getBaseContext().
Thank you!
No comments:
Post a Comment