Android, add a condition to my button (SMS app) [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
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)

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
}

Try
if(TextUtils.isEmpty(nyanumtxt.getText().toString()))

Related

Why does the notification not show up in API 28?

I have looked at android documentation and I have seen all the answers in StackOverflow, however, I cannot seem to understand why the notification I am trying to show not show up. Whenever I click the button, instead of notification showing up, the app crashes, can someone please give me insight as to why this is occurring?
notify_me.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("miscellaneous", "Hello World", NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Hello Brothers and Sisters");
NotificationManager noti = getSystemService(NotificationManager.class);
noti.createNotificationChannel(channel);
}
}
}
);
Here is the stack trace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.test, PID: 27996
java.lang.IllegalArgumentException: Reserved id
at android.os.Parcel.createException(Parcel.java:1970)
at android.os.Parcel.readException(Parcel.java:1934)
at android.os.Parcel.readException(Parcel.java:1884)
at android.app.INotificationManager$Stub$Proxy.createNotificationChannels(INotificationManager.java:1888)
at android.app.NotificationManager.createNotificationChannels(NotificationManager.java:577)
at android.app.NotificationManager.createNotificationChannel(NotificationManager.java:565)
at com.example.test.Main4Activity$1.onClick(Main4Activity.java:44)
at android.view.View.performClick(View.java:7352)
at android.widget.TextView.performClick(TextView.java:14177)
at android.view.View.performClickInternal(View.java:7318)
at android.view.View.access$3200(View.java:846)
at android.view.View$PerformClick.run(View.java:27800)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7050)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
Caused by: android.os.RemoteException: Remote stack trace:
at com.android.server.notification.RankingHelper.createNotificationChannel(RankingHelper.java:641)
at com.android.server.notification.NotificationManagerService$12.createNotificationChannelsImpl(NotificationManagerService.java:2585)
at com.android.server.notification.NotificationManagerService$12.createNotificationChannels(NotificationManagerService.java:2600)
at android.app.INotificationManager$Stub.onTransact(INotificationManager.java:292)
at android.os.Binder.execTransact(Binder.java:739)
As per the error message, you cannot use "miscellaneous" as the ID of your notification channel - that name is reserved specifically for apps that don't target API 26 or higher for posting all notifications that don't have a channel attached to them.
You can use any other id string for your channel.

How to fix error in Dialog after dismiss and click again?

I'm developing webview app, the problem in OnJsAlert that when i click on the Dialog it opens after dismiss it and click again it stop my app, for sorry i can't get the problem from debugging.
This is my MainActivity.class
#Override
public boolean onJsAlert(WebView view, String url, final String alertSource, final JsResult alertResult) {
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.activity_alert);
alertDialog.setCancelable(true);
TextView alertMessage = alertDialog.findViewById(R.id.alert_text);
alertMessage.setText(alertSource);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
alertResult.cancel();
}
});
alertDialog.show();
return true;
}
Edited : Log
W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
E/ViewRootImpl: sendUserActionEvent() mView == null
W/System.err: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
W/System.err: at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:331)
at android.app.Dialog.requestWindowFeature(Dialog.java:1057)
at com.xcoder.stepview.MainActivity$4.onJsAlert(MainActivity.java:285)
at com.android.webview.chromium.WebViewContentsClientAdapter.handleJsAlert(WebViewContentsClientAdapter.java:606)
at com.android.org.chromium.android_webview.AwContentsClientBridge.handleJsAlert(AwContentsClientBridge.java:73)
at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:27)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5641)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1288)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1104)
at dalvik.system.NativeStart.main(Native Method)
A/libc: Fatal signal 6 (SIGABRT) at 0x00002c6d (code=-6), thread 11373 (xcoder.stepview)
Application terminated.
Your alertDialog is created before public boolean onJsAlert(...) method called and when it's called second time you got AndroidRuntimeException: requestFeature() must be called before adding content because of you can't use requestWindowFeature() with created dialog. You have to create new instance of dialog in this method or reuse global defined dialog.

How to fix Unable to add window when use Dialog in Android [duplicate]

This question already has answers here:
Unable to add window -- token null is not valid; is your activity running?
(10 answers)
WindowManagerBadTokenException unable to add window
(1 answer)
Closed 4 years ago.
In my application I want use dialog and for this I should set custom view to dialog.
I write below codes, but when running application show me ForceClose error on LogCat.
My Codes :
if (!isPremium) {
count = prefsUtils.getFromShared_INT(PrefsKeys.TRIAL_COUNT.name());
prefsUtils.setToShared_INT(PrefsKeys.TRIAL_COUNT.name(), count + 1);
if (count > 10) {
final Dialog dialog = new Dialog(getApplicationContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_end_trial);
TextView dialogEndCount_premiumTxt = dialog.findViewById(R.id.dialogEndCount_premiumTxt);
dialogEndCount_premiumTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, MainActivity2.class);
startActivity(intent);
finish();
dialog.dismiss();
}
});
dialog.show();
}
}
Error message on LogCat :
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:702)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
at android.app.Dialog.show(Dialog.java:337)
at com.mcc.wpnews.activity.PostDetailsActivity.initView(PostDetailsActivity.java:176)
at com.mcc.wpnews.activity.PostDetailsActivity.onCreate(PostDetailsActivity.java:104)
at android.app.Activity.performCreate(Activity.java:6754)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2787) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6247) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762) 
How can I fix it?
Do not use getApplicationContext() unless you know why you are using getApplicationContext().
You cannot show a Dialog using the Application. So, replace new Dialog(getApplicationContext()) with new Dialog(this), and you should have better luck.
See this classic blog post from Dave Smith for more about when to use different types of Context.

