Reputation: 745
I have noticed a trend with the AlertDialog in Android. It inconsistently crashes complaining of the type of Context passed to the AlertBuilder constructor.
Is this a known issue and how can I completely avoid this from happening in production.
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getApplicationContext())
.setTitle("Title")
.setMessage("Your message that the user won't see cause this might just crash the app")
.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertBuilder.create().show();
java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:843)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:806)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:693)
at androidx.appcompat.app.AppCompatDialog.setContentView(AppCompatDialog.java:95)
at androidx.appcompat.app.AlertController.installContent(AlertController.java:232)
at androidx.appcompat.app.AlertDialog.onCreate(AlertDialog.java:279)
at android.app.Dialog.dispatchOnCreate(Dialog.java:465)
at android.app.Dialog.show(Dialog.java:333)
at org.aplusscreators.com.views.onboarding.SubscriptionPlanActivity$4.onClick(SubscriptionPlanActivity.java:145)
at android.view.View.performClick(View.java:6719)
at android.view.View.performClickInternal(View.java:6677)
at android.view.View.access$3400(View.java:797)
at android.view.View$PerformClick.run(View.java:26475)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:226)
at android.app.ActivityThread.main(ActivityThread.java:7212)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:576)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:956)
Upvotes: 1
Views: 337
Reputation: 363825
The issue is here:
new AlertDialog.Builder(getApplicationContext())
You have to pass Activity
as context instead of getApplicationContext()
.
The ApplicationContext
has not the app theme.
Upvotes: 1
Reputation: 1506
Set a theme for that activity either in the manifest or programmatically before onCreate in the class. You can also set it globally for the entire app inside application tag of manifest.
<application
android:theme="@style/AppTheme">
....
Upvotes: 1