Amit625
Amit625

Reputation: 25

Android AlertDialog using Intents to finish Activity

I am trying to finish my Activities when the user selects the quit option in an AlertDialog within another class. However, when I try to use the getApplicationContext() I get this error

The method getApplicationContext() is undefined for the type new DialogInterface.OnClickListener(){}

and the error

The method startActivity(Intent) is undefined for the type new DialogInterface.OnClickListener(){}

for the StartActivity(intent). Any advice will be great. Thanks

new AlertDialog.Builder(context)
.setTitle("End Option ")
.setMessage("Continue ?")
.setPositiveButton("Quit",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}).setNegativeButton("Retry",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {

}}).show();

Upvotes: 1

Views: 451

Answers (2)

Sekhar Madhiyazhagan
Sekhar Madhiyazhagan

Reputation: 889

write the intent into a method like,

 public void anotheractivity()
  {
    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  intent.putExtra("EXIT", true);
 startActivity(intent);  


}

and call them from alert box,

        new AlertDialog.Builder(this)
   .setTitle("End Option ")
  .setMessage("Continue ?")
  .setPositiveButton("Quit",new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog,int which) {
     //call the method here
        anotheractivity();
     }).setNegativeButton("Retry",new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog,int which) {

        }}).create().show();

Upvotes: 1

Blo
Blo

Reputation: 11978

You need to attach the Activity to start another one, and pass the Context just as you set it above in your Builder with the content variable:

Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
context.startActivity(intent);  

You can also get the context by the getContext method:

Intent i = new Intent(getContext(), MainActivity.class);
getContext().startActivity(i);

Upvotes: 0

Related Questions