How to resolve : android.view.WindowManager$BadTokenException - is your activity running? - android

I have an activity with lot of Dialogs for ex Dialog_1, Dialog_2, Dialog_3, I have implemented a WebView in one of the Dialogs lets say Dialog_2. When navigate through the Dialog's, first time the Dialog_2 with the WebView opens with no problem, but second time when I navigate to Dialog_3 and come back to Dialog_2 OR Dialog_1 to Dialog_2 and touch the WebView I get an error as mentioned bellow.
I have looked at Bad token exception but it does not work still using
if (! this.isFinishing()) {
showDialog(DIALOG_ADD_A_PERSON_BODY_MAP)
}
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#41ec0fc8 is not valid; is your activity running?
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#41ec0fc8 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:806)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:265)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:73)
at android.widget.ZoomButtonsController.setVisible(ZoomButtonsController.java:373)
at android.webkit.ZoomControlEmbedded.show(ZoomControlEmbedded.java:41)
at android.webkit.ZoomManager.invokeZoomPicker(ZoomManager.java:1728)
at android.webkit.WebViewClassic.startDrag(WebViewClassic.java:11645)
at android.webkit.WebViewClassic.handleTouchEventCommon(WebViewClassic.java:11170)
at android.webkit.WebViewClassic.onHandleUiTouchEvent(WebViewClassic.java:3225)
at android.webkit.WebViewClassic.onHandleUiEvent(WebViewClassic.java:3135)
at android.webkit.WebViewClassic.access$12000(WebViewClassic.java:278)
at android.webkit.WebViewClassic$PrivateHandler.dispatchUiEvent(WebViewClassic.java:13405)
at android.webkit.WebViewInputDispatcher.dispatchUiEvent(WebViewInputDispatcher.java:1078)
at android.webkit.WebViewInputDispatcher.dispatchUiEvents(WebViewInputDispatcher.java:1066)
at android.webkit.WebViewInputDispatcher.access$300(WebViewInputDispatcher.java:78)
at android.webkit.WebViewInputDispatcher$UiHandler.handleMessage(WebViewInputDispatcher.java:1392)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
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:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
The Dialog code is
case DIALOG_ADD_A_PERSON_BODY_MAP:
try {
LayoutInflater inflaterBodyMap = this
.getLayoutInflater();
final View inflatorBodyMap = inflaterBodyMap
.inflate(
R.layout.dialog_incident_window_body_map,
null);
bodyMapWebView = (WebView) inflatorBodyMap.findViewById(R.id.webView);
bodyMapWebView.getSettings().setJavaScriptEnabled(true);
//bodyMapWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
//bodyMapWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
bodyMapWebView.getSettings().setBuiltInZoomControls(true);
bodyMapWebView.getSettings().setSupportZoom(true);
bodyMapWebView.loadUrl("https://www.google.co.uk");
bodyMapWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
builder.setTitle("Injured person");
builder.setView(inflatorBodyMap);
builder.setPositiveButton("Next",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
showDialog(DIALOG_ADD_A_PERSON_WAS_THE_PERSON_INJURED_ET);
wasThePersonInjured.setText(map_incident_addAPerson.get("InjuredNotes"));
}
});
builder.setNegativeButton("Back",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
showDialog(DIALOG_ADD_A_PERSON_WAS_THE_PERSON_INJURED);
}
});
return builder.create();
} catch (Exception e) {
e.printStackTrace();
}
How do I resolve this error. Your help and suggestions much appreciated.

This happens if your Activity has been killed due to some reason and window token of your activity has expired but you try and access it anyways. So to solve this put this in onPause:
#Override
protected void onPause() {
super.onPause();
if ((progress != null) && progress.isShowing()) {
progress.dismiss();
}
progress = null;
}

Related

alertDialogBuilder crashes only when relaunching the APP

