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

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.

Related

How to show an alert dialog anywhere in my application?

I have an android application where on BaseActivity, I need to check for some logic and trigger to show an alert dialog irrespective of the Activity opened. It means, no matter which activity class I am in, the alert dialog should show up on top of that activity.
Making sure that, all my activities extends BaseActivity.
Below, is my function to show alert dialog
if (activity != null && !activity.isFinishing()) {
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext(), R.style.Theme_AppCompat)
.setCancelable(false)
.setMessage("There is some unsynced data. Please connect it to internet and sync it. The user will be logged out if data is not synced for 72 hours")
.setTitle("Attention")
.setPositiveButton("OK", listener);
Dialog dialog = builder.create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
dialog.show();
}
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3822)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3854)
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:145)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1816)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6718)
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:858)
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:798)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:329)
at com.gmp_manage_v2.ui.activities.BasePrinterActivity.showAlertToSyncData(BasePrinterActivity.java:463)
at com.gmp_manage_v2.ui.activities.BasePrinterActivity.onResume(BasePrinterActivity.java:304)
at com.gmp_manage_v2.ui.activities.ActiveSessionListActivity.onResume(ActiveSessionListActivity.java:470)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1412)
at android.app.Activity.performResume(Activity.java:7300)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3814)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3854) 
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:51) 
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:145) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1816) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6718) 
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:858) 
You should use current activity context rather than Application context.
Change
new AlertDialog.Builder(getApplicationContext(), R.style.Theme_AppCompat)
to
new AlertDialog.Builder(activity, R.style.Theme_AppCompat)
getApplicationContext() can be used only if you are using dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT) with permission <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

My AsyncTask in another class is causing NullPointerException when it is called in this class

I am quite new to android development and I am facing a NullPointerException when I am trying to call an AsyncTask which is an inner class in another class.
I believe it is the way I am instantiating it but this is what I have:
// This onClick is in my adapter class - which is a separate Java File and class
#Override
public void onClick(View v) {
UploadRes uploadRes = new UploadRes();
UploadRes.UploadResConfirm uploadResConfirm = uploadRes.new UploadResConfirm(v.getContext());
uploadResConfirm.execute(fileName, filePath);
}
public class UploadResConfirm extends AsyncTask<String, String, String> {
Dialog dialog;
Context context;
public UploadResConfirm(Context context){
this.context = context;
}
#Override
protected void onPreExecute(){
dialog = new Dialog(UploadRes.this);
dialog.setTitle("Currently uploading");
dialog.show();
}
I believe it has got something to do with the dialog box itself being instantiated in the AsyncTask class.
The error stack trace on Logcat - its the Dialog, I think its in the wrong place...
java.lang.NullPointerException
at codeman.androapp.UploadRes$UploadResConfirm.onPreExecute(UploadRes.java:246)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Some help if any would be much obliged.
Instead of dialog = new Dialog(UploadRes.this);
Try
dialog = new Dialog(context);
your are passing a wrong context to create dialog.

BadTokenException even after referring to Activity and not the application context

android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#406a6678 is not valid; is your activity running?
at android.view.ViewRoot.setView(ViewRoot.java:528)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.Dialog.show(Dialog.java:241)
at android.app.Activity.showDialog(Activity.java:2569)
at android.app.Activity.showDialog(Activity.java:2527)
at MyCode$8$4.run(MyCode.java:557)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
at dalvik.system.NativeStart.main(Native Method)
I am getting above exception when following code is executed. This file dialog will shown once the processing is done and progressbar reaches 100%. FileSaveDialog extends Dialog and implements OnCompletionListener
runOnUiThread(new Runnable() {
#Override
public void run() {
showDialog(error.Code());//Line 557
}
});
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
AlertDialog.Builder builder;
final ScrollView scrollView = new ScrollView(this);
final TextView textView = new TextView(this);
switch (id) {
// Other cases are here
case 4:
File playFile = new File(mediaPath, TEMP_WAV_FILE_NAME);
dialog = new FileSaveDialog(this, getResources(),
playFile.getAbsolutePath(), saveDiscardHandler);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// do whatever you want the back key to do
cleanUp();
}
});
break;
// Other cases are here
default:
dialog = null;
}
return dialog;
}
You must check activity isFinishing() If the activity is finishing, returns true; else returns false.

Calling getActivity() inside a Fragment returns null

