i have a default activity that starts first (Activity A), and from there the user can go to another activity (Activity B). In B after some work the user sets a sharedpreference. the next time the app starts i want to check in A if sharedpreference is null to go to B. and i put this if just under
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
and it encapsulates the whole onCreate. when the app starts it skips A and on B i shows the layout and the FC with NullPointerException.
Any one got experience with this?
OR
any one got a better idea on skipping A?
Well Simon you have to use Shared prefrences. save your data in shared prefrences. Then in the activity where you want to use the data in Shared prefres again get instance of same shared prefrence. get the data and use it.
go through this code
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();
}
}
probably you will get an insight
To answer my own question. i had a location listener in onDestroy an because it was not initialized because of skipping onCreate it returned NullPointer.
Related
I have one application that uses SharedPreferences to record the checkin or checkout state of the user.
If the checkin is pressed, it's button is grayed out the checkout becomes available, the opposite work as well.
However some users tells me that "sometimes" they will make another checkin on the next day and the checkout is still available.
Im supecting that they are forgetting to tap it, but i want to know if is there by any chance that this SharedPreferencces get cleared by itself?
this is the part of my code that i save the checkin state:
SharedPreferences preferences = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("statuscheckin", 1); //1 for checkin, 0 for checkout
editor.commit();
this is the part where i check it
if (getSharedPreferences("MyPreferences", Context.MODE_PRIVATE).getInt("statuscheckin", 0) == 1) {...}
Unless you clear the storage/cache, SharedPreferences won't get cleared by itself.
Make sure you are not clearing it by yourself for any condition happening.
If you are getting the default value only, it's possible that you are using it before the value gets committed.
Try this code,
Session Manager code:
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Context context;
public static final String KEY_CHECKIN= "checkin";
public void setCheckin(boolean login){
editor = sharedPreferences.edit();
editor.putBoolean(KEY_CHECKIN,checkin);
editor.apply();
}
public boolean getCheckin(){
return sharedPreferences.getBoolean(KEY_CHECKIN,false);
}
In your Java code:
SessionManager sessionmanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sessionmanager = new SessionManager(this);
//Condition for checkin
if(user checkedIn){
sessionmanager.setCheckin(true);}
//Retrieving the value when user again opens the app:
if(sessionmanager.getCheckin()){}////proceed with your logic.
I`m trying to pass 3 int values to another class using shared preferences. But the issue is that only first value gets added the remaining two values only default values are shown.
The shared prefs editor is committed;
The main function is fragment activity,the second one is fragment
This getsharedprefs is used to access the shared preferences from fragment
here is my code
{
SharedPreferences sharedPreferences;
SharedPreferences.Editor sharedPrefsEditor;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help_images);
sharedPreferences=getSharedPreferences("values",MODE_PRIVATE);
sharedPrefsEditor=sharedPreferences.edit();
sharedPrefsEditor.putInt("length",length);
sharedPrefsEditor.putInt("response1",intentResponse1);
sharedPrefsEditor.putInt("response2",intentResponse2);
sharedPrefsEditor.commit();
}
this is my second class
{
sharedPreferences=this.getActivity().getSharedPreferences("values",
Context.MODE_PRIVATE);
length=sharedPreferences.getInt("length",-1);
intentResponse1=sharedPreferences.getInt("response1",0);
intentResponse1=sharedPreferences.getInt("response2",-1);
}
all the variables are declared properly,
this is my first question in stack overflow, so kindly bear any mistakes i made
My question is "Is there any way to save state of activity, that can be used when application has been restart.".
In my application, I had been override onSaveInstanceState and onRestoreInstanceState to save and restore my instance state.
I also used SharedPreferences to save the state. But I found that SharedPreference has been clear when I pressed Back Buttaon and restart my application.
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
SharedPreferences pref = getSharedPreferences(MY_APP, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(USER_NAME, name.getText().toString());
editor.putInt(COUNT_STATE, count);
editor.commit();
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
SharedPreferences pref = getSharedPreferences(MY_APP, MODE_PRIVATE);
name.setText(pref.getString(USER_NAME, ""));
count = pref.getInt(COUNT_STATE, 0);
}
I also know that this problem has been solved if I used external or local storage.
I want to know that can I persist application state without using file or database.
at onBackPressed() you need to store your state
and when activity created onCreate() you need to restore it
private void saveMyState(){
SharedPreferences pref = getSharedPreferences(MY_APP, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(USER_NAME, name.getText().toString());
editor.putInt(COUNT_STATE, count);
editor.commit();
}
private restoreMyState(){
SharedPreferences pref = getSharedPreferences(MY_APP, MODE_PRIVATE);
name.setText(pref.getString(USER_NAME, ""));
count = pref.getInt(COUNT_STATE, 0);
}
#Override
public void onBackPressed() {
saveMyState();
super.onBackPressed();
}
#Override
public void onCreate(Bundle savedInstanceState){
//init views, buttons, textViews (findViewById)...
//do other works ...
//:
//:
//then try to restore state (if saved)
restoreMyState();
}
if you want you can do the same call saveMyState() and restoreMyState() at
onSaveInstanceState() and onRestoreInstanceState() in case of orientation changed
i think this will cover all the cases you want.
PS: using SharedPreferences will write/read to a file, under the hood so you are already using file if you are using SharedPreferences
For my question, I try to change behavior of Pressed Back Button by overring onBackPressed.
In this method I write moveToBackTask(true).
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
My application state has been restored when I pressed back button and restart application.
But I think that this state can't be restored when I restart my device.
Do I need to store my state in a file?
I'm developing an application in which I have to show an activity only once in the app lifecycle.
What I'm doing is on my MainActivity.java I'm calling an Activity 1, so after when I move in my app and whenever I come back to MainActivity.java my Activity 1 is called. I just want to show it once.
And again Activity 1 should be displayed when user kills the app and restarts it.
Here is what I'm doing in my MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startActivity(new Intent(MainActivity.this,
Activity1.class));
}
I have tried using the following code but it only run once, when the app is installed for the first time.
private boolean isFirstTime() {
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
// first time
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
}
return !ranBefore;
}
How can I modify the above code, so that my requirement is satisfied.
Any kind of help will be appreciated.
You should set ranBefore to false in onDestroy
#Override
public void onDestroy()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", false);
editor.commit();
}
Change
return !ranBefore
to
return ranBefore
It looks to me that you are always returning the same thing instead of the variable you initialize. Also, you could put the code to start the Activity directly in that method. Then you don't have to even worry about a return statement. It will just never run it again after you change the value in SharedPreferences
Edit
you can set your SharedPreferences value to false in onCreate(). This will work if you don't finish your Activity when you go to another and if its your main Activity then you probably don't ever want to finish it until you exit the app
I have solved this problem using SharedPreferences. What I have done is on Splash I entered some values in SP, and on the MainActivity I checked that, if the value matches show the activity, otherwise don't open the dialog. And on keyCodeBack(), I have cleared SP, this helps me in meeting my requirement.
Use shared preferences..
and to kill the activity, use class.finish() at your onClick()..
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.