I have a "alertDialogBuilder" to rename an entry when a button is pressed. This works fine when the App is freshly opened. But If I press the back button (meaning the App is minimized and I am back at the Android home-screen), when I relaunch the App and press the button, this time the APP crashes. This happens every time and I have no idea how to debug this. I have checked the lifecycle and "onPause" and "onStop" are called when pressing the back button. But I don't see why that should be a problem.
Any ideas?
Here is the code where I launch the prompt dialogue in a helper class:
public void loadPromptInput(Context promptcontext, final OnOkGetText onOk, String InitialTxt) {
//pathText.setText("Prompt input");
LayoutInflater li = LayoutInflater.from(promptcontext);
View promptsView = li.inflate(R.layout.prompts_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( promptcontext);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
userInput.setText("");
userInput.append(InitialTxt);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
onOk.hereIsYouText(userInput.getText().toString());
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
// make the keyboard shown by default
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com...., PID: 31622
android.view.WindowManager$BadTokenException: Unable to add window --
token android.os.BinderProxy#423c9940 is not valid; is your activity
running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:532)
at
android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at
com....myUtils.loadPromptInput(myUtils.java:71)
at
com....MainActivity$6.onReceive(MainActivity.java:557)
at
android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:308)
at
android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:46)
at
android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:118)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5095)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
at
com.zte.heartyservice.SCC.FrameworkBridge.main(FrameworkBridge.java:136)
at dalvik.system.NativeStart.main(Native Meth
od)
It would be helpful looking at your code to see where you call:
void loadPromptInput(Context promptcontext...
...most probably you are passing as parameter an instance of a context no more valid.
In any case before calling your method check if the activity is finishing:
//in a fragment
if(getActivity() != null && !getActivity().isFinishing()) {
loadPromptInput(getActivity()...
}
//in an activity
if(!isFinishing()) {
loadPromptInput(this...
}

DialogFragment - reference from db to MainActivity Android Studio

In my database when a condition is fulfilles i'd like to appear a AlertDialog popup. I've tried to do it in two ways, like this
dataBaseHandler
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
result = c.getInt(c.getColumnIndex(KEY_COUPONS_TIMES_TO_USE))
-c.getInt(c.getColumnIndex(KEY_COUPONS_TIMES_USED));
if (result < 4) {
MainActivity alert = new MainActivity();
alert.showAlert();
}
}
MainActivity
public void showAlert() {
AlertDialog.Builder myAlert = new AlertDialog.Builder(this);
myAlert.setMessage("Text").create()
myAlert.show();
}
There's no red errors in the code but when a condition is fulfilled during using the application, critical error appears on the screen. Here's what console says
D/QUERY: UPDATE coupons SET times_used = times_used + 1 WHERE id=1
D/AndroidRuntime: Shutting down VM
W/dalvikvm: threadid=1: thread exiting with
uncaught exception(group=0xa4ccfb20)
[10-17 06:13:14.364 1579: 1724 D/]
HostConnection::get() New Host Connection established 0xb9986d90, tid 1724
E/AndroidRuntime: FATAL EXCEPTION: main
Process: promocje, PID: 2744 java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationInfo
(ContextWrapper.java:152)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:103)
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:143)
at android.app.AlertDialog$Builder.<init>(AlertDialog.java:360)
at promocje.MainActivity.showAlert(MainActivity.java:164)
at promocje.db.engine.DatabaseHandler.useCoupon
(DatabaseHandler.java:889)
at promocje.adapter.CouponListAdapter.useCoupon
(CouponListAdapter.java:166)
at promocje.adapter.CouponListAdapter$1$1.onFinish
(CouponListAdapter.java:144)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:118)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Application terminated.
I have tried also to this around in alternate way
dataBaseHandler
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
result = c.getInt(c.getColumnIndex(KEY_COUPONS_TIMES_TO_USE))
- c.getInt(c.getColumnIndex(KEY_COUPONS_TIMES_USED));
if (result < 4) {
PopUpFragment popup = new PopUpFragment();
popup.show(FragmentManager manager, String tag);
}
New java file with Dialog Fragment
public class PopUpFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("I'm a PopUp")
.setPositiveButton("Button 1", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// POSITIVE BUTTON
}
})
.setNegativeButton("Delete me", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
Here i've got some problems with parameters in .show() method.
Any help would be appreciated!

Opencv stopped working on Android 6.0

I am using Opencv on my application and it works fine with Android 4.3 but it doesn't even open with Android 6.0.
I looked up for a solution on SO, and found one that says to set the package name. So I did it.
Follow code:
public static boolean initOpenCV(String Version, final Context AppContext,
final LoaderCallbackInterface Callback)
{
AsyncServiceHelper helper = new AsyncServiceHelper(Version, AppContext, Callback);
Intent intent = new Intent("org.opencv.engine.BIND");
intent.setPackage("org.opencv.engine");
if (AppContext.bindService(intent,
helper.mServiceConnection, Context.BIND_AUTO_CREATE))
{
return true;
}
else
{
AppContext.unbindService(helper.mServiceConnection);
InstallService(AppContext, Callback);
return false;
}
}
But now I am getting the following error:
11-18 10:14:43.447 24901-24930/br.com.ibramed.dermos E/AndroidRuntime: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
11-18 10:14:43.447 24901-24930/br.com.ibramed.dermos E/AndroidRuntime: at android.view.ViewRootImpl.setView(ViewRootImpl.java:571)
11-18 10:14:43.447 24901-24930/br.com.ibramed.dermos E/AndroidRuntime: at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310)
11-18 10:14:43.447 24901-24930/br.com.ibramed.dermos E/AndroidRuntime: at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
11-18 10:14:43.447 24901-24930/br.com.ibramed.dermos E/AndroidRuntime: at android.app.Dialog.show(Dialog.java:319)
in the following code:
case InstallCallbackInterface.NEW_INSTALLATION:
{
Looper.prepare();
Log.d("Debug", ""+mAppContext);
AlertDialog InstallMessage = new AlertDialog.Builder(mAppContext).create();
InstallMessage.setTitle("Package not found");
InstallMessage.setMessage(callback.getPackageName() + " package was not found! Try to install it?");
InstallMessage.setCancelable(false); // This blocks the 'BACK' button
InstallMessage.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
callback.install();
}
});
InstallMessage.setButton(AlertDialog.BUTTON_NEGATIVE, "No", new OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
callback.cancel();
}
});
InstallMessage.show();
} break;
I have searched and found some people saying to keep track of the main Context, because Threads doesn't have context. But my app already does this and use the main context to create the AlertDialogs and it still doesn't work.
The error is when the app show the AlertDialog.
I really don't know what else to do. Can someone help?
As far as I know in service or Aplication class you cant get context with View for android 6.0, so when OpenCv tries to show AlertDialog it does not know to what activity bind dialog and crashes.
Try to init OpenCv in Activity onCreate method before usage.
My working init method in MainActivity (code on kotlin):
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9, this, object : BaseLoaderCallback(this#HistoryActivity) {
override fun onManagerConnected(status: Int) {
if (LoaderCallbackInterface.SUCCESS == status)
Log.i(TAG, "OpenCV was loaded")
else
super.onManagerConnected(status)
}
})
}