excuse the trouble I was trying to make a listview for parsing a page for my app, I'll explain: I have a actionbar formed by Fragment.
When instazia the fragment, opening the app the first time "getActivity" does not return null, is the next time, when I start the AsyncTask
In the fragment in which I will stop parsing this error:
java.lang.NullPointerException
at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:104)
at com.megadown.megacodownloader.ParsingArrayAdapter.<init>(ParsingArrayAdapter.java:30)
at com.megadown.megacodownloader.Tab_Search$ParsingPaginaWeb.onPostExecute(Tab_Search.java:264)
at com.megadown.megacodownloader.Tab_Search$ParsingPaginaWeb.onPostExecute(Tab_Search.java:125)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
at dalvik.system.NativeStart.main(Native Method)
Code Java that refers:
protected void onPostExecute(String result)
{
// dopo che ho eseguito il parsing mostro i dati nella listview
adapter = new ParsingArrayAdapter(myActivity, titoli, descrizioni,immagini);
lista.setAdapter(adapter);
}
If you want I can post the code of the ArrayAdapter.
Thank you in advance
First, make sure myActivity has the correct value:
protected void onPostExecute(String result) {
Activity myActivity = getActivity();
adapter = new ParsingArrayAdapter(myActivity, titoli, descrizioni,immagini);
lista.setAdapter(adapter);
}
Next, point is, you can't be sure that your activity and fragment is still active in onPostExecute().
For example, the user could have pressed 'back' button or rotated the screen, which would re-create the activites and fragments.
So, the good code is:
protected void onPostExecute(String result) {
Activity myActivity = getActivity();
if (myActivity==null) return; // Fragment not active anymore, bail out
adapter = new ParsingArrayAdapter(myActivity, titoli, descrizioni,immagini);
lista.setAdapter(adapter);
}
Fragment's getActivity() will only return expectable value while the associated activity has done onCreate method.

windowleaked in android view

Hi I have developed android phonegap app and when dialog is shown and screen orientation changes,showing the error in logcat.How to solve this
Here is my logcat error:
E/WindowManager(5759): Activity com.example.Service.NotificationAlert has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#412c93c0 that was originally added here
E/WindowManager(5759): android.view.WindowLeaked: Activity com.example.Service.NotificationAlert has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#412c93c0 that was originally added here
E/WindowManager(5759): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:344)
E/WindowManager(5759): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:267)
E/WindowManager(5759): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
E/WindowManager(5759): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
E/WindowManager(5759): at android.view.Window$LocalWindowManager.addView(Window.java:537)
E/WindowManager(5759): at android.app.Dialog.show(Dialog.java:278)
E/WindowManager(5759): at com.example.Service.NotificationAlert$1.handleMessage(NotificationAlert.java:103)
E/WindowManager(5759): at android.os.Handler.dispatchMessage(Handler.java:99)
E/WindowManager(5759): at android.os.Looper.loop(Looper.java:137)
E/WindowManager(5759): at android.app.ActivityThread.main(ActivityThread.java:4424)
E/WindowManager(5759): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager(5759): at java.lang.reflect.Method.invoke(Method.java:511)
E/WindowManager(5759): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
E/WindowManager(5759): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
E/WindowManager(5759): at dalvik.system.NativeStart.main(Native Method)
Please tell me the solution.Thanks In Advance.
Here is my code:
AlertDialog alertDialog = new AlertDialog.Builder(NotificationAlert.this).create();
alertDialog.setTitle("Mobilyzer");
msgCountBundle = getIntent().getExtras();
messageCount = msgCountBundle.getInt("Count");
userId = msgCountBundle.getInt("userid");
if (messageCount > 1) {
alertDialog
.setMessage("You have " + messageCount + " New Messages");
} else {
alertDialog.setMessage("You have " + messageCount + " New Message");
}
alertDialog.show();
new Timer().schedule(new task(), 30000);
private class task extends TimerTask
{
public void run()
{
toastHandler.sendEmptyMessage(0);
}
}
private final Handler toastHandler = new Handler() {
public void handleMessage(Message msg) {
if(alertDialog.isShowing())
{
try
{
alertDialog.dismiss();
finish();
Log.i("alertdialog","hide alert dialog");
}
catch(IllegalArgumentException e)
{
Log.e("illegal ","illegal exception in dialog"+e);
}
catch(Exception e)
{
Log.e("illegal ","exception in dialog"+e);
}
}
Log.i("alertdialog","show alert dialog");
}
};
In NotificationAlert Activity you are showing a Dialog that was not dismissed by explicitly calling dismiss() on it when Activity was paused. Keep a reference to your Dialog object and in onPause() call dismiss() on it.
#Override
protected void onPause() {
if (myDialog != null) {
myDialog.dismiss();
}
super.onPause();
}
Check the flow of application .In application you are adding dialog more than one time i think.So, try to solve by adding only one dialog in to activity view.
It is because of some other exception the app is crashing and because the dialog is showing the window leak exception is thrown.
Anyways the window leak exception occurs when the dialog is not null and the activity is finished. So the dialog has to be made null either in onPause() as mentioned above or where the activity is moving to a new screen like before starting an intent. Here you can nullify the dailog in the catch so that the window leak exception can be handled, but there is some other exception in your code. Provide the complete logcat.

Categories