How to set Vairable to 0 on Only first open - java

Is there a way for me to set a integer variable to 0, but it will only do this on the first time the app is opened by a device?

Create a shared preference. Query the shared preference int value (for example) at the start of the application. If it's a first time boot up we get the default 0 value where we change the shared preference value which helps us keep track that it isn't a first time start in the future start of the application.
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
In your splash (or wherever necessary) check for a specific key of the shared preference like this :
//Check for the key "tracker", if it does not exist consider the default value as 0
int appStartTracker = pref.getInt("tracker", 0);
if(appStartTracker == 0){
// It means you started the app for the first time. Do what you have to
// and set the preference to 1 or increment the appStartTracker to keep
//track of how many times the app has been started.
appStartTracker++;
editor.putInt("tracker", appStartTracker);
editor.commit();
}else{
// Not a first time start.
//Do the following if you need to keep track of total app starts else ignore
appStartTracker++;
editor.putInt("tracker", appStartTracker);
editor.commit();
Log.d("TAG", "App has been started for the " + appStartTracker +"time");
}
P.S The shared preference is cleared when the user clears data.

Related

storing & loading your apps previous state

I am using static session_counter to store the data,
yes the data I want to retrieve when app is opened is a INTEGER
private static int session_counter = 0;
MY app state
AFTER USER PERFORMED AN ACTION THE SESSION COUNTER SHOWS 1,
BUT WHEN THE APPLICATION IS CLOSED AND RE-OPENED AGAIN THE COUNTER IS SET TO 0
I WANT THAT SESSION COUNTER TO BE THE SAME AS PREVIOUS STATE TILL THE SPECIFIC CONDITION IS MET
For applications such as this you need a way where you can persist the data between each session.
as a previous answer mentioned shared preferences is the most effective way to do it.
Other alternatives exist as
Room
A remote database (Firebase) etc.
The structure will be somewhat like this
```
// Create object of SharedPreferences.
SharedPreferences sharedPref = getSharedPreferences("mypref", 0);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("session_value", required_Text);
//commits your edits
editor.commit();
// Its used to retrieve data
SharedPreferences sharedPref = getSharedPreferences("mypref", 0);
String name = sharedPref.getString("session_value", "")
```
In your case it will be like
textView.text= sharedPref.getString("session_value", "")
if(condition){
editor.putString("session_value", required_Text);
}
You might want to use shared-preferences to save your value. This answer might be useful

How to pass the same data with different value with putExtra()

I am working with a service class that needs to know if the application is running in background or not. To do so, I created a boolean variable called activityVisible in my service. I need to update it constantly to know wether the app is in background or active.
I do this by sending true on the onResume() method in my activity like this:
intent.putExtra("Activity Visible", true)
and false on the onPause() method like this:
intent.putExtra("Activity Visible", false)
However, I print the extra in my service and it is always getting true. What I think it is happening is that once you put an extra, you cannot update its value, and that may be the reason it is not working.
Any way I can do the same in a different way? Or a solution to the way I am implementing this?
You can use SharedPreference to store the current state of the app.
to reference to the SharedPreference
SharedPreferences sp = getSharedPreferences("prefs", Context.MODE_PRIVATE);
to set a boolean in the shared preference, you need to use its editor, so apply this code in onPause, and onResume, while changing the "isVisible" value based on your need
boolean isVisible = true;
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("activity_visible", isVisible);
editor.apply(); // use apply to confirm the edit
and in order to get the value stored, you can simply refer to it using
boolean valueStored = sp.getBoolean("activity_visible", false /* Default value if not existed */);
Log.d("Activity State: ", "Boolean: " + valueStored);
and do whatever you want with that valueStored.

Store variable in shared preferences and changes their value on different activities