Error : BinderProxy#45d459c0 is not valid; is your activity running?

What is this error... i haven't found any discussion on this error in the stackoverflow community Detailed :-
10-18 23:53:11.613: ERROR/AndroidRuntime(3197): Uncaught handler: thread main exiting due to uncaught exception
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#45d459c0 is not valid; is your activity running?
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.view.ViewRoot.setView(ViewRoot.java:468)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.view.Window$LocalWindowManager.addView(Window.java:424)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.app.Dialog.show(Dialog.java:239)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at com.vishal.contacte.Locationlistener$MyLocationListener.onLocationChanged(Locationlistener.java:86)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:179)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:112)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:128)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.os.Handler.dispatchMessage(Handler.java:99)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.os.Looper.loop(Looper.java:123)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.app.ActivityThread.main(ActivityThread.java:4363)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at java.lang.reflect.Method.invokeNative(Native Method)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at java.lang.reflect.Method.invoke(Method.java:521)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:862)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at dalvik.system.NativeStart.main(Native Method)
This is most likely happening because you are trying to show a dialog after execution of a background thread, while the Activity is being destroyed.
I was seeing this error reported once in a while from some of my apps when the activity calling the dialog was finishing for some reason or another when it tried to show a dialog. Here's what solved it for me:
if(!((Activity) context).isFinishing())
{
//show dialog
}
I've been using this to work around the issue on older versions of Android for several years now, and haven't seen the crash since.
2021 Update
It's been noted in some of the comments that it's bad to blindly cast Context to an Activity. I agree!
When I'm writing similar code these days in a Fragment (8+ years after the original answer was provided), I do it more like this:
if (!requireActivity().isFinishing) {
// show dialog
}
The main takeaway is that trying to show a dialog or update any UI after the hosting Activity has been killed will result in a crash. Do what you can to prevent that by killing your background threads when your Activity is killed, or at a minimum, use the answer here to stop your app from crashing.
I faced the same problem and used the code proposed by DiscDev above with minor changes as follows:
if (!MainActivity.this.isFinishing()){
alertDialog.show();
}
if dialog is trowing this problem because of the thread you should do run this on UI thread like that :-
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.show();
}
});
This error occurs when you are showing the dialog for a context that no longer exists.
Before calling .show() check that activity/context is not finishing
if (!(context instanceof Activity && ((Activity) context).isFinishing())) {
alert.show();
}
I encountered this error when I had a countDownTimer in my app. It had a method calling GameOver in my app as
public void onFinish() {
GameOver();
}
but actually the game could be over before the time was up due to a wrong click of the user (it was a clicking game). So when I was looking at the Game Over dialog after e.g. 20 seconds, I forgot to cancel the countDownTimer so once the time was up, the dialog appeared again. Or crashed with the above error for some reason.
The fix to this is pretty simple. Just test if the Activity is going through its finishing phase before displaying the Dialog:
private Handler myHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DISPLAY_DLG:
if (!isFinishing()) {
showDialog(MY_DIALOG);
}
break;
}
}
};
see more here
In my case, the problem was that Context was kept as a weak reference in the class that extends Handler. Then I was passing Messenger, that wraps the handler, through an Intent to a Service. I was doing this each time the activity appeared on screen in onResume() method.
So as you understand, Messenger was serialized together with its fields (including context), because it is the only way to pass objects using Intent - to serialize them. At that moment when Messenger was passed to the service, the activity itself still wasn't ready for showing dialogs as it is in another state (being said onResume(), that is absolutely different from when the activity is already on the screen). So when messenger was deserialized, the context still was at the resuming state, while the activity actually was already on the screen. Moreover, deserialization allocates memory for new object, that is completely different from the original one.
The solution is just to bind to the service each time you need it and return a binder that has a method like 'setMessenger(Messenger messenger)' and call it, when you are binded to the service.
I solve this problem by using WeakReference<Activity> as a context. The crash never appeared again. Here is a sample code in Kotlin:
Dialog manager class:
class DialogManager {
fun showAlertDialog(weakActivity: WeakReference<Activity>) {
val wActivity = weakActivity.get()
wActivity?.let {
val builder = AlertDialog.Builder(wActivity, R.style.MyDialogTheme)
val inflater = wActivity.layoutInflater
val dialogView = inflater.inflate(R.layout.alert_dialog_info, null)
builder.setView(dialogView)
// Set your dialog properties here. E.g. builder.setTitle("MyTitle")
builder.create().show()
}
}
}
And you show the dialog like this:
val dialogManager = DialogManager()
dialogManager.showAlertDialog(WeakReference<Activity>(this#MainActivity))
If you want to be super-duper protected from crashes. Instead of builder.create().show() use:
val dialog = builder.create()
safeShow(weakActivity, dialog)
This is the safeShow method:
private fun safeShow(weakActivity: WeakReference<Activity>, dialog: AlertDialog?) {
val wActivity = weakActivity.get()
if (null != dialog && null != wActivity) {
// Api >=17
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (!dialog.isShowing && !(wActivity).isFinishing && !wActivity.isDestroyed) {
try {
dialog.show()
} catch (e: Exception) {
//Log exception
}
}
} else {
// Api < 17. Unfortunately cannot check for isDestroyed()
if (!dialog.isShowing && !(wActivity).isFinishing) {
try {
dialog.show()
} catch (e: Exception) {
//Log exception
}
}
}
}
}
This is a similar method that you could use for safe dismissing the dialog:
private fun safeDismissAlertDialog(weakActivity: WeakReference<Activity>, dialog: AlertDialog?) {
val wActivity = weakActivity.get()
if (null != dialog && null != wActivity) {
// Api >=17
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (dialog.isShowing && !wActivity.isFinishing && !wActivity.isDestroyed) {
try {
dialog.dismiss()
} catch (e: Exception) {
//Log exception
}
}
} else {
// Api < 17. Unfortunately cannot check for isDestroyed()
if (!dialog.isShowing && !(wActivity).isFinishing) {
try {
dialog.dismiss()
} catch (e: Exception) {
//Log exception
}
}
}
}
}
In Kotlin
if (!(context is Activity && context.isFinishing)) {
pausingDialog!!.show()
}
how about makes a new Instance of that dialog you want to call? I've actually just met the same problem, and that is what I do. so rather than :
if(!((Activity) context).isFinishing())
{
//show dialog
}
how about this?
YourDialog mDialog = new YourDialog();
mDialog1.show(((AppCompatActivity) mContext).getSupportFragmentManager(), "OrderbookDialog");
}
so rather than just checking is it safe or not to show the dialog, I think it's much more safe if we just create a new instance to show the dialog.
Like me, In my case I tried to create one instance (from a Fragment onCreate) and call the instance of those dialog in another content of adapterList and this will result in "is your activity running"- error. I thought that was because I just create one instance (from onCreate) and then it is get destroyed, so when I tried to call it from another adapterList I calling the dialog from old instance.
I am not sure if my solution is memory friendly or not, because I haven't tried to profile it, but it works
(well surely, it is safe if you do not create too many instance)

