Android: How to load saved data from another class? - android

I've saved an int when a button is saved (in the upgrade class), and the int is called in another activity (the play class). But whenever I replay the app, I first need to go to the upgrade activity before the i go to the play activity, otherwise the integers I have saved aren't loaded properly.
public class Play extends Activity implements OnTouchListener {
MKZSurface ourSurfaceView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ourSurfaceView = new MKZSurface(this);
ourSurfaceView.setOnTouchListener(this);
setContentView(ourSurfaceView);
MYU = Upgrades.mYU;
BU = Upgrades.BU;
MBU = Upgrades.mBU;
RU = Upgrades.RU;
MRU = Upgrades.mRU;
}
And in the upgrades class I have saved these ints with a value using SharedPreferences. How do I load the data with the saved ints without the need to going to the upgrades page first?

You can retrieved your data without going back to Upgrades page if you have saved them using SharedPreferences. Use something like below to retrieve your data.
SharedPreferences prefs = getSharedPreferences(MY_PREFS, MODE_PRIVATE);
int indData = prefs.getInt(MY_INT, 0);
0 is the default value in case you haven't saved any values.

Go to Play activity firstly and check if saved value != DEFAULT_VALUE
otherwise go to upgrade activity and save new value

Related

Difficulty with SharedPreference data storage and losing values on exit

I am having trouble storing primitive data in an instance of SharedPreferences. Everything works as I thought it would, but when I close or exit my app and reopen it, the values in the SharedPreference go back to the default states.
I think it may have to do with either where or how I set the default values. Here is the snippet I am referring to that resides in the onCreate() of my main activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null){
userDetails = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor edit = userDetails.edit();
edit.putInt("list_code", 0); //stores the number corresponding to a word list
edit.putInt("highscore", 0); //stores the starting score
edit.commit();
}
Thougts?
The Bundle != null when your activity "restarts". For instance when screen was rotated or system killed background activity and recreated it. Otherwise it equals null. So to save some data between different instances of activity you need to check whether you save data before or not.
Sample:
SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
int highScore = preferences.getInt("highscore", -1);
if (highScore == -1) {
//preferences was never used, so put default value
highScore = 0;
preferences.edit().putInt("highscore", highScore).commit();
}

Android maintain activity state with data

I have 2 different activities. MainActivity, ContactList & ContactDetails. Now from MainActivity user will tap on Add new and application will open ContactList screen from where user can select any contact to see details which opens ContactDetails activity. Now if user select any no. from ContactDetails, application will go back to MainActivity and add the selected no. in arraylist. I am able to add the data but my problem is that whenever add new record old records are erased. I found the reason that evertime i open MainActivity from ContactDetails it creates new Activity. So i am looking for a way to use OnResume or OnResult Method to solve the problem.
In ContactDetails
Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.putExtra("CONTACT_NO", CONTACT_NO); startActivity(intent)
In MainActivity OnResume method
String data = getIntent().getExtras().getString("keyName");
arr.add(data);
If you are looking to persist data during the lifetime of your Activity, SharefPreferences will serve you well. An example:
Write (onPause/onDestroy):
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Read (onResume/onCreate):
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Read more here.
Update
Alternatively, you can use onSavedInstanceState. Example:
Save state:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
Restore state:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
...
}
More information about managing Activity states here.
From where ever you are getting the list in MainActivity.java, take it as public static ArrayList or String array and do not initialize it in MainActivity.java.
Also if you have not called finish() for MainActivity (while going to ContactListActivity.java), then add the new data to the arraylist in onResume(). But remember to keep a checking - whether you have a new data to add or not because for the first time, there would be no data to add (as per your posted question).

variables need to be saved

I am making an application that contains a form and whenever a data clicks a button loads from a BD in a EditText, but every time I press a different button, the other EditText are cleared, I tried with:
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("data", myVariable);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
other = savedInstanceState.getString("data");
name.setText(other);
}
Sorry if I have not explained well, I need that every time they change Activity variables and I have not deleted. Any suggestions? Thank you!
Try using Android SharedPreferences instead. This is a persistent key-value storage that Android offers for its apps and was designed to covers issues like this. Here's the easy way to use it:
SharedPreference prefs = PreferenceManager.getDefaultSharedPreferences(this);
// To put a data (in this case a String from your EditText)..
Editor editor = prefs.edit();
editor.putString("data", yourStringHere);
editor.commit();
...
// ..and to retrieve it..
prefs.getString("data", null);
// NOTE: The 'null' in above method call could be replaced by any String you want;
// it basically specifies a default value to get when "data" is empty or doesn't
// yet exist.
Hope this helps.

