I want to know how to take a simple string that is being saved in shared preferences but then save each one of those strings and display them into an array list. The user will save the string once a day. And I want the strings to display as an array list. Here's the code for what I'm working with. I have "physical_fragment.java"(SAVES THE DATA) & "MainActivity.java"(LOADS THE DATA).
PHSYICAL_FRAGMENT.JAVA
public void save(View view){
Date date = new Date();
String stringDate = DateFormat.getDateInstance().format(date);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences.edit();
editor.putString("result",String.format(stringDate, date) + " - " + text_view5.getText().toString());
editor.commit();
Toast.makeText(this, "Saved successfully!", Toast.LENGTH_LONG).show();
}
MAINACTIVITY.JAVA
resultPhysical= (TextView) findViewById(R.id.home);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String result= sharedPreferences.getString("result",DEFAULT);
if (result.equals(DEFAULT))
{
Toast.makeText(this, "No data found", Toast.LENGTH_LONG).show();
}
else
Toast.makeText(this, "Load Successful", Toast.LENGTH_LONG).show();
resultPhysical.setText(result);
}
I'd say use GSON for that.
To convert a list of strings to JSON to be stored in preferences you use this:
List<String> list = ...
Type type = new TypeToken<List<String>>(){}.getType();
String json = gson.toJson(list, type);
and store json in SharedPreferences using putString.
To read from SharedPreferences you use something like this:
String result = sharedPreferences.getString("result", DEFAULT);
Type type = new TypeToken<List<String>>(){}.getType();
List<String> list = gson.fromJson(result, type);
you can do as follows:
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences.edit();
ArratList<String> dataList;
String data = "";
for(String itemData:dataList){
data = itemData + String.format(stringDate, date) + " - " + text_view5.getText().toString()+ "/";
editor.putString(data);
}
editor.commit();
Now get the string from Shared preference and split it.
String result= sharedPreferences.getString("result",DEFAULT);
String[] splited = str.split("/");
This helps with out having support of Libraries which can effect size of apk file
Related
I'm new to android programming and I was wondering if it's possible to add more than one value in shared preferences at the same time. I have tried the following, but when I try to get the values I can see only the first one. The other value is getting the default value. Can you help me, please?
My code:
SharedPreferences.Editor editor = getSharedPreferences("prefs", Context.MODE_PRIVATE).edit();
String string1 = "myString1";
String string2 = "myString2";
editor.putString(string1, string2).apply();
SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
String string1FromSP = preferences.getString(string1, "default");
String string2FromSP = preferences.getString(string2, "default");
Log.e("Value 1", string1FromSP);
Log.e("Value 2", string2FromSP);
Values in Android SharedPreference gets stored like Key Value pair. And You are trying to store it all together like list or varargs.
So to save the values in Your example
SharedPreferences.Editor editor = getSharedPreferences("prefs", Context.MODE_PRIVATE).edit();
String string1 = "myString1";
String string2 = "myString2";
editor.putString("STRING_1", string1).apply();
editor.putString("STRING_2", string2).apply();
SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
String string1FromSP = preferences.getString("STRING_1", "default");
String string2FromSP = preferences.getString("STRING_2", "default");
Log.e("Value 1", string1FromSP);
Log.e("Value 2", string2FromSP);
I have two arrays, the first consists of 9 buttons. The second can hold 9 Strings. I have a method called getPlayerChoiceText to populate the String array with the text that is set on each button from the playerchoice Array. How can I save this text using SharedPreferences?
private String[] getPlayerChoiceText()
{
playerchoiceText[0] = playerchoice[0].getText().toString();
playerchoiceText[1] = playerchoice[1].getText().toString();
playerchoiceText[2] = playerchoice[2].getText().toString();
playerchoiceText[3] = playerchoice[3].getText().toString();
playerchoiceText[4] = playerchoice[4].getText().toString();
playerchoiceText[5] = playerchoice[5].getText().toString();
playerchoiceText[6] = playerchoice[6].getText().toString();
playerchoiceText[7] = playerchoice[7].getText().toString();
playerchoiceText[8] = playerchoice[8].getText().toString();
return playerchoiceText;
}
private void saveData()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
playerchoiceText = getPlayerChoiceText();
}
I have got the same problem. I solved it by using JSONArray.
JSONArray choices = new JSONArray();
choices.put("1");
choices.put("2");
choices.put("3");
// Save
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("choices", choices.toString());
// Retrieve
choices = new JSONArray(sharedPreferences.getString("choices", "[]"));
In this way, you can easily do Insert and Delete operations. I hope this helps.
Android's SharedPreferences operates as a key value store, and does not allow you to directly store Java objects. So, representing your player choice text values as a map would make more sense, if you want to store them using shared preferences.
There is one trick you might be able to use here, if you wanted to continue representing your choice texts as an array. You could store the texts using a delimiter, e.g. pipe:
String choices = String.join("|", playerchoiceText);
SharedPreferences prefs = getSharedPreferences(YOUR_PREFS_KEY, Context.MODE_PRIVATE);
prefs.edit().putString("choices", choices).apply();
And then, on the way out:
SharedPreferences prefs = getSharedPreferences(YOUR_PREFS_KEY, Context.MODE_PRIVATE);
String[] playerchoiceText = prefs.getString("choices", "").split("\\|");
Use put/getStringSet():
private void saveData()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
String[] playerchoiceText = getPlayerChoiceText();
editor.putStringSet("player_choice", new HashSet<T>(Arrays.asList(playerchoiceText));
editor.commit();
}
I want my app to check some web page only once a day, so I want the data to be saved anded reloaded upon starting the app again.
I followed this tutorial, but I can not save the result with MainActivity extends AppCompatActivity:
String url = "https://en.wikipedia.org/wiki/Main_Page";
SharedPreferences data;
SharedPreferences.Editor dataEditor;
String sDate = date.getString("date", "");
DateFormat df = new SimpleDateFormat("MMMM d");
String date = df.format(Calendar.getInstance().getTime());
if(sDate != date){ // <-- this does not work
new Date().execute();
}
and Date extends AsyncTask<Void, Void, Void>:
Document document = Jsoup.connect(url).get();
Elements date = document.select("div#mp-otd p b");
String sDate = date.getText();
dataEtitor.setString("date", sDate)
dataEtitor.commit;
The "Date extends AyncTask" class always start.
editor.commit() is used in order to save changes to shared preferences.
Add below line of code after setString
dataEtitor.commit(); // commit changes
SharedPreferences Example as follow
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
Storing Data
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Retrieving Data
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Clearing or Deleting Data
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
editor.clear();
editor.commit(); // commit changes
You muss use !(sDate.equals(date) in place of sDate != date, because the Strings are new and so they can not be compare each other.
I need help with my project. I need to be able to press a save button that uses shared preferences, and every time I press that button, I need it to take the saved data and stack it underneath each other like a list. The key value is "result". So the save button takes the string and integer and places it onto my Main activity XML layout. But, if I press save again with different integers or string it will replace the original string and integer I had originally saved. I want it to be able to keep the original string and integer if i save it for the first time and make a new string and integer underneath the original if i do a second time and so on forever. Please help!
This is under my saving activity:
public void save(View view){
Date date = new Date();
String stringDate = DateFormat.getDateInstance().format(date);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences.edit();
editor.putString("result",String.format(stringDate, date) + " - " + text_view5.getText().toString());
editor.commit();
Toast.makeText(this, "Saved successfully!", Toast.LENGTH_LONG).show();
}
This is under my loading activity:
resultPhysical = (TextView) findViewById(R.id.home);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String physicalresult = sharedPreferences.getString("result", DEFAULT);
String physicalresult2= sharedPreferences.getString("result2", DEFAULT);
if (physicalresult.equals(DEFAULT)){
Toast.makeText(this,"No Data Found", Toast.LENGTH_LONG).show();
}
else{
resultPhysical.setText(physicalresult);
}
}
You can easily save them, just create an extra variable that refers to the size of saved results so that you can loop over them. To start saving, get the size then save with the index
int size = sharedPreferences.getInt("size", 0); // if it doesn't exist, get 0
// then save the result like
editor.putString("result" + String.valueOf(size), String.format(stringDate, date) + " - " + text_view5.getText().toString()); // just add index to result
// then increase the size
editor.putInt("size", ++size);
editor.commit();
To load the results
StringBuilder results = new StringBuilder();
int size = int size = sharedPreferences.getInt("size", 0); // get the size to start looping
if(size == 0){ // if results are empty
// show toast there is no saved result
} else { //start looping
for(int i = 0; i < size; i++){
String temp = sharedPreferences.getString("result" + String.valueOf(i), DEFAULT);
results.append(temp + " ");
}
resultPhysical.setText(results.toString());
}
I need the inserted values in this edittext to show up after i quit the application. I currently have it set up so it'll set new default values if this is the first time for a user to set up the settings page but i can't get the set values to save and load the same values. Here is my code.
if (res.equals("555")) {
//post the saved text
} else if (res.equals("510")) {
editTextname.setText("Firstname Lastname", TextView.BufferType.EDITABLE);
editTextphone.setText("XXX-XXX-XXXX", TextView.BufferType.EDITABLE);
editTextemail.setText("name#yourdomain.com", TextView.BufferType.EDITABLE);
editTextaddress.setText("Street, City, State, Zip", TextView.BufferType.EDITABLE);
//save the entered text above and show it
}
Use SharedPreferences:
SharedPreferences prefs = getSharedPreferences("MyPreference", MODE_PRIVATE);
// On first run:
SharedPreferences.Editor editor = prefs.edit();
if(!prefs.contains("key1"))
editor.putString("key1", "defaultValue1");
if(!prefs.contains("key2"))
editor.putString("key2", "defaultValue2");
editor.commit();
// On save:
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key1", "value1");
editor.putString("key2", "value3");
editor.commit();
// On read:
String value1 = prefs.getString("key1");
String value2 = prefs.getString("key2");