Android Unable To Add Window

I have a PreferenceActivity containing checkboxes amongst other things and worked perfectly. I decided to add an AlertDialog which first prompts the user to ensure they wish to select the check box. Nine times out of 10 everything works fine but on occasion specifically when I try to check a check box as soon as the ActivityPreference has loaded I get the following error when trying to show the dialog:
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#45a646d8 is not valid; is your activity running?
at android.view.ViewRoot.setView(ViewRoot.java:468)
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:239)
at android.app.AlertDialog$Builder.show(AlertDialog.java:802)
at com.beargraves.hitechmedia.AppPreferenceActivity.onSharedPreferenceChanged(AppPreferenceActivity.java:385)
at android.app.ApplicationContext$SharedPreferencesImpl$EditorImpl.commit(ApplicationContext.java:2861)
at android.preference.Preference.tryCommit(Preference.java:1199)
at android.preference.Preference.persistBoolean(Preference.java:1404)
at android.preference.CheckBoxPreference.setChecked(CheckBoxPreference.java:154)
at android.preference.CheckBoxPreference.onClick(CheckBoxPreference.java:143)
at android.preference.Preference.performClick(Preference.java:811)
at android.preference.PreferenceScreen.onItemClick(PreferenceScreen.java:190)
at android.widget.AdapterView.performItemClick(AdapterView.java:284)
at android.widget.ListView.performItemClick(ListView.java:3606)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:1751)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4363)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:862)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
at dalvik.system.NativeStart.main(Native Method)
I saw this question but the answers didn't appear relevant. Here is my code
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key) {
final String k = key;
if (findPreference(key) instanceof CheckBoxPreference) {
final CheckBoxPreference chkPref = (CheckBoxPreference) findPreference(key);
boolean result = sharedPreferences.getBoolean(key,false);
if(result){
new AlertDialog.Builder(AppPreferenceActivity.this)
.setTitle("Confirm Ation")
.setMessage("Do you wish to: " + chkPref.getTitle())
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pDialog.setMessage("Syncing");
pDialog.show();
new SyncTask().execute(k);
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
chkPref.setChecked(false);
}
}).show();
}
}
}
Any help would be much appreciated.

Categories

Resources