I want to save some values with SharedPreferences in my app. These values constantly change when it is active (for example every game brings some coins, and I want to save these coins). However I don't know when the user will quit the app in order to save the coins then for next time. So in every activity where the coins change I have:
#Override
protected void onStop() {
super.onStop();
SharedPreferences sp = getSharedPreferences("my_pref", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("coins", MainActivity.COINS);
editor.commit();
}
Is there a way to do this better.
use isFinishing() in onPause() method that means that the application paused and if isFinishing() is true then your app will end
#Override
protected void onPause() {
super.onPause();
if(isFinishing())
{
//finishing logic here
}
}
Related
I am working on an app, so basically, when the user launches the app for the first time, activity A comes up, which asks the user for a bunch of data. Now, that I have the data, I take the user to activity B. Here, if the user kills the app completely, and relaunches it, the app reopens activity A, instead of B... Is there a way to control this behaviour? I want to be able to control what activity the app should open after a particular action by the user... Note : I am a complete newbie, so I have no idea how to do this.. I tried to ask this up on a google search, but couldn't find anything proper ig.
You can store boolean by shared preference to do that. Here your AcitivityA class. Store user provided data before user land to ActivityB.
public class ActivityA extends AppCompatActivity {
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
try {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean firsttimeLoad = prefs.getBoolean("first_time_load", true);
if (!firsttimeLoad) {
sendToB();
}
} catch (Exception e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("first_time_load", false);
editor.commit();
//Store user data here
sendToB();
}
});
}
private void sendToB() {
Intent mainIntent = new Intent(ActivityA.this, ActivityB.class);
startActivity(mainIntent);
finish();
}}
The easiest way to use user data in all over the app. Make a separate class for storing user data and make the getter and setter to get and set the data.
public class UserSharedPrefs {
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
#SuppressLint("CommitPrefEdits")
public UserSharedPrefs(Context context) {
sharedPreferences = context.getSharedPreferences("UserData", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public void setIsLogin(boolean isLogin) {
editor.putBoolean("isLogin", isLogin);
editor.apply();
}
public boolean getIsLogin() {
return sharedPreferences.getBoolean("isLogin", false);
}
In Activity A makes the reference of that class and get the data and use it as your need. And send the user to desired Activity
if(userSharedPrefs.getIsLogin()){
moveToActivityB()
}
I have a problem that should remember-save the text from the TextView that the user inputs through his voice, but I have enabled the Night mode, at the time when the day mode passes into the night mode, the text entered at that moment disappears. I know that it needs to be SharedPreferences, I tried this code, but I can not record anything. I emphasize that there is no Save button. It is necessary to return the text already entered when refreshing the Activity. I ask for help please
/*...*/{
//...
myText = (TextView) findViewById(R.id.textView);
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (!TextUtils.isEmpty(restoredText)) {
myText.setText(restoredText);
}
//...
}
public void loadData() {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("text", myText.getText().toString());
editor.commit();
}
It sounds like your activity is getting killed. If this is the case, then you should implement the android activity lifecycle methods onSaveInstanceState and onRestoreInstanceState.
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(bundle);
state.putString("text", myText.getText().toString());
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
myText.setText(savedInstanceState.getString("text"));
}
I have a situation with onResume() method and I don't know how to solve it.
conssider the following code:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
Log.d("tag", "onCreate");
}
#Override
protected void onResume() {
super.onResume();
//do something only when everytime the activity comes to screen
Log.d("tag", "onResume");
}
private void myMethod() {
this.onResume();
}
}
If we asume that myMethod will definitly be called, I don't want to let onResume() to execute //do something only when everytime the activity comes to screen. I should note that myMethod is a fixed method and cannot be changed.
PS:The reason that I am asking this question is that I have a simillar situation with PermissionDispatcher library with android 6 and I want to call a "risky permission" in the onReume() method but if the user denies the permission, it will call the onReume() again, and since the permission required task is in the onResume(), the permission will be denied again and cauases an inifite loop
could anyone give me a suggestion?
UPDATE: here is the permissionDispatcher library and the issue that is related to my problem
verify this method Already Executed or not simply in if Condition
Bool a=true;
#Override
protected void onResume() {
super.onResume();
//do something only when everytime the activity comes to screen
if(a==true)
{
//your Actions
}
else if(a==false)
{
//do nothing
}
}
Use SharedPreferences in onResume
#Override
protected void onResume() {
super.onResume();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean firstStart = settings.getBoolean("firstStart", true);
if(firstStart) {
//do something only when everytime the activity comes to screen
Log.d("tag", "onResume");
//display your Message here
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstStart", false);
editor.commit();
}
}
I have an if loop when a chebkox in sharedpreferences changed status. But I'm not able to set putBoolean("blabla", false); when the status changed.
For example: User hits checkbox, CB gets checked, if says uncheck it but it won't uncheck.
My Code:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals("cbSaveUsername")) {
SharedPreferences.Editor SFEdit2 = sharedPreferences.edit();
SFEdit2.putBoolean("cbSaveUsername", false);
SFEdit2.commit();
}
}
Can anyone tell me my mistake?
Edit: It looks like it works programatically but the tick is still in the box :o Where could be the mistake? I use it like Gunaseelan postet
Try to use onPause() and onResume() methods.
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
For more details onSharedPreferenceChanged not fired if change occurs in separate activity?
im building a app, found a java part that lets me show an activity only at first start.
this works but when i kill the app or reboot my phone it goes back, can anyone help me out with this?
im using this in my main activity (Toolz.java)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Prefs.firststart == false) {
setContentView(R.layout.toolz);
} else {
Intent i = new Intent(this, First.class);
startActivity(i);
finish();
}
}
#Override
protected void onResume() {
super.onResume();
}
and i added this to First.java
Prefs.firststart=false;
and i made the Prefs.java and added this
public class Prefs {
public static boolean firststart = true;
}
you will need to use SharedPreferences instead o static variable for saving data which also available when app killed or device reboot.
you can see following tutorial how we use SharedPreferences for saving and reading data from SharedPreferences
Shared Preferences
When the app restarts all your code will start from the starting point (i.e Prefs.firststart will be set to true). Instead, you need to make a persistent variable that is saved throughout sessions. If you're using a DB you could use that, or you could use the built-in SharedPreferences, as such:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = this.getPreferences(MODE_PRIVATE);
if (prefs.contains("started")) {
setContentView(R.layout.toolz);
} else {
//Add the preference:
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("started",true);
editor.apply();
Intent i = new Intent(this, First.class);
startActivity(i);
finish();
}
}
When you kill your app, the values are going to reset to their initial values. Your boolean will be equal to true. I suggest saving the state of the variable using SharedPreferences. Check out this other question someone asked about saving.
How to save a state of a variable in android app and use it
Try it like this
//**** First start *****
//you get the prefs for your app using a pref name
String PREFS_NAME = "myAppPrefs";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
//persist the boolean value in preferences using a key-value approach
editor.putBoolean("pref_app_started", true);
//commit the changes
editor.commit();
and when you start the app you check for that pref
//**** next start *****
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
//now we get the saved boolean using the key we previously uesd when setting it
//the second parameter is the default value for the flag in case it was never set
boolean wasAppStarted = settings.getBoolean("pref_app_started", false);
//now you can use your wasAppStarted flag to decide what you do further