How can i stop to be refreshed my values in android activity

I am working in android. I am designing a file upload functionality.
This is my layout:
If I fill my entries like as title,price,category and then I press browse button for browse option then I go to BrowseActivity using startActivity(). But when I come back to this activity then all entries which were filled by me disappear. please suggest me what should I do for this so my entered entries save. If I do browse first then fill entries then it works properly.
What should I do for the case in which user first fill entries and then click on the browse button?
Use the SharedPreferences options to save all the Strings in onPause(). You can get them back in onResume() and fill out your text boxes. This is also nice since you can save the values that were entered and restore them each time the user leaves the app for any other reason.
EDIT:
Quick example:
Save your strings like so:
#Override
public void onPause(){
super.onPause();
// Save the user preferences during runtime for later use.
SharedPreferences settings = getSharedPreferences("aName", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("title", "Value of title");
editor.commit();
}
Then you get get the value back like this.
#Override
public void onResume(){
SharedPreferences settings = getSharedPreferences("aName", MODE_PRIVATE);
String title = settings.getString("title");
}
Here is what you need to do.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putString("title", title.getText.toString());
//Do the same for the other 2 boxes.
super.onSaveInstanceState(savedInstanceState);
}
and in onRestoreInstanceState() pull the items out.
Like..
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
String Title = savedInstanceState.getString("title");
//Do the same for other String items you put into the bundle using the savedInstanceState() above. And then use EditText.setText(title); to set the text
}
The bundle is used exactly for this purpose. You Can get more info here
Check out android's shared preferences, they should give you an easy way to store data.
Android Shared Preferences
http://developer.android.com/guide/topics/data/data-storage.html
http://developer.android.com/reference/android/content/SharedPreferences.html
Another way is to create an object which holds the data you need, and don't new it in the onResume method...

Android - persisting activity instance

I am using instances of two activies (A and B) among my application. Now I am facing problem of persisting each of them. When I use sharedpreferences, I can get only to persisting A.class and B.class with SharedPreferences, but when I use instance A again. It's persistent state in SharedPreferences is overriden. I think, I should use Bundle wtih onSavedInstanceState and onRestoredInstanceState. But how to pass saved Bundle into onCreate()? Goal is to be able to persist activity instances.
Thanks
When launching activity A. You can use intent.putExtra( String name, Bundle value ) to pass the bundle to your activity and then in Activity A's onCreate use getIntent.getBundleExtra( String name ) to get your bundle again.
You need to consider what state you need to persist.
For example;
which checkboxes have been ticked?
what level is the user on?
what is the position of their cursor
As an example,
I just finished an application where a user can view different levels of flashcards.
I care about;
which level of flashcard they are looking at (maybe they're at level 2)
which card are they looking at (maybe they're on the 4th card)
Here's the code.
// a variable to store the level
private final static String CARD_LEVEL_STATE = "currentCardLevel";
// a variable to store the current card
private final static String CURRENT_CARD_STATE = "currentCardNumber";
#Override
protected void onSaveInstanceState(Bundle outState) {
// save the level
outState.putInt(CARD_LEVEL_STATE, flashCardList.currentLevel());
// save the current card
outState.putInt(CURRENT_CARD_STATE, flashCardList.currentCardNumber());
// do the default stuff
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// ignore if we have no saved state
if (savedInstanceState != null) {
// record the level
if (savedInstanceState.containsKey(CARD_LEVEL_STATE)) {
int currentCardLevel = savedInstanceState.getInt(CARD_LEVEL_STATE);
flashCardList.setCardLevel(currentCardLevel);
}
// recover the current card
if (savedInstanceState.containsKey(CURRENT_CARD_STATE)) {
int currentCardNumber = savedInstanceState.getInt(CURRENT_CARD_STATE);
flashCardList.setCurrentCardNumber(currentCardNumber);
}
// refresh the view
refreshCard();
}
super.onRestoreInstanceState(savedInstanceState);
};

Categories

Resources