I got a ViewPager which saves the current page position (as the order in it's adapter). When the app goes to the backgroung, the ViewPager seem to lose the position it was last in and when switching to the app again, it starts at fragment with the position 0.
How can I save the current position and set the correct fragment? Hopefully it's something that needs to be done in a single place only and not in every fragment.
OK so it eventually was just something standard. I just overrided OnPause and OnResume. I saved the state with a SharedPreferences in the OnPause method and restored it in the OnResume method.
#Override
public void onPause()
{
super.onPause();
final SharedPreferences.Editor ed = getSharedPreferences("name",
android.content.Context.MODE_PRIVATE).edit();
ed.putInt(INDEX_KEY_STRING, viewPager.getCurrentItem());
ed.commit();
}
#Override
public void onResume()
{
super.onResume();
final SharedPreferences sp = getSharedPreferences("name",
android.content.Context.MODE_PRIVATE);
viewPager.setCurrentItem(sp.getInt(INDEX_KEY_STRING, 0));
}
Related
I have two activities. In the first activity, I have a SharedPreferences with a TextView, which displays the amount of data in the SharedPreferences. These codes are written in the onCreate()
SharedPreferences coin = getSharedPreferences("saved", MODE_PRIVATE);
SharedPreferences.Editors editor2 = coin.edit();
editor2.putInt("t", 0).apply();
editor.commit();
TextView name = (TextView) findViewById(R.id.textview);
Integer a = coin.getInt("t", 0);
name.setText(a.toString());
In the second activity, I wanna add 10 points to the data and update the SharedPreferences. These codes are not inside onCreate().
SharedPreferences coin = getSharedPreferences("saved", MODE_PRIVATE);
SharedPreferences.Editors editor2 = coin.edit();
int a = coin.getInt("t", 0);
int b = a + 10;
editor2.putInt("t", Integer.valueOf(b));
The problem is, after adding 10 units there is no update in the TextView so I don't even know if the 10 units have been added correctly to SharedPreferences or not.
Please help
If I understand, you would like reflect the final value of t in SharedPreference in your first activity after its updated in second activity?
To do that, create a function updateNameTV() which would contain logic to update the TextView with the value of t from SharedPreference
and call that function in onResume() of the FIRST activity like:
#Override
protected void onResume() {
// TODO Auto-generated method stub
updateNameTV();
super.onResume();
}
So when Activity 2 is launched, Activity 1 goes in back of the stack and onPause() gets called.. when we return to Activity 1 this activity is pop back and onStart() followed by onResume() is called.
These are the lifecycle events more here
So the plan is, when onResume() is called we update the TextView value with the latest SharedPreference
And we do that before calling super.onResume() such that update is performed before handing over the control to next lifecycle event. Hope this gives more clarity.
You have to register OnSharedPreferenceChangeListener in your first activity in order to listen to the changes and then update your TextView with the updated value.
Implement OnSharedPreferenceChangeListener in your FirstActivity:
public class FirstActivity extends AppCompatActivity implements
SharedPreferences.OnSharedPreferenceChangeListener {
...
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
// This method will be called when there is a change in SharedPreference
// Update your textview here
if(s.equals("t")) {
Integer a = sharedPreferences.getInt("t", 0);
name.setText(a.toString());
}
}
}
In your FirstActivity's onStart() and onStop() method, manage the listener:
#Override
protected void onStart() {
super.onStart();
getSharedPreferences("saved", MODE_PRIVATE).registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onStop() {
getSharedPreferences("saved", MODE_PRIVATE).unregisterOnSharedPreferenceChangeListener(this);
super.onStop();
}
But remember, once you leave your FirstActivity, the listener gets unregistered and you will no longer receive updates. To reflect the updates even after the activity go background, you can just update your textview in your onStart() so that when the FirstActivity starts, the textview gets updated with the latest value from SharedPreferences:
#Override
protected void onStart() {
super.onStart();
SharedPreferences coin = getSharedPreferences("saved", MODE_PRIVATE);
coin.registerOnSharedPreferenceChangeListener(this);
// Also Update the textview here
Integer a = coin.getInt("t", 0);
name.setText(a.toString());
}
Now, any update to the preference from anywhere will also change the textview text as soon as the FirstActivity comes into foreground or launches.
I have a switch button in my android app I intend to switch it on but after I exit the app by removing it on my background task when I opened again the app it goes back to normal and switch goes back to off again. i=I want to retain or save the activity which I have been left. How am I going to retain the task of my activity basically the fragment itself? Am I going to use On pause?
#Override
public void onPause() {
super.onPause();
}
You can accomplish this using shared preferences. For example, in onCreate, load the switch state from shared preferences (with a default for the first time)
SharedPreferences prefs = getSharedPreferences("MyUniquePrefsName", Context.MODE_PRIVATE);
switchState = prefs.getBoolean("MyBoolean", false); // switchState being a boolean class member
// then set the switch to switchState
When the user updates the switch, change the stored value of switchState and in onPause save the updated state to the shared preferences
#Override
public void onPause() {
super.onPause();
SharedPreferences.Editor ed = getSharedPreferences("MyUniquePrefsName", Context.MODE_PRIVATE).edit();
ed.putBoolean("MyBoolean", switchState);
ed.apply();
}
how does one save a clicked state in android listview after exiting the app and restore state on app launch.The app should be able to listen to click event on listview and save the state and when the app is closed it saves the clicked state and then restore it on relaunch.
i have tried using getView but it doesnt seem to work as expected. please help
What you have to do is, you have to override the below method in your Activity,
#Override
public void onBackPressed() {
super.onBackPressed();
}
And save the state of your Button using SharedPrefrence, and next time when you enter your Activity get the value from the Sharedpreference and set the enabled state of your button accordingly.
Example,
private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", button.isEnabled());
editor.commit(); // I missed to save the data to preference here,.
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
button.setEnabled(state);
}
#Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}
onCreate(Bundle savedInstanceState){
LoadPreferences();
//just a rough sketch of where you should load the data
}
I have two activities. Activity A has a button which starts activity B. When you hit the back button in activity B it restarts activity A. Also when the back button is hit it goes to the onStop method for activity B and in this point I update shared preferences for the user. Basically I'm storing player data on the shared preferences but the problem is when activity A is restarted I also load the same shared preferences but it doesn't show the updated data that I saved while activity B was stopped. I reload the app and it shows the up to date data. So it seems that while it is being saved while activity B is being stopped there isn't enough time for when it is loaded while activity A is being restarted. So how can I tell whether the shared preferences have finished being written to or not? Basically I want to load the shared preferences once I know for sure the shared preferences has been updated, is that possible?
I am using commit method:
#Override
protected void onStop()
{
Long dist = (long)treadmill_.Mod.distance_;
Long newdist = dist + PlayerInfoManager.getInstance().getDistanceTraveled();
PlayerInfoManager.getInstance().setDistanceTraveled(newdist);
float fastestSaved = PlayerInfoManager.getInstance().getFastestSpeedAcheived();
float fastestInSess = treadmill_.Mod.fastestSpeed;
if(fastestSaved<fastestInSess)
PlayerInfoManager.getInstance().setFastestSpeedAcheived(fastestInSess);
Long time = (long)treadmill_.Mod.time_;
Long newTime = time + PlayerInfoManager.getInstance().getTotalTimeRan();
PlayerInfoManager.getInstance().setTotalTimeRan(newTime);
Log.e("OnStop", "at Run, run, run");
super.onStop();
}
In PlayerInfoManager.getinstance().setDistanceTraveled(newdist):
public void setDistanceTraveled(Long distanceTraveled)
{
DistanceTraveled = distanceTraveled;
Editor edit = SP.edit();
edit.putLong("DistanceTraveled", distanceTraveled);
edit.commit();
}
SP is the sharedPreference instance:
private SharedPreferences SP;
For activity A when it restarts:
#Override
protected void onRestart() {
super.onRestart();
LoadStats();
Log.e("onrestart", " ");
}
public void LoadStats()
{
PIM.loadAll();
Dis.setText(Long.toString(PIM.getDistanceTraveled()));
FastestSpeed.setText(Float.toString(PIM.getFastestSpeedAcheived()));
TotalTime.setText(Long.toString(PIM.getTotalTimeRan()));
KeepItUp.setText(Long.toString(PIM.getLongestTimeInKeepItUp()));
}
public void loadAll()
{// load all saved player data from sharedpreferences
DistanceTraveled = SP.getLong("DistanceTraveled", 0L);
FastestSpeedAcheived = SP.getFloat("FastestSpeed", 0.0f);
TotalTimeRan = SP.getLong("TotalTime", 0L);
LongestTimeInKeepItUp = SP.getLong("KeepItUp", 0L);
}
using .commit() method will make sure your data has been saved.
see the android doc for sharedPreferences.
see the commit and apply method
Use onPause instead since this occurs before onStop
From the documentation
Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.
You might want to see the description of an Activity's lifecycle.
I am making my first Android app, which consists of just editText's and Spinner's. Reading up on the activity cycle, I am wondering if it is even necessary to use the Bundle mechanism in my situation.
Since the state of the widgets are automatically persisted -
could I just call the getSelectedItem() method on the spinners and getText() on the EditText's within the onCreate() method for the Activity and pass that on to my newly re-created model object rather than using the Bundle mechanism? What are the advantages and disadvatanges of this approach?
The state of widgets it not automatically persisted. When you activity is destroyed it loses all the information about state. I recommend you saving you application state using shared preferences. Here is an example from google developers site. it allows you to save your application state by storing key-value pairs and it should suffice for your app.
Save the text and spinner item position in shared preferences when your activity is stopped - onStop() and restore the state in onCreate().
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
Although you can save your application state by onSaveInstanceState(Bundle) method, usually the better way will be to do that in onPause() or onStop() methods(the data will be saved for sure). Documentation says:
Note that it is important to save persistent data in onPause() instead
of onSaveInstanceState(Bundle) because the latter is not part of the
lifecycle callbacks, so will not be called in every situation as
described in its documentation.