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
Related
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");
I have a variable and I want to change it only the first time that I start my app. For example:
I open the app: Variable is not initialized. Variable changes to 4.
I close the app
I open the app Variable is 4.
And so on.
How can I do this?
I guess you are new to Android. You can save the values using "SharedPreferences".
Check this link : https://developer.android.com/training/basics/data-storage/shared-preferences.html
Also check out this example :
https://www.tutorialspoint.com/android/android_shared_preferences.htm
You can use this code :
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();
Here, MyPREFERENCES is the file name. Replace the "value" with the variable name.
Again, if you want to retrieve the value, then use:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.getBoolean("key", true);
//There are other methods like getInt(),getDouoble().getString() depending on the type of value
You can also write to a local file and use SQLite for that purposes if you would like to persist big object's data.
Below is a snippet of code that i use in my save settings function (DialogFragment):
String orderBy = mOrderBySpinner.getSelectedItem().toString();
String search = mSearchEditText.getText().toString().trim();
SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(InventoryPreferences.ORDER_BY, orderBy);
editor.putString(InventoryPreferences.SEARCH_TERM, search);
editor.apply();
I then retrieve that data with the following (Activity):
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String orderBy = sharedPrefs.getString(InventoryPreferences.ORDER_BY, "name ASC");
String searchTerm = sharedPrefs.getString(
InventoryPreferences.SEARCH_TERM,"").trim();
These are my keys:
public static final String ORDER_BY = "orderBy";
public static final String SEARCH_TERM = "search";
Is there any reason as to why it wouldn't update the values when the key is the same?
getActivity().getPreferences(Context.MODE_PRIVATE);
is not
PreferenceManager.getDefaultSharedPreferences(this);
Use the second line in both methods.
From the docs:
https://developer.android.com/reference/android/app/Activity.html#getPreferences(int)
Retrieve a SharedPreferences object for accessing preferences that are
private to this activity
You are using two different methods to get access to a SharedPreferences file.
The first time using getActivity().getPreferences(Context.MODE_PRIVATE) you are calling Activity's getPreferences(int mode) which returns a SharedPreferences object which is supposed to be private to the activity which requests it. The name of the preferences file this SharedPreferences object points to is CLASS_NAME.xml
The second time using PreferenceManager.getDefaultSharedPreferences(this)
returns a SharedPreferences object which is supposed to be available and useful for the entire application. The name of the preferences file this SharedPreferences object points to is PACKAGE_NAME_preferences.xml.
So your problem is that you are using one file to write the preferences to and another to read them. Try using the more global thinking PreferenceManager.getDefaultSharedPreferences(Context context) to store preferences that relate to the entire application, and only use Activity.getPreferences(int mode) for preferences that only relate to a specific activity. (And then also remember to use the appropriate methods to retrieve them)
Use PreferenceManager to access SharedPreference.
Your code for updating preference value is correct.
Consider verifying that the values in input controls really changed
and verify, that the application has permission to write preferences.
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();
I am working on a small project that requires a details screen where the user inputs his details and they are permanently stored. The user must have the option to change the details as well if he needs to do so. I looked into the saved preferences library however it does not seem to offer such functionality.
To give a visual idea of what is required, something like this screen should be fine:
http://www.google.com.mt/imgres?start=97&num=10&hl=en&tbo=d&biw=1366&bih=643&tbm=isch&tbnid=aQSZz782gIfOeM:&imgrefurl=http://andrejusb.blogspot.com/2011/10/iphone-web-application-development-with.html&docid=YpPF3-T8zLGOAM&imgurl=http://2.bp.blogspot.com/-YRISJXXajD0/Tq2KTpcqWiI/AAAAAAAAFiE/-aJen8IuVRM/s1600/7.png&w=365&h=712&ei=rbX6ULTDCOfV4gTroIDoCg&zoom=1&iact=hc&vpx=834&vpy=218&dur=2075&hovh=314&hovw=161&tx=80&ty=216&sig=108811856681773622351&page=4&tbnh=155&tbnw=79&ndsp=35&ved=1t:429,r:4,s:100,i:16
Any help is much appreciated. Thanks in advance
You could easily use Shared Preferences to store user's details. Everytime the Preference screen is opened the stored data can then be extracted from the Shared Preferences and presented to the user for edit. ONce the edit is done the new data can be updated back in the the Shared Preferences.
Also look at this thread to see how this can be done.
Using SharedPreferences would be perfect for this kind of small amount of data which you want to store persistently.
// 'this' is simply your Application Context, so you can access this nearly anywhere
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To obtain from the preferences:
// You can equally use KEY_LAST_NAME to get the last name, etc. They are just key/value pairs
// Note that the 2nd arg is simply the default value if there is no key/value mapping
String firstName = prefs.getString(KEY_FIRST_NAME_CONSTANT, "");
Or to save:
Editor editor = prefs.edit();
// firstName being the text they entered in the EditText
editor.putString(KEY_FIRST_NAME_CONSTANT, firstName);
editor.commit();
You can achieve such functionality using SharedPreferences Class in android.
public void onCreate(Bundle object){
super.onCreate(object);
// Initialize UI and link xml data to java view objects
......
SharedPreferences myPref = getPreferences(MODE_PRIVATE);
nameView.setText(myPref.getString("USER_NAME", null));
passView.setText(myPref.getString("PASSWORD", null));
}
public void onStop(){
super.onStop();
if (isFinishing()) {
getPreferences(MODE_PRIVATE).edit()
.putString("USER_NAME", nameView.getText().toString())
.putString("PASSWORD", passView.getText().toString())
.commit()
}
}