Search code examples
androidlistviewonresume

restart activity in android


I have one activity A, that has one button and one list view which shows names of books . on click of the button, activity B starts, there user fill the book form and save it . when he press back button , user comes to activity A. Here the book name should be updated in listview. I think I have to write some code in onResume() . Can u please tell me what to write. I am using customised list view.


Solution

  • Start activity B with startActivityForResult() and use method onActivityResult() to restart or process the new data

    For example, to start Activity B:

    String callingActivity = context.getLocalClassName();
    Intent newActivity = new Intent(getApplicationContext(),ActivityB.class);
    newActivity.setData(Uri.parse(callingActivity));
    startActivityForResult(newActivity, 0);
    

    Then somewhere in your Activity A class:

    protected void onActivityResult(int requestCode, int resultCode, Intent data){
            if(requestCode == 0){
                // do processing here
            }
        }
    

    The other answers should suffice, but onResume() can be called in cases where the activity is resumed by other means.

    To simply restart Activity A when user presses back button from Activity B, then put the following inside the onActivityResult:

    if(requestCode == 0){
                finish();
                startActivity(starterintent);
    
            }
    

    And in the onCreate of Activity A, add starterintent = getIntent();

    Just remember to initiate the variable with Intent starterintent; somewhere before your onCreate is called.

    e.g.

    public class ActivityA extends ListActivity {
      Intent starterintent;
    
      public void onCreate(Bundle b){
        starterintent = getIntent();
      }
    
      protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if(requestCode == 0){
          finish();
          startActivity(starterintent);
        }
      }
    
      private void startActivityB(){
        String callingActivity = context.getLocalClassName();
        Intent newActivity = new Intent(getApplicationContext(),ActivityB.class);
        newActivity.setData(Uri.parse(callingActivity));
        startActivityForResult(newActivity, 0);
      }
    
    }
    

    Then just call startActivityB() from a button click or whatever