I have WeakReference<Activity> this problem, using WeakReference<Activity> as the context. The wreck never appeared again. Here is an example code in Kotlin:
Dialog class manager:
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)
And you show the dialog as follows:
val dialogManager = DialogManager() dialogManager.showAlertDialog(WeakReference<Activity>(this@MainActivity))
If you want to be super-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 can use to safely close the dialog box:
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 } } } } }
Ivo Stoyanov Nov 01 '18 at 7:45 2018-11-01 07:45
source share