Supriya
Supriya

Reputation: 290

Activity getting reset upon displaying an AlertDialog

My Activity is getting reset upon AlertDialog display.

I am learning Android and following this tutorial.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Other Code
    submitBtn = (Button) findViewById(R.id.submit_button);
    // Other Code
    submitBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            AlertDialog alert = builder.create();
            alert.setMessage("Hello " + name);
            alert.setTitle("Showing content in prompt window");
            alert.show();
            setContentView(R.layout.activity_main);
        }

Here is my AlertDialogCode:

//creating the alert dialog
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true)
            .setNegativeButton("Close", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                //Action for close button
                    dialog.cancel();
                }
            });

Activity gets reset as soon as the AlertDialog is displayed
Can you help to tell the reason why the activity is getting reset?

Upvotes: 1

Views: 152

Answers (3)

Sunil
Sunil

Reputation: 3424

When you call onCreate method, you need to set content view just once. In your code you have already set the setContentView on the second line. If you happen to set it again, it will reset your activity and also remove your event handlers.

So suggest you to delete the second setContentView. This is also the problem in the tutorial you are following.

alert.show();
//setContentView(R.layout.activity_main); // <-- Needs to be removed

Upvotes: 1

Comment or remove the line

        setContentView(R.layout.activity_main);

On you first code. Because this is forcing your activity to reload.

Upvotes: 2

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

You are resetting the XML view of the activity with same layout so

Remove setContentView(R.layout.activity_main);

 public void onClick(View v){
     AlertDialog alert = builder.create();
     alert.setMessage("Hello " + name);
     alert.setTitle("Showing content in prompt window");
     alert.show();
     //setContentView(R.layout.activity_main);
     //^^^^^^^^^^^^^^^^^^^^^^^^^^^^ remove
}

Upvotes: 2

Related Questions