Tim Tim - 15 days ago 4
Java Question

Android, add a condition to my button (SMS app)

I have made an SMS app (I'm a newbie). When the user press a button a message will be sent to a number where the user types in. That goes okay! but when there there is no number (Textview is empty) the app crashes. So i tried adding a condition to when the Textview is empty send a Toast, if it is not empty send message, here my code. I tried diffrent ways but the body in Else is activated anyway? Hope someone can help me :).

sendSMSa2 is my button.
nyanumtxt is where the number is.

sendSMSa2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {


if(nyanumtxt.getText().toString().isEmpty()) {

Toast.makeText(getActivity(), "No Number chossen",
Toast.LENGTH_LONG).show();



} else {


String myMsgrela1 = a2txt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, myMsgrela1);
Toast.makeText(getActivity(), "Message sent!",
Toast.LENGTH_LONG).show();
}

}
}
);


log cat



11-18 21:05:01.505 22083-22083/user.smsgsm20 E/AndroidRuntime: FATAL EXCEPTION: main
Process: c.timno.smsgsm20, PID: 22083
java.lang.NullPointerException
at android.os.Parcel.readException(Parcel.java:1478)
at android.os.Parcel.readException(Parcel.java:1426)
at com.android.internal.telephony.ISms$Stub$Proxy.sendText(ISms.java:881)
at android.telephony.SmsManager.sendTextMessage(SmsManager.java:181)
at c.timno.smsgsm20.Fragment.sendMsg(Fragment.java:359)
at c.timno.smsgsm20.Fragment.access$000(Fragment.java:34)
at c.timno.smsgsm20.Fragment$1.onClick(Fragment.java:184)
at android.view.View.performClick(View.java:4443)
at android.view.View$PerformClick.run(View.java:18475)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
at dalvik.system.NativeStart.main(Native Method)




Answer

I think nyanum text contains blank spaces that's why else condition is executed. try this

if(TextUtils.isEmpty(nyanumtxt.getText().toString().trim())){
//your code
}
else{
//your code
}
Comments