I'm working on a practise 7 days exercise app. I set a progree bar on the main activity and want to change progress after days. Means if i complete exercise of day 1 ,progress bar set 15% . and when i complete day2 , progress set 30%. I can do it without shared preference , it working correctlt but when after day1 complete i closed the app it again set progress from 0 . So i want to use shared preferences for this reason . Kindly someone guide me regarding this issue;
For Set Value to Shared Prefrence
SharedPreferences.Editor editor = getSharedPreferences("ProgressBarData",
MODE_PRIVATE).edit();
editor.putInt("progress", 15);
editor.apply();
for get value From Shared Prefrence
SharedPreferences prefs = getSharedPreferences(ProgressBarData,
MODE_PRIVATE);
int progress = prefs.getInt("progress", 0);
1st ur know ur mistake
u can't store ur data in local variable because at the end of the activity it destroyed every things and when u come back to android activity it will be started all thing once again and every thing is restarted
[https://developer.android.com/guide/components/activities/activity-lifecycle
read this u have better understanding
Now ur solution
if u want to store the data and process every day better to use local storage like
Sqlite ,room or shared preference.
Step to do the task
There is three step to store, get and remove data into share preference
For storing , getting deleting data
//storing
SharedPreferences.Editor editor = context.getSharedPreferences(name,Context.MODE_PRIVATE).edit();
editor.putString(key, data);
editor.apply();
//getting
SharedPreferences getSharedPrefrence = context.getSharedPreferences(name, Context.MODE_PRIVATE);
int data = getSharedPrefrence.getInt(key, IntegerValuesAndStringValues.REGISTER_BEFORE_LOGIN);
return data;
BasicFunctions.removeSharedPrefrences(getContext(),"Name of the preference");

What does this SharedPreferences code do in Android?

I understand what SharedPreferences do but still struggling to get my head round what this piece of code is trying to do.
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
if (sharedPref.getBoolean("login", false)) {
edtUser.setText(sharedPref.getString("user", ""));
edtPass.setText(sharedPref.getString("pass", ""));
new SigninTask().execute("user=" + edtUser.getText(), "pass=" + edtPass.getText());
}
I understand that the first line is accessing the default SharedPreferences file. However I am still confused, what does this set code do exactly?. What information is it trying to get?. What does the last line do? (new SigninTask())..
sharedPref.getString("user", "") tries to get a preference with the key user from the SharedPreferences. If it's not found, it returns an empty String. This value is loaded to a Text control (I assume, since you didn't include the definition of edtUser).
The same is done with the value of pass, which probably represents a password.
Basically, this app probably stores in SharedPreferences the user and password that were entered by the user of the app in a previous launch of the app, so that the user doesn't have to enter them again every time the app is launched.
There should be additional code that would store the entered user and pass in the SharedPreferences, and store the login preference with the value true.

Update Shared Preferences after restarting application

I use Shared Preferences to fetch and store a variable, I then fetch that variable across a different class. After I restart the app, the initial variable stored is to be updated by the new one. What I can see is that on quitting the application, I should set my shared preference to be cleared and then again fetch the fetch value.
However, the problem is that even on restart, the shared preference still store the older value and do not update themselves.
Here is the code where I initially save the value
protected void onLoginSuccess(String cookieString, String userName) {
// set cookie and initialize data center.
mCookieString = cookieString;
SharedPreferences settings =getSharedPreferences("cookie",MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("cookie", cookieString);
editor.commit();
//editor.apply();
mDataCenter = new LsApiDataCenter(this, userName);
mCachedUserData.clear();
System.out.println("shhhhhhhhhhhh iis original : "+cookieString);
mSendersObservers.clear();
mMessageObservers.clear();
mNotificationObservers.clear();
Later, Upon exit I want the shared preference to be cleared and this is how I do it
protected void onLogoutSuccess() {
// clear cookie and data center.
SharedPreferences settings =getSharedPreferences("cookie",MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.clear().commit();
mCookieString = null;
mDataCenter = null;
mCachedUserData.clear();
mSendersObservers.clear();
mMessageObservers.clear();
mNotificationObservers.clear();
Finally, this is how I fetch them in a completely different class
SharedPreferences settings = mMainActivity.getSharedPreferences("cookie", Context.MODE_PRIVATE);
count = settings.getString("cookie","");
The problem is that the value which I get upon fetching is the old value and not the latest value since i am fetching a value provided by a server via api used when the user logs in. However, I get the old value and the latest value is not fetched.
Thanks
If you want to clear the value of cookie variable you can do like this
SharedPreferences settings =getSharedPreferences("cookie",MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("cookie", null);
editor.commit();

Categories