1

I'm trying to have a alert dialog show if account info is missing when clicking the check the account. I get an error in Eclipse where new AlertDialog.Builder(this) saying the constructor AlertDialog.Builder(new View OnClickListener(){}) is undefined. The code works fine if I add it to the onCreate of the activity.

checkButton.setOnClickListener(new OnClickListener() {
        public void onClick(View Arg0){
            String AccNum = null, Store = null;
            final SharedPreferences settings = getSharedPreferences(CHECK_PREFERENCES, MODE_PRIVATE);

            if (settings.contains("Account") == true){
                AccNum = (settings.getString("Account", "default"));
                Store = (settings.getString("Store", "default"));
            }
            if (AccNum.length() < 7) { 
                AlertDialog alert = new AlertDialog.Builder(this).create();
                alert.setTitle("Account Information missing!");
                alert.setMessage("Enter now? ");

                alert.setButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            startActivity(new Intent(CheckOrder.this, GoToSetup.class));
                        }
                });
                alert.setButton2("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            return;
                        }
                });
                alert.show();   

            }
        }
});
Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
Kim Jensen
  • 11
  • 1
  • 1
  • 2

3 Answers3

16

The error occurs because this is the OnClickListener that you're creating (in the call to checkButton.setOnClickListener(new OnClickListener(){), not the parent Activity. If your Activity class is ParentActivity, try this:

AlertDialog alert = new AlertDialog.Builder(ParentActivity.this).create();
Femi
  • 64,273
  • 8
  • 118
  • 148
  • Thanks, comming from C++ and Delphi there is a learning curve here. Can I create it outside the OnClickListener and call the procedure if I need it? I tried but the I got another error telling me something about taht I can call outside the class. – Kim Jensen Aug 09 '11 at 15:14
  • You can create a function in the activity and call that, which would probably solve those issue. – Femi Aug 09 '11 at 16:08
2

Your class needs to extends Activity, such as

public class MyClass extends Activity{
// ... Your code
}
1

I had same problem. Try this one.

AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
Ensar
  • 17
  • 4