i am developing an android application. i have 8 activities in the application. i have a submit button in the last activity. the user can go back to any activity and edit the data before pressing submit.i have two buttons in every activity named as Next and previous. and in the last activity an extra button called Submit is there. I want to come to any previous page from the next page and edit the data and go to submit.
Now my problem is, every time i press Previous my previous-activity data fields are becoming blank..
please help me solving this problem.
Save the state of your activities with bundles. The back button ends the lifecycle of an activity. Here's a link that would guide you through what you should do. Hope this helps.
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
Dont kill your activity while moving to other activity. Also you can set a flag while launching activity whihc will just put your activity to backstack and will be retrieved when relaunch by pressing back. Follow below link for details:
http://developer.android.com/guide/components/tasks-and-back-stack.html
You need to save the state of Activity:
private static final String INPUT1 = "ip1";
private static final String INPUT2 = "ip2";
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putString(INPUT1, mEditText1.getText().toString());
savedInstanceState.putString(INPUT2, mEditText2.getText().toString());
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
And restore it when Activity starts:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
mEditText1 = findViewById(.....
mEditText2 = findViewById(.....
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mEditText1.setText(savedInstanceState.getString(INPUT1));
mEditText2.setText(savedInstanceState.getString(INPUT2));
}
}
Also, you can tell EditText and other such Views to save their state individually, by adding android:saveEnabled="true" to their layout:
<EditText
android:id="#android:id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:saveEnabled="true"
android:inputType="text"/>
Related
I would like my application to save state after it already has loaded once. For example in one of my activities I have a ListView. If the user scrolls it, and than switches activities, I wish for them to go back to the ListView activity and have the same scrolling position. I noticed that pressing the back button goes back to a saved version of the state. This is the exact kind of save I want (where it saves the state of the previous activity). Except I want to do this from anywhere in the application, not just when the back button is pressed... Please help me.
You have to override onSaveInstanceState(Bundle savedInstanceState) and store the values you want to save in Bundle object as name value pair.
#Override public void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean("position", 12);
savedInstanceState.putString("Name", "John");
}
also you have to override onRestoreInstanceState() where you'd extract the values:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
boolean myPosition=savedInstanceState.getBoolean("position");
String name= savedInstanceState.getString("Name");
}
see this link for help LINK
It can be done with the saveInstanceState() and onRestoreInstanceState() methods. The first one called near onPause(), the second called before onResume(). To save the state of a view, call onSaveInstanceState() from view.
For example, listview.onSaveInstnceState();
Here's a detailed article
https://futurestud.io/blog/how-to-save-and-restore-the-scroll-position-and-state-of-a-android-listview
I have an Android app, that allows the user to dynamically add their own buttons to the layout. I need to make it so that once the app is closed and re-opened, this dynamically added button returns to the layout. Instead of loading the default layout.
Currently, I'm dynamically adding buttons through the ActionBar of the App:
if (id == R.id.add_button)
{
String string = "Adding Button in Progress";
Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show( );
Button myButton = new Button(this);
myButton.setText("Button");
RelativeLayout layout = (RelativeLayout)findViewById(R.id.Layout1);
layout.addView(myButton);
//myButton.setVisibility(View.VISIBLE);
return true;
}
This creates the Button fine, however when the app is closed and re-opened, it launches up the default layout.
I've done some research on having the app save and reload the updated layout. It seems that I need to use onSaveInstanceState. Here is what I have so far in terms of trying to save the layout:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the app state here:
savedInstanceState.putAll(savedInstanceState);
super.onSaveInstanceState(savedInstanceState);
}
And here is what I have in terms of trying to "reload/restore" said layout. Notice I'm not using onRestoreInstanceState, instead I'm doing it through the onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
//savedInstanceState.get(savedInstanceState);
}
else
{
//initialize members with default values for a new instance
setContentView(R.layout.activity_main);
}
}
I'm not sure if I'm saving/loading correctly, but any advice on how I can accomplish this task would be greatly appreciated.
Thanks for your time!
P.S. I'm still a fairly new member so I couldn't comment/ask questions on existing threads.
I know there's a lot of information out there on trying to load/save layouts, however in my case I need it to save the Button, and not a string of user text. In other words, its not a fixed value that I need to save. If the user adds n buttons, when the app is exited and relaunched, it should have those same 3 buttons.
Saved Instance State is a key-value pair about your activity. The documentation clearly says that it is destroyed when the app is closed .(pressing back button or if the system itself shutsdown the app).This is only useful when you are navigating within the app or changing orientation.
One solution is to create a Shared Preference of the details your application needs to identify the given structure consisting the dynamic contents. The fetch the values whenever you open the app and code according to it.
Other solutions are to use databases or files to store data about your dynamic content.
just store the String or Boolean.. when ever you try to use them in onRestoreInstanceState then create Button or anything dynamically and use stored String or boolean to set text on them
I know this question has been asked many times but i have tried many solutions to no avail. sob sob.
Ill try to keep it simple. Im writing an app that uses spinners and edit texts to intake float numbers. so screen A has 4 spinners and 4 edit texts. I use a next button to open screen B
onClick(){
a.putExtras(sendScoreSoFar);
a.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(a);
}
Screen B is much the same with 3 spinners and 2 edittexts.
I can move from A to B and back to A while preserving the input from the user but when I go back to B again B is reset. I need to preserve the input so the user can flick back and forth to check input. I could use shared preferences but need to reset on the first loadup.
Ive tried various lines in the manifest:
<activity
android:name="com.package.Screen2"
android:label="#string/app_name"
android:alwaysRetainTaskState="True"
android:launchMode="singleInstance">
>
<intent-filter>...
and heres my on create and saved instance state code.
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
setContentView(R.layout.screen2);
super.onCreate(savedInstanceState);
setUpVariables();
if (savedInstanceState != null) {
int a = savedInstanceState.getInt("weightlostorprev");
spinner1.setSelection(a);
int b = savedInstanceState.getInt("metricorimp");
spinner1.setSelection(b);
int c = savedInstanceState.getInt("acute");
spinner1.setSelection(c);
etBigWeight.setText(savedInstanceState.getString("bigweight"));
etSmallWeight.setText(savedInstanceState.getString("smallweight"));
}
gotBasket = getIntent().getExtras();
passedResults = gotBasket.getFloatArray("the data");
passedWeight = passedResults[5];
Toast c1 = Toast.makeText(Screen2.this, "on create run! new run = "
+ newRun, Toast.LENGTH_LONG);
c1.show();
// question.setText(gotBread);
}
//#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
int a = spinner1.getSelectedItemPosition();
savedInstanceState.putInt("weightlostorprev", a);
int b = spinner2.getSelectedItemPosition();
savedInstanceState.putInt("metricorimp", b);
int c = spinner1.getSelectedItemPosition();
savedInstanceState.putInt("acute", c);
savedInstanceState.putString("bigweight", etBigWeight.getText()
.toString());
savedInstanceState.putString("bigweight", etBigWeight.getText()
.toString());
}
//#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
int a = savedInstanceState.getInt("weightlostorprev");
spinner1.setSelection(a);
int b = savedInstanceState.getInt("metricorimp");
spinner1.setSelection(b);
int c = savedInstanceState.getInt("acute");
spinner1.setSelection(c);
etBigWeight.setText(savedInstanceState.getString("bigweight"));
etSmallWeight.setText(savedInstanceState.getString("smallweight"));
}
I know theres a simple solution, but i cant find it.
thanks in advance.
EDIT
as far as I can see you cant send data to onResume
so although the answers given were correct I solved the problem by removing all shared preferences code, removing the changes to the manifest:
android:alwaysRetainTaskState="True"
android:launchMode="singleInstance">
and instead of trying to preserve the activity, killing it as normal (with the back button)
and just send the values of the spinners and edit texts in a bundle using startactivityforresult.
So screenA starts screenB sending bundle a, then when screenB is killed with the back button, it sends bundle b back to screenA, then when screenA now starts screenB it Sends bundles a and b and b is populated with values in bundle b.
Probably no one interested but I thought id put up the solution anyway.
I can put up the code if anyone wants.
Thanks for the answers guys ill be taking a look at your options next time.
I am assuming you are moving back to A screen via the back button which is finishing your B screen.
You may want to consider putting each screen into a fragment, loading them both in your activity and using the fragment manager to flip between the fragments.
Here are a resources that will pertain to this solution.
Switching between Fragment view
http://www.vogella.com/articles/AndroidFragments/article.html#fragmentspersistence
You can use the fragments lifecycle call backs to handle the data and setRetainInstance() to "Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change)."
If you need pre honeycomb compatibility, check out the support libraries to do so.
Your choices are that you either persist the data (using, for example, SharedPreferences as you already know). Alternatively you could create a Service which holds your values. Both Activities bind to the Service, and can get and set the values from the Service. The Service will stay alive across your Activity transition, so the values set by ActivityA will be available to ActivityB.
Saving Activity state will only persist the state to the same Activity type. It is used when resuming an Activity, or persisting state across, for example, an orientation change.
I have a ListActivity with an EditText and a ListView. Content of the ListView changes according to the EditText content. I do the following steps:
1) Fill in something in the EditText
2) Consequently the Listview changes (properly)
3) I scroll the listview
4) I press the back button
At this point I expect to get back to the previous activity, while i happens that the EditText gets erased and consequently the ListView empty.
Is there a way to tell the EditText not to erase itself when Back Button is pressed?
Thanks a lot.
G
You could save the editText in the Shared Preferences. To always have the text saved when you back or when you open again the application.Take a look : Shared Preferences
Like this:
private SharedPreferences pref;
In your SecondClass:
pref.edit().putString("text", Text).commit();
MainClass:
String texto = pref.getString("text", "");
I just want the activity to finish whenever i press back button. Doesn't matter what i was doing and which object had the focus
Here's how you can force a finish of the Activity when back is pressed...
#Override
public void onBackPressed() {
finish();
}
You can use the onPause method to store the EditText value. Either in SharedPrefrence or a Global variable.
#Override
public void onPause() {
super.onPause();
// Get the current value from Edit text and store the value on sharedpref or global variable
}
here inside onPause method you can save the current value of the EditText into shared preference.
alternatively you can overide the back button's event and do the same as below
you can use following method
#Override
public void onBackPressed(){
//your code here to save it to shared pref or global varialble then invoke relevant activity manually
}
to overide the events when the back button is pressed
Is there an built in way to save the contents of a listView as part of onSaveInstanceState to then restore later? I want the listView to look the same if the user hit the back button and now onCreate is being called again.
If you set your activity's launchMode to singleTask, then (unless the application was terminated / gc called upon) your data (list) will be preserved.
This way your device will hold only one running instance of your application at a time, so when you "launch it again" no matter from where, if it's already running in the background, then that instance will show up (with the latest data).
If there is a risk that your application was finished, and you still need the latest list of data to show up, this solution won't work.
But you could give a try to SharedPreferences: save the current data to the application's SharedPreferences, and restore it from there when launching it.
If it's ok, to have the predefined new list on each clean start of the application, but when getting it into foreground, you need the last seen items in your list, you should use the savedInstanceState parameter of your onCreate method:
private static final String MYLISTKEY = "myListLabels";
private ArrayList<String> listLabels = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (savedInstanceState.containsKey(MYLISTKEY))
{
listLabels = savedInstanceState.getStringArrayList(MYLISTKEY);
}
else
{
// TODO: populate explicitely your list
}
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putStringArrayList(MYLISTKEY, listLabels);
}
where listLabels contains the labels for your list.
It's not necessary for them to be of type String, you can put any type inside your Bundle.
When the user hits the back button the activity is always destroyed, so there will not be any restoring from savedinstance.
Android Training
When your activity is destroyed because the user presses Back or the activity finishes itself, the system's concept of that Activity instance is gone forever because the behavior indicates the activity is no longer needed.