Search code examples
androiddialogandroid-context

Are Context and MainActivity.this different?


In MainActivity, Context and MainActivity are different?

They are exactly getApplicationContext() and MainActivity.this in Method.

The reason I'm asking this is because i got error because of them.

if these are different, Complier didn't display red line in code.

I thought it was the same until now.

I got this error code.

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.writeweight, PID: 24595
    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:702)
        at android.app.Dialog.show(Dialog.java:424)
        at com.example.writeweight.MainActivity.onOptionsItemSelected(MainActivity.java:85)
        at android.app.Activity.onMenuItemSelected(Activity.java:4182)

And I changed from getApplicationContext() to MainActivity.this and it worked well.

Code

MainActivity.class
@Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // HERE
        builder.setTitle("SET");
        builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(),"TEST", Toast.LENGTH_SHORT).show();

            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();

        return true;
    }

Tell me please. Thank you


Solution

  • getApplicationContext() (somewhat unsurprisingly) returns the application context, whilst MainActivity.this is itself an activity context. Themes associated with your activity will differ from your application. They aren't the same thing.

    if these are different, Complier didn't display red line in code.

    You wont see an error, because it's only a Context that is requested. I haven't tried it, but you probably could use an Application instance so long as you specify the theme as well by using new AlertDialog.Builder(getApplicationContext(), /* theme res id */)

    However, all the examples in the Android documentation use an Activity context, so I'd suggest you just go with that.