Search code examples
javaandroidbuttonactivity-finishonbackpressed

back button without calling finish() or onBackPressed()


I want to create a button to go back to the previous activity, but if I use the methods "finish()" or "onBackPressed()" in the "onclick" event, each time I press the button I have the message from the system "unfortunately, activity has stopped". Is there an alternative way to introduce a back button, without showing messages such as this which could be taken for message errors from the user?

Here is my xml for the button:

<Button
    android:layout_width="wrap_content"
    android:layout_weight=".2"
    android:layout_height="wrap_content"
    android:text="back"
    android:id="@+id/back"
    android:onClick="onBackPressed"
    />

No more code is needed, because the onBackPressed already exists in the library.


Solution

  • If the same activity always starts your current one, just hard code it...

    Intent myIntent = new Intent(CurrentActivity.this, PreviousActivity.class);
    CurrentActivity.this.startActivity(myIntent);
    

    Otherwise you can pass extras in your intents to let you know, and then make a conditional method to start the correct one. Also I'd write all your button code in your java files, but that's more a personal preference I guess.

    //global declaration
    Button GameButton;
    
    //onCreate
    GameButton = (Button)findViewById(R.id.GameButton);
    GameButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //your code
            }
        });