I am having two activities (activity1 and activiy2) and each activity is having one button each. In activity1 i having a spinner with few options. Suppose i am selecting option 2 from this spinner and i am clicking the button in activity1, then activity2 starts. When i click back button activity1 is resumed and the same option 2 is visible (like i need). Now the problem is that if my activity2 is started and i am clicking a button in it, activity1 is started. But instead of resuming the previous state of activity1 it starts in a way that it has just created and the previous selection is changed. How can i get the same facility like back button (not the facility of going back to previous activity, i mean automatically resuming the previous state of any activity) even when i start the activity again. Simply i need to know how to maintain the previous state of an activity if it is again visited.
It is with this code I go from one activity to another when button is clicked:
Intent intent=new Intent();
intent.setClassName(getApplicationContext(),"com.myapp.activityname");
startActivity(intent);
Kindly help me.I am a beginner in android, so if any one is giving the answer please explain it a bit. Thanks in adavnce
Think I found the answer. Let me tell what I have done in simple words,
Suppose i am having two activities activity1 and activity2 and i am navigating from activity1 to activity2(i have done some works in activity2) and again back to activity 1 by clicking on a button in activity1. Now at this stage I wanted to go back to activity2 and i want to see my activity2 in the same condition when I last left activity2.
For the above scenario what i have done is that in the manifest i made some changes like this:
<activity android:name=".activity2"
android:alwaysRetainTaskState="true"
android:launchMode="singleInstance">
</activity>
And in the activity1 on the button click event i have done like this:
Intent intent=new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.setClassName(this,"com.mainscreen.activity2");
startActivity(intent);
And in activity2 on button click event i have done like this:
Intent intent=new Intent();
intent.setClassName(this,"com.mainscreen.activity1");
startActivity(intent);
Now what will happen is that whatever the changes we have made in the activity2 will not be lost, and we can view activity2 in the same state as we left previously.
I believe this is the answer and this works fine for me.
By overriding an Activity’s onSaveInstanceState event handler, you can use its Bundle parameter to save instance values. Here is an example:
#Override
public void onSaveInstanceState(Bundle outState) {
// Retrieve the View
TextView myTextView = (TextView)findViewById(R.id.myTextView);
// Save its state
outState.putString("My text",
myTextView.getText().toString());
super.onSaveInstanceState(outState);
}
The saved Bundle is passed into the onRestoreInstanceState and onCreate methods if the application is forced to restart during a session. You can then extract values from the Bundle and use them to update the Activity instance state. Here is an example:
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TextView myTextView = (TextView)findViewById(R.id.myTextView);
String text = “”;
if (icicle != null && icicle.containsKey("My text")) {
text = icicle.getString(TEXTVIEW_STATE_KEY);
}
myTextView.setText(text);
}
It’s important to remember that onSaveInstanceState is called only when an Activity becomes inactive, but not when it is being closed by a call to finish or by the user pressing the Back button.
Download source code or see the entire post
For activity one, you need to use the startActivityForResult() function that returns values to the parent activity which is the activity one.
Intent intent = new Intent(MainActivity.this, Activity2.class);
startActivityForResult(intent, 1);
And to receive the values from activity two without alteration of activity one, add the following code
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String text=data.getStringExtra("text");
vTxt.setText("Name 1: "+eTxt.getText()+ "\n Name 2: "+text);
}
}
}
Activity 2
add the following code to return to activity one and pass some values
Intent intent=new Intent(Activity2.this, MainActivity.class);
Bundle extra=new Bundle();
extra.putString("text", eTxt.getText().toString());
intent.putExtras(extra);
setResult(RESULT_OK, intent);
finish();
Finally you are done
Related
Say Activity A has a Edittext, on entering some information and on clicking a button in that particular activity it goes to Activity B.
On returning to Activity A by clicking back button from B, the content in the Edit text remains as such.. help me getting it erased.
There are several ways to do that:
1) Remove EditText data before start ActivityB
2) Use startActivityForResult to launch your ActivityB and override onActivityResult in your ActivityA
3) Override ActivityA onResume method and remove EditText data inside that method. With this approach, your EditText data could be flushed even if you do not start ActivityB, so be aware of Activity lifecycle.
To do so, just do:
editText.setText("");
just before calling startActivity(intent) method, reset it by setting the editText.setText("");
before Intent set your edittext to ("");
EditText name = (EditText)findViewByid(R.id.edittext);
name.settext("Your Name");
Button send = (Button)findViewById(R.id.button);
send.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
name.settext("");
Intent activity_b = new Intent(ActivityA.this, ActivityB.class);
startActivity(activity_b)
}
});
or you can also do
#Override
public void onResume(){
super.onResume();
name.settext(");
}
editText.setText("");
you can put above line of code in two different ways
If you want to make only edittext empty when ActivityA comes back from ActivityB then just put it before the line of code where you are starting ActivityB.
edittext.settext("");
Intent intent = new Intent(ActivityA.this, ActivityB.class);
startActivity(intent)
In onResume() if you want to cover all different scenarios. It will make edittext empty whenever that activity returns whether from another activity or from the background.
Hope it will help you.
I am writing a application where I am dealing with 5 activities, let's say A, B, C , D & E.
Activity A invokes B, B invokes C, C invokes D,D invokes E. On each of the activity, I have a button called "next" button and editText to fill name. When user clicks on next button in any of the A,B, C, D,E activities, application should go to next activity screen but when user clicks On back button in E activity it should go on activity A.
Now my question is when i start from activity A after coming from activty E on back press I want to maintain data of editText of all the actvities which filled by user when comes first time ?
Try This:
Have a Shared Preference file. When clicking next you save the fields in your shared preference.
then when loading a activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
et1 = (EditText)findViewById(R.id.editText_Name);
loadSavedPreferences();
}
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
et1.setText(sharedPreferences.getString("string_et_Name",""));
}
Have your own saving mechanism on the next button click.
Note: Clear your shared preference when clicking finish (if required)
step 1: decalre a boolean flag with int value on MainActivity first suppose:
private boolean flag=200;
step 2: from main activity we are switching to suppose 5 other activities on a button click respectively.
So from main activity we call StartActivityForResult(intent,flag); which indicate that we can come back with the same flag value from any activity.
step 3: now suppose we want data of activity "E" (as per your question) then we send it by sending it through bundle;
like: declare same boolean value of 200 on each activity from which we are traveling
Intent intent=new Intent();
intent.putExtra("firstName",firstName);
intent.putExtra("lastName",lastName);
setResult(flag,intent);
finish();
step 4: get bundle vale on coming activities by onActivityResult() method which is overriden
and check with flag value
like:
if (resultCode==200)
{
String firstName=data.getStringExtra("firstName");
String lastName=data.getStringExtra("lastName");
Intent intent=new Intent();
intent.putExtra("firstName",firstName);
intent.putExtra("lastName",lastName);
setResult(200,intent);
finish();
}
step 5: similarly for all activities;
step 6: finally, get bundle on MainActivity
like:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==200)
{
String firstName=data.getStringExtra("firstName");
String lastName=data.getStringExtra("lastName");
textViewFirstName.setText(firstName);
textViewLastName.setText(lastName);
}
}
I did something very similar to your needs and like you i started with activities but then I found this, which makes all easy, 1 activity with several fragments instead of lots of activities, maybe you are interested in : StepStone
Here the answers to common questions : ans
Then if you want to pass data, i am working with Parceler because i saved my data in custom classes, check my question:
How can i correctly interact between Activities and fragments
If you have any doubts just say it.
Hope this helps!
In my app, there are 3 activities and their calling sequence is like this...
Splash activity--->Dashboard Activity--->List Activity
If it goes like this then If I press back button on List activity then it will follow the reverse sequence of above.
There is one requirement where user can navigate to List Activity directly from Splash (Skipping Dashboard Activity) Now when user will hit back button on List Activity then I wan't to show Dashboard Activity which is not there in the Activity Stack.
So please help me with the best approach.
Pass a boolean through the intent for going to List Activity from either of the others. Using onBackPressed check if the boolean is true or false for skipping Dashboard Activity.
Then if true put new intent for loading dashboard activity and finish(); on list activity.
You have to pass class name as intent extra from both Splash and DashboardActiviy.
In List Activity you have to get the class name using getIntent().
When the user click back button, you need to check the class name based on that you can take decision.
if(name.equalIgnorecase(DashboardActivit.class.getSimpleName()){
//Add your intent
}else{
//
}
This may give you definite solution to you.Give a try
you can directly go to splash from list Activity while going to
ListActivity from Dashboard Activity call finish()
Intent i = new Intent(DashboardActivity.this,ListActivity);
startActivtiy(i);
finish();
Start your inner activities with startAcvitiyForResult
Intent i = new Intent(this, Activity_2.class);
startActivityForResult(i, 1);
and in your inner activity
#Override
public void onBackPressed ()
{
finish();
}
You can also do stuff in your outer activity as you like after your inner activity finishes
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == 1){
Log.i("TEST", "RESULT_OK");
}
else {
return;
}
}
}
In my android app, I have an activity that displays profile information. Then it opens a new activity to make changes to the activity. After you save changes, it closes the edit activity from the edit activity, then goes back to the profile displaying activity, there I need to restart this activity to refresh the data.
Is there a way I can restart the activity that opened the current activity?
There are three ways you can achieve what you want:
Start the profile activity by calling startActivityForResult() and refresh your data in onActivityResult()
Finish() the activity when start the profile activity and then override onBackPress() in the profile activity to start the previous activity and then call finish().
Override onBackPress() in the profile activity to start the previous activity with the flag Intent.FLAG_ACTIVITY_CLEAR_TOP and refresh your data in onNewIntent()
Use Android Activity Result Pattern that communticates parent and child activities:
In your profile activity (parent):
#Override
public void onClick(View v) {
startActivityForResult(
new Intent(this, NameActivity.class),
1); // 1 to identify caller activity.
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
updateProfile();
}
}
In your editor activity (child):
#Override
public void onClick(View v) {
setResult(
RESULT_OK);
finish();
}
You won't have to "restart" Activity A.
You can call startActivityForResult(Intent, int) to start your new Activity, and then receive extras via the onActivityResult(int, int, Intent) call.
http://developer.android.com/reference/android/app/Activity.html#StartingActivities
Alternatively, look into the onResume() method, which is called every time your screen becomes visible. Assuming you persisted some state in Activity B (e.g. a SharedPreference or a database record), in onResume() you can refresh Activity A.
Activity Display;
Activity Modification;
When you startActivity M in your Activity D,don't D.finish();
then, when you M.finish(),you don't need "restart" Activity D,because it is already there.
You have two choices to "refresh the data":
1.startActivityForResult as they said.I won't explain any more.
2.make a cache.
save data in some static variables or sqlite or even sharedPreference.Then in onResume() of Activity D,get those data and show them.
Try this: If A is calling B and when B ends you need to update A, then in A launch B with startActivityForResult(). When B returns, the method onActivityResult() of A will be called. In this method (of A) you can test, if necessary, that some stored values are changed. At this point you do something like:
finish();
startActivity(intent); //start the activity A
I try to go to previous Activity (Activity A) but have problem. Command to this get inside Activity B and I wont to go back to B:
A:
if(...)
{
B.staticF();
}
B:
static void staticF()
{
super.onBackPressed();
}
But I can't use super because it's static context.
Of course, I can call
Intent i = new Intent(this, B.class);
startActivity(i);
but I wont to save B look.
Why not just use something like a shared preference to save the state? and then use the intent to go back and in the onCreate method get the preferences and populate any views with the data you wanted to save