Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Back button and refreshing previous activity

Tags:

android

If we have two activities:

  1. List of files and last modified time
  2. File editing activity

A user selects a file from the list and is taken to the file editing activity. When done editing, the user presses the back button to return to the file list.

The list is not reloaded and therefore an incorrect value is displayed for the just edited files modified time.

What is the proper method of causing the file list to refresh after the back button is pressed?

This example assumes that no database is being used, just an ArrayAdapter.

like image 414
Paul Avatar asked Apr 04 '11 22:04

Paul


People also ask

What happens to activity when back button is pressed?

This is an override function called when the user presses the back button on an Android device. It has great implications on the activity lifecycle of the application. The official documentation states that onBackPressed() method is called when the activity has detected the user's press of the back key.

How do I go back to previous activity?

You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.

How do I go back to first activity on Android?

Declare A in your manifest with the android:launchMode="singleTask" . This way, when you call startActivity() from your other activies, and A is already running, it will just bring it to the front. Otherwise it'll launch a new instance.

How do you refresh a fragment after onBackPressed from activity?

You can override onBackPressed in Activity and call a function on corresponding fragment to reloadItems().


1 Answers

One option would be to use the onResume of your first activity.

@Override public void onResume()     {  // After a pause OR at startup     super.onResume();     //Refresh your stuff here      } 

Or you can start Activity for Result:

Intent i = new Intent(this, SecondActivity.class); startActivityForResult(i, 1); 

In secondActivity if you want to send back data:

 Intent returnIntent = new Intent();  returnIntent.putExtra("result",result);  setResult(RESULT_OK,returnIntent);       finish(); 

if you don't want to return data:

Intent returnIntent = new Intent(); setResult(RESULT_CANCELED, returnIntent);         finish(); 

Now in your FirstActivity class write following code for onActivityResult() method

protected void onActivityResult(int requestCode, int resultCode, Intent data) {    if (requestCode == 1) {       if(resultCode == RESULT_OK){                //Update List               }      if (resultCode == RESULT_CANCELED) {              //Do nothing?      }   } }//onActivityResult 
like image 83
Waza_Be Avatar answered Sep 27 '22 20:09

Waza_Be