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).
Related
I have an activity A, it has a button to open B, which inserts a record. A can then refresh the view inside onActivityResult. This is a normal flow.
However, B can accept share intent to insert a record also. How can A know when this action is done from B to refresh the view just like the normal flow? (of course, I assume act A already running on background task)
I can, of course, detect the change using onResume inside A, but i wish to know if it is a proper method.
thank you
You can use onResume to refresh the view for activity A. Because other method would be using broadcastReceiver and broadcastIntent and that would create unnecessary load.
You can use sharedPreference to store if data has been changed in Activity B and then in onResume of Activity A fetch that shared Preference and refresh the view
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean isChanged = sharedPreferences.getBoolean("isChanged",false);
if(isChanged){
//refresh your views
//clear the shared prefernce
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean("isChanged",false);
editor.apply();
}
}
Remember you have set that shared preference in ActivityB while loading data
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean("isChanged",true);
editor.apply();
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();
}
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.
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
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...