0

I am trying to add an AlertDialog to popup from a popup Activity (which is an Activity that extends Activity with android:theme="@android:style/Theme.Dialog" in the Manifest. I am using:

Context context = getApplicationContext();
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Add Extra");
final EditText base = new EditText(builder.getContext());
final EditText value = new EditText(builder.getContext());
base.setHint("Name");
value.setHint("Value");
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
base.setInputType(InputType.TYPE_CLASS_TEXT);
value.setInputType(InputType.TYPE_CLASS_TEXT);
layout.addView(base);
layout.addView(value);
builder.setView(layout);
builder.setMessage("")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {

       }
       })
       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
          // User cancelled the dialog
       }
       });
 // Create the AlertDialog object and return it
AlertDialog dialog = builder.create();
dialog.show();

to create my Alert, but I recieve an error about not having the correct context. Is there a specific way to get the context of the popup dialog?

Torewin
  • 887
  • 8
  • 22

3 Answers3

1

You are using getApplicationContext(), use Activity context instead

Use this instead to avoid errors

Context context = YourCurrentActivity.this;
Andre Breton
  • 1,273
  • 1
  • 9
  • 19
  • I receive this error: `You need to use a Theme.AppCompat theme (or descendant) with this activity.` – Torewin Aug 25 '17 at 23:32
  • Is your activity extending from ActionBarActivity or AppCompatActivity? if so, extend from Activity or any other answer in this question might come on handy https://stackoverflow.com/a/21815015/7355128 – Andre Breton Aug 25 '17 at 23:35
  • Thanks, I will take a look. I am extending Activity instead of AppCompatActivity because I have the theme Dialog. – Torewin Aug 25 '17 at 23:39
  • This doesn't answer why the AlertDialog isn't working on this do you have any other suggestions? – Torewin Aug 25 '17 at 23:47
0

You should use the Activity context.

Change this line,

Context context = getApplicationContext();

to this:

Context context = this;
CzarMatt
  • 1,773
  • 18
  • 22
0

Android AlertDialog in Activity Dialog.Theme

I asked this question again and it was answered for anyone else having this problem.

Torewin
  • 887
  • 8
  • 22