App not running on switching between Activities

I have two Activities
1. List view (multiple items each with title and link)
2. Text View( when click on any item in list view, fetches the link, do xml parsing and fetch the content and displayed)
I used intent to switch from List view to text view activity. Now on first time click, it start the text view activity. On pressing devices back button, it goes again to List view. Uptil now it's all right.
The main problem is that when the second time , i click on any item in List view, Android App gives me error of "Unfortunately application has stopped" .
and On clicking "OK" , it displayed the content of second item. and when second time , i pressed back button , application got closed
Here is my Second activity
public class ColoumnView extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_coloumn_view);
Intent intent = getIntent();
String message = intent.getStringExtra(MainListActivity.EXTRA_MESSAGE);
TextView myColoumnView = (TextView)findViewById(R.id.ColoumnView);
myColoumnView.setText(message);
}
#Override
public void onBackPressed()
{
// code here to show dialog
super.onBackPressed();
finish();
}
Here is the part of my first activity where it is creating an intent
protected void onPostExecute(List<ContentGetter.Content> contents) {
if (contents != null && mException == null) {
for(int i=0; i<contents.size();i++) {
if(contents.get(i).summary != null )
{
summaryContent= contents.get(i).summary;
}
else {
continue;
}
Intent intent = new Intent(MainListActivity.this,ColoumnView.class);
intent.putExtra(EXTRA_MESSAGE, summaryContent);
startActivity(intent);
Log.d(TAG, contents.get(i).summary != null ? contents.get(0).summary : "NULL");
}
} else {
if (mException instanceof IOException){
} else if (mException instanceof XmlPullParserException) {
}
}
}
Edit: Here is the crash Log
11-01 13:11:46.274 2296-2296/com.example.talha.appforblog E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.talha.appforblog, PID: 2296
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:139)
at com.example.talha.appforblog.MainListActivity$DownloadXmlTaskContent.onPostExecute(MainListActivity.java:241)
at com.example.talha.appforblog.MainListActivity$DownloadXmlTaskContent.onPostExecute(MainListActivity.java:206)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
The problem is in line no 241 of activity MainListActivity. You are calling a print there which is not having a proper msg to print for time being comment that line. If you share the line of code in that line that would help me narrow it down
Looks like this is doing it...
Log.d(TAG, contents.get(i).summary != null ? contents.get(0).summary : "NULL");
Ensure that your log message is not null, in this case, contents.get(0).summary.

NullPointerException in BroadcastReceiver

I am totally new to Android development, so I apologize before hand if what I'm asking is really simple, I've been Googleing around for the past couple of hours with no luck.
In my MainActivity I reference AlarmReceiver.class in an Intent and then into a PendingIntent and finally it is set to an AlarmManager. Which I do to set an alarm, and this works fine, it's when the alarm is triggered the Exception happens.
Intent intent = new Intent(ourContext, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ourContext, 666, intent, 0);
AlarmManager alarmManager = (AlarmManager) ourContext.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
And then in AlarmReceiver.class it extends BroadcastReceiver, and makes an SDK call.
This part of the code in run whenever the Alarm triggers, meaning when the selected time is neigh, run this code.
public void onReceive(Context arg0, Intent arg1) {
SDK.sendNotification(arg0, new Notification("alarm", "Top Line", "Bottom Line"), new SendNotificationListener() {
#Override
public void onSuccess(String s) {
Log.d("success", s);
}
#Override
public void onFailed(String s) {
Log.d("fail", s);
}
});
}
SendNotification takes 3 variables, a context, a Notification and a NotificationListener.
What I've been able to determine, I am pretty sure that it's the NotificationListener that is the problem and causes the error.
Here is the stacktrace:
Process: com.example.timer:remote, PID: 27665
java.lang.RuntimeException: Unable to start receiver com.example.timer.AlarmReceiver: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2452)
at android.app.ActivityThread.access$1700(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
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:796)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.imer.AlarmReceiver.onReceive(AlarmReceiver.java:21)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2445)
at android.app.ActivityThread.access$1700(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
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:796)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
This is line 21:
SDK.sendNotification(arg0, new Notification("alarm", "Top Line", "Bottom Line"), new SendNotificationListener() {
If the exception is thrown here:
SDK.sendNotification(arg0,
new Notification("alarm", "Top Line", "Bottom Line"),
new SendNotificationListener() {
then the only possible explanation is that SDK is null. Check that it is properly initialized; i.e. a non-null value has been assigned to it. (And check that you don't have multiple declarations ... and that some of them are not initialized.)
You posted this as (supposed) counter-evidence.
SDK.initiate(getActivity(), "DEVCODE", new String[] { Scope },
new AuthListener() {
That doesn't set SDK to a non-null value. It doesn't set (hint: assign) anything to SDK.
(But hypothetically, it would give an NPE if SDK is a variable, it is null and initiate is an instance method.)
That statement may not be executed.
Even if that SDK variable is not null, there could be another declaration of SDK.
In short, that doesn't prove anything.

Categories