I’m making an app in which there is a ‘MainActivity.class’ which has a button ‘Edit profile’ that leads to another activity, called ‘Editprofile.class’. It (MainActivity) also has a TextView which displays a string (name).
Editprofile.class accepts a string from user and upon pressing a button ‘add’, the new String gets updated to the database, replacing the previous string. Now when, after updating, the user goes back to the MainActivity via the back button I want the TextView to display the new updated String; for which I have to restart MainActivity.
I have achieved this by using finish() function when the user presses the ‘Edit profile’ button and when the user presses the back button during the Editprofile activity, the MainActivity gets restarted via onBackPress() method.
Code for intent to start ‘Editprofile.class’:
public void edit_profile(View view) { Intent intent = new Intent(this, Editprofile.class) startActivity(intent) finish(); }
Code to go back to ‘MainActivity’:
@Override public void onBackPressed() { finish(); startActivity(new Intent(this, MainActivity.class)); }
I have managed to get the result I wanted but I would appreciate it if someone can tell me if it is the most efficient method.
Should have I posted this in a Q/A format??
An alternative to @Mattias answer is to start
EditprofileusingstartActivityForResult(...). That activity can then return a result indicating whether the user has actually edited his/her profile, which you’ll be able to capture inonActivityResult(...)ofMainActivity. Only if the profile changed theTextViewneeds to be updated.It may take a few lines of extra coding, but is slightly more efficient than updating every single time
onResume()gets hit. In my opinion it also a bit cleaner, although in terms of performance it probably won’t be a big deal.For an example, have a look at the documentation on the Android developers website.