I was trying to use Save/Load Preferences to save the User's input through EditView. However, my current code only saves the last string the user inputted. So when i re-enter the app, the only string in the ListView is the last string the user entered.
How can i fix this?
EDITED CODE BELOW:
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String task = display.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
JSONArray array = new JSONArray();
array.add(task);
SavePreferences("LISTS", array.toString());
}
});
}
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = data.edit();
editor.putString("LISTS", value);
editor.commit();
}
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("LISTS", "");
adapter.add(dataSet);
adapter.notifyDataSetChanged();
ArrayList<String> dataSetarrlist = new ArrayList<String>();
dataSetarrlist.add(dataSet);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,dataSetarrlist);
lv.setAdapter(adapter);
Aren't you overwriting the same key?
SavePreferences("LISTS", task);
in
editor.putString(key, value);
It will always write on key "LISTS" of the SharedPreferences, overwriting the previous value.
You should try to get the current saved values to a string and append the new value.
Sort of:
String dataset = loadPreferences();
SavePreferences("LISTS",dataset+task);
Depending on the desired save format.
-- Example --
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
JSONArray array = new JSONArray(data.getString(key,"");
SharedPreferences.Editor editor = data.edit();
editor.putString(key, value);
editor.commit();
}
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
JSONArray dataSet = new JSONArray(data.getString("LISTS", "None Available");)
for(int i = 0; i<dataSet.length; i++)
adapter.add(dataSet.getString(i);
adapter.notifyDataSetChanged(); // You don't need this if you aren't overriding the Adapters 'add' method.
}
Your problem is that you are writing on the same key "LISTS" and it will take always the last value. You should use different keys or just get the previous value from "LISTS" key, add a separator character and append the new preferences. Then in your LoadPReferences use String.split(pattern) to get all the values.
Related
In my app, I am trying to save a key value as zero or one depending on whether a checkbox is checked. I retrieve these values in a different activity. However, when I attempt to retrieve the value, I am getting an empty string:
Saving key values in Activity 1(ScienceCoursesCheck):
public void setDefaults(String key, String value) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, value);
editor.commit();
}
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkBox_APBio:
if (checked) {
setDefaults("APBio", "1");
}
else {
setDefaults("APBio", "0");
break;
}
}}
Retrieving key values in activity 2(MyHome):
public static String getDefaults(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
public void myMethod() {
SharedPreferences myPrefs = getSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE);
String APBio = myPrefs.getString("APBio","");
if (APBio.equals("1")){
Button myButton = new Button(this);
myButton.setText(APBio);
RelativeLayout ll = (RelativeLayout)findViewById(R.id.activity_my_home);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
}
}
Is the second activity accessing the correct SharedPreferences file?
Use the following code for sharedpreference. Call
Util.saveInfo(activityContext,_key,_value)
when you want to save the info. Then call
Util.getInfo(getApplicationContext(),_key)
to get the info.
public class Util{
public static void saveInfo(Context context, String key, String value )
{
try
{
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, value).apply();
}
catch (Exception ex)
{
Log.e(TAG," saveInfo "+ex+"");
}
}
public static String getInfo(Context context, String key)
{
try {
return PreferenceManager.getDefaultSharedPreferences(context).getString(key,"");
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
The issue is because when you store the items in SharedPreferences you are using
PreferenceManager.getDefaultSharedPreferences
but when you retrieve them you are using
getSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE);
These are two different SharedPreferences files. Try using getSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE); for your setting method as well. Or perhaps you meant to use your getDefaults() method in activity 2 instead of myPrefs
That is because you are saving in the DefaultSharedPreferences file
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
and retrieving from another file named "ScienceCoursesCheck"
SharedPreferences myPrefs = getSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE);
and they are not the same file!
See the difference between getSharedPreferences and getDefaultSharedPreferences in this answer
====
Solution is either to always use DefaultSharedPreferences OR always use the file named "ScienceCoursesCheck" .
The problem is you're saving the values in the DefaultSharedPreference and trying to retrieve the values from the ScienceCoursesCheck preference file.
Try below code for setDefaults method.The getDefaultSharedPreference and getSharedPreference methods are different.
See this link for the difference.
public void setDefaults(String key, String value) {
SharedPreferences sharedPref = getApplicationContext().getDefaultSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, value);
editor.commit();
}
Hope this helps you...
I use this code to save String value in SharedPreference , But returns empty String! I tried very hard and spend long time, But I can't understand why?
sp=getSharedPreferences("sp", Activity.MODE_PRIVATE);
bshare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
sp.edit().putString("a","ali");
sp.edit().commit();
Log.i("sp","z"+sp.getString("a","");
}
});
Try this way:
SharedPreferences sp = this.getSharedPreferences("sp", Activity.MODE_PRIVATE);
SharedPreferences.Editor aa = sp.edit();
Set<String> myStrings = settings.getStringSet("myStrings", new HashSet<String>());
// Add the new value.
myStrings.add("Another string");
// Save the list.
aa.putStringSet("myStrings", myStrings);
aa.commit();
I have try to set and store the password for my apps, but it is not working at all. The password should be setted first time then return the home page, then when the user open it again the password should be stored but somehow it didn't store it.
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences passfile = getSharedPreferences("ans",0);
String pass = passfile.getString("ans", null);
check.setOnClickListener(new OnClickListener () {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String answer1 = answer.getText().toString();
//Check that user typed in an answer
if(answer1.length()<8){
Toast.makeText(CheckPwActivity.this, "Answer must be 8 characters long", Toast.LENGTH_SHORT).show();
answer.setText("");
answer.requestFocus();
return;
}
answer.getEditableText().toString();
//check if the answer is valid
if (answer1.equals("ans")) {
Intent intent2 = new Intent(CheckPwActivity.this,MainActivity.class);
startActivity(intent2);
}else{
return;
}
}});
}
public void setPassword(String key, String value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
Editor preferenceEditor = context.getSharedPreferences("password", 8).edit();
preferenceEditor.putString(key, value);
preferenceEditor.commit();
}
public static String getPassword(String filename) {
return context.getSharedPreferences("password", 2).getString(filename,"");
}
you are using shared preferences wrong, in your set password you get shared preferences but then you get it again but in a different context
this is all you need to use shared preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
then when you want to set it you use the editor you just got
editor.putString(key,pass).commit;
then to get it from shared preferences you would just do
preferences.getString(key,defaultString);
I have a bundle passed from one activity to another. That contains String n (the length is max 30), String ID and String color. I need to save these values to an ArrayList as an array (n, ID, color) and then to save ArrayList to androids memory. I was looking for a best way of doing that.. I've tried database but its to complicated for me at the moment and I don't think I need such a complex thing. I've tried FileOutputStream (as it explained here: http://developer.android.com/guide/topics/data/data-storage.html#pref?) but it's not working for me, probably because I'm doing something wrong. Do I actually need to create an arraylist of arrays or may be i could use arraylist of bundles, or any other way..? Whats the best way...? Please help..
Thanks every one...Was trying all this time but no luck.. I'm posting the code hoping that someone could give me a hand on that:
public class MainActivity extends Activity
{
String gotNotes;
String n;
String gotDOW;
String gotID;
public String clrs;
public String id;
public String nts;
String gotHour;
String gotColor;
TextView notes;
public static String FILENAME = "allevents";
String[] newevent;
String[] events;
SharedPreferences sharedPref;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button settings = (Button)findViewById(R.id.settings);
Bundle gotPackage = getIntent().getExtras();
if (gotPackage != null){
gotNotes = gotPackage.getString("AddedNote");
if (gotNotes.equals(" "))
{
n = "Empty";
}
else
{
n = gotNotes;
}
//gotDOW = gotPackage.getString("Day");
//gotHour = gotPackage.getInt("Hour");
gotID = gotPackage.getString("ID");
gotColor = gotPackage.getString("color");
initialize();
}
else{}
settings.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(v.getContext(),Settings.class);
startActivityForResult(i,0);
}
});
}
private void initialize()
{
// TODO Auto-generated method stub
String[] newevent = {n, gotID, gotColor};
ArrayList<String[]> events = new ArrayList<String[]>();
events.add(newevent);
SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("yourKey", events.toString());
editor.commit();
String allData = sharedPref.getString("yourKey", null);
String[] playlists = allData.split(",");
/* for (int number=0;number<events.lastIndexOf(sharedPref);number++)
{
notes = (TextView)findViewById(getResources().getIdentifier(playlists[number], getString(0), allData));
notes.setText(number+1);
}*/
notes = (TextView)findViewById(getResources().getIdentifier(gotID, "id",getPackageName()));
notes.setText(n);
notes.setGravity(Gravity.CENTER_HORIZONTAL);
notes.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
if (gotColor.equals("Blue")){
notes.setBackgroundColor(Color.rgb(99, 184, 255));}else
if(gotColor.equals("Green")){
notes.setBackgroundColor(Color.rgb(189, 252, 201));}else
if(gotColor.equals("Yellow")){
notes.setBackgroundColor(Color.rgb(238, 233, 191));}else
if(gotColor.equals("Grey")){
notes.setBackgroundColor(Color.LTGRAY);}else
if(gotColor.equals("Aqua")){
notes.setBackgroundColor(Color.rgb(151, 255, 255));}else
if(gotColor.equals("White")){}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Simply use SharedPreferences to save your application's data.
SharedPreferences sharedPref = activity.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = activity.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("yourKey", yourArray.toString());
editor.commit();
To get your array as String do the following:
String arrayString = sharedPref.getString("yourKey", null);
You can save array into shared preferences and retrieve it back. Here is a good example with fully functional code.
Hi I'm trying to save a user preference from a list view i'm wanting it to store what the selected and then when the app loads up again checks for the preference chosen method if it = team then do something but at the moment its not loading in preferences any ideas as to what i'm doing wrong. when i log out chosen Method it says null
heres my code
preferences.edit().putString("ChosenMethod", "Team").commit();
preferences.edit().putString("ChosenTeam", ChosenTeam).commit();
preferences.edit().putString("ChosenTeamId", ChosenTeam).commit();
preferences.edit().putString("ChosenLeagueId", ChosenTeam).commit();
preferences.edit().putString("ChosenDivisionID", ChosenTeam).commit();
then in the introActivity I've put this this
protected void checkPreferences(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Log.v("myapp", "prefs = " + preferences);
String ChosenMethod = preferences.getString("ChosenTeam", chosenMethod);
Log.v("myapp", "ChosenMethod = " + ChosenMethod);
if (ChosenMethod != null){
Intent intent = new Intent(TheEvoStikLeagueActivity.this,Activity.class);
}
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
checkPreferences();
//Retrive value from SharedPreference
public static String getStringFromSP(String key) {
// TODO Auto-generated method stub
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
return preferences.getString(key, null);
}//getPWDFromSP()
you can use the above code get value from SharedPreference.
Refer this LINK