So currently I have:
public void SaveText(View view) {
String saved = text.getText().toString();
// TODO
Toast.makeText(getApplicationContext(), R.string.addedfavs, Toast.LENGTH_SHORT).show();
}
How do you save the 'Text' string and save it into shared preferences, without overwriting previous saved strings.
(Note: I've tried using arrays and array lists but I just end up with one result and overwriting it rather than adding to the previously saved strings)
I'm pretty new to this so please don't skip any steps regardless of how insignificant they may seem.
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
while saving
public void SaveText(View view) {
String saved = text.getText().toString();
SharedPreferences.Editor editor=prefs.edit();
editor.put("value",saved);
editor.commit();
Toast.makeText(getApplicationContext(), R.string.addedfavs, Toast.LENGTH_SHORT).show();
}
while retriving
String value=prefs.getString("value");
Read the content which is already stored in your SharedPreferences, append the new value and finally write back to SharedPreferences.
Related
I have a variable who contains data that can change when user is using app.
My goal is to store those data in SharedPrefs just before user is closing app,
I was thinking about something like
OnStop() {
Preferences.edit()... }
but i don't know the correct syntax ...
thanks in advance guys
Save your data in SavedPrefs in onStop Method.
Syntex will be like
In onStop Method
#Override
protected void onStop() {
super.onStop();
SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = saved_values.edit();
edit.putString("key", "stringToBeSaved")
editor.commit();
}
And then to retrive your data in onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String foo = saved_values.getString("key", "default_string");
}
Remember the key should be same.
For more info check out Android docs on
Shared Preferences: Save key-value data
Android Lifecycle: Understand the Activity Lifecycle
Activity.onStop() is called just before the app is completely closed (kicked from recents)
You should probably use Activity.onPause() to save your preferences as it will also be called when the user just switches to another app.
Further information:
https://developer.android.com/guide/components/activities/activity-lifecycle
You should save your persistent data in onPause() rather than in onStop().
Then you can retrieve your data in onResume().
For saving the data you can take a look at this example
SharedPreferences.Editor editor = getSharedPreferences("myPrefs", MODE_PRIVATE).edit();
editor.putString("username", "My name");
editor.apply();
And then retrience your data like this
SharedPreferences prefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
String username = prefs.getString("username", "No username"); //No username is the default value
I am currently new to android and am working on a note taker application so please be patient with me. Inside the menu, i implemented an option whereby the user can change view if desired (List or Grid).
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View customTitleView = inflater.inflate(R.layout.dialog_menu, null);
mListViewSelect = (LinearLayout) customTitleView.findViewById(R.id.list_select);
mGridViewSelect = (LinearLayout) customTitleView.findViewById(R.id.grid_select);
case R.id.changeView:
final AlertDialog alertbox = new AlertDialog.Builder(this).create();
alertbox.setCancelable(true);
alertbox.setView(customTitleView);
alertbox.show();
mListViewSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListNotes.setVisibility(View.VISIBLE);
mGridNotes.setVisibility(View.GONE);
alertbox.dismiss();
}
});
mGridViewSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListNotes.setVisibility(View.GONE);
mGridNotes.setVisibility(View.VISIBLE);
alertbox.dismiss();
}
});
}
return super.onOptionsItemSelected(item);
}
This works perfectly. However, i want the app to open in the selected view initially selected by user. For example, if the user had closed the app while in gridview, the app should open in gridview while restarted.
I understand i need to save data persistently with shared preferences or something. But i need to know exactly what i need to do.
If you want to save your data in Shared Preference, here is a way to do it.
First you need to create an instance of SharedPreferences and SharedPreferences.Editor:
private SharedPreferences settings = context.getSharedPreferences("*Desired preferences file", Context.MODE_PRIVATE);
*Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor
(SharedPreferences.edit()) and then commit changes (Editor.commit()).
private SharedPreferences.Editor editor = settings.edit();
If you need to save a String:
editor.putString(key, val).commit()
Don't forget to do the .commit();
To get The String from SharedPreferences:
String str = settings.getString(key, "");
Saving Int:
just use:
editor.putInt(key, val).commit();
and so on.
You are correct that you need to persist data, you have options though. You say it is a note taking app, where are you saving your notes?
You could store your application's state in share preferences, described in the the docs here. You could store the applications state, as well as all the notes in a database, such as a relational database, of which there a tons of tutorials on and the main docs can be found here, or alternatively a database such as Realm, which saves objects to the database.
I would research into these options, and implement one. Then, on application launch, check the 'application state' that you have saved and adjust the UI accordingly!
SharedPreferences mPrefs = getSharedPreferences("IDvalue",0);
if(mPrefs.contains("DATE")) {
//do something
}else {
mPrefs.edit().putString("DATE", currentdate);
mPrefs.edit().commit();
Toast.makeText(this, "changed", Toast.LENGTH_SHORT).show();
}
What i want the code to do is run the first time and show the toast but the second time it is run not show it and run the code inside the first parameters. But as it is now the code just runs the second "else" statement twice and doesn't even run the first. it's as if the string isn't even being put in "DATE"? Is there anything wrong with my code?
Make Editor Object and use it for edit/commit.
You can use below code. it will work fine.
SharedPreferences mPrefs = getSharedPreferences("IDvalue",0);
SharedPreferences.Editor mEditor = mPrefs.edit();
if(mPrefs.contains("DATE")) {
//do something
}else {
mEditor.putString("DATE", currentdate);
mEditor.commit();
Toast.makeText(this, "changed", Toast.LENGTH_SHORT).show();
}
I really confused to save my Switch statement so when the game reopen button that had been VISIBLE is Save, so I do some coding with SharedPreferences like this
f1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent level1 = new Intent ();
level1.setClassName ("com.example.game", "com.example.game.levelone");
startActivityForResult (level1, 0);
}
});
}
public void onActivityResult (int requestCode, int resultCode, Intent level1){
super.onActivityResult (requestCode, resultCode, level1);
f2=(Button)findViewById(R.id.f2);
f2lock=(ImageView)findViewById(R.id.f2lock);
SharedPreferences resultcode = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = resultCode.edit();
editor.putBoolean("IsFinished", true);
editor.commit();
boolean resultcode = preferences.getBoolean("IsFinished", true);
switch (resultCode) {
case 2: f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
}
There is the an error on different line
First in SharedPreferences.Editor editor = resultCode.edit();
I got this error Cannot invoke edit() on the primitive type int
Second, boolean resultcode = preferences.getBoolean("IsFinished", true);
I got two error like this
preferences cannot be resolved and Duplicate local variable
Can anyone help me to fix the code or giving another solution code to save the Switch Statement?
error no:1
There is a typo in your code. Notice the C in resultCode.edit()
Replace
SharedPreferences resultcode = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = resultCode.edit();
with
SharedPreferences resultcode = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = resultcode.edit();
Actually, in your code, it is resultcode which is the SharedPreference, but you was calling edit() on resultCode
error:2
I think you are trying to get a boolean value that is stored in the SharedPreference. For that, what you are doing is wrong.
It should be done as follows
boolean result = resultcode.getBoolean("IsFinished", true);
Actually, it is resultcode which refers to your SharedPreference in your Java class and not preferences. preferences is just a name given to the xml file that is saved in your local device.
Please take a look in the docs for more details about SharedPreferences.
As Lal said, you have a typo. Personally, I prefer one-liner SharedPreferences with the key String as a private static String at the top of the class.
The code below is derived from one of my projects.
private static final String KEY_ISFINISHED = "prefs_isfinished";
PreferenceManager.getDefaultSharedPreferences(context)
.edit().putBoolean(KEY_ISFINISHED, myboolean).commit();
Using this code, you minimize typos. Aside from code typos, a typo in the key will make sure your preference is never saved/retrieved correctly which is why I 'advocate' for the use of the static String. You will also notice from my link that all of my preferences are managed by a single class which means I do not have to repeat code in other classes to retrieve/store a particular preference. Generally speaking, less code == less chance of errors.
So I am trying to use SharedPreferences to pass a value from the Activity to a Class. The problem is the following:
On initial loading of the Activity, the value is stored in SharedPreferences but if I exit the Activity and return back, and try to update the value, the SharedPreferences does not seem to update and stays at the value of the initial load of the Activity.
Some class function
private void populatePlayerQueue(){
int category_index;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.getContext());
category_index = sharedPreferences.getInt("selected_category", 0);
}
Activity onResume
#Override
public void onResume() {
super.onResume();
int tmp = Integer.parseInt(getIntent().getStringExtra("CategoryIndex"));
//store the category in the shared preferences
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("selected_category", tmp);
editor.commit();
}
What I am trying to do:
I have to send an integer from the activity to a specific class and if I come back to the activity then I need to store the update value and so the class will be able to access the newly updated value again. I only have access to the context and not the activity. This causes errors if I try to create an interface callback to communicate with the activity. So this option is eliminated, hence I am trying anything I can to do that.
For some better result remove the SharedPreference through its key at the time of exit application.
In your case when you exit your application just clear the SharedPreference like:
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("selected_category"); //Just remove it by its specific key
editor.commit();
Then it will clearly load and save the new value again when you go back to your application on the same key or you can use new one.