What I missing when tried to retrieve data from Shared Preferences - java

Hey guyz check it out what I am missing here cause of I am not able to fetch all my data from Shared Preferences.
I am making such an tasklist application in which I am saving my data(means mytask) with a certain key and storing it in the shared Preferences and increments a variable for total count.
Check my Code(Whenever I click on addTask button the following code gets executed).
private void saveToSharedPreference(){
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
editor = sharedPre.edit();
String myKey = "key"+a;
String myValue = et.getText().toString();
editor.putString(myKey,myValue);
// editor.putInt("totalTask", a);
editor.commit();
}
Now when I close the application and open it again the following code gets executed in order to load the data from shared preferences.
private void loadData(){
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
int p = 1;
String myKey = "key"+p;
while(sharedPre.getString(myKey,"") != null){
Toast.makeText(this, sharedPre.getString(myKey,""),Toast.LENGTH_SHORT).show();
}
}
but the problem is all it always returning null on all indexes. I don't know why I am getting this error. Please help me
Thanks in advance
Sarosh Madara

to load all saved values just use the following code:
private void loadData() {
SharedPreferences sharedPre = getSharedPreferences("todoPref",android.content.Context.MODE_PRIVATE);
Map<String,?> keys = sharedPre.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
if (entry.getValue().toString().length() > 0) {
Log.d("map values",entry.getKey() + ": " + entry.getValue().toString());
}
}
}
I found it here but added a check to ignore null values.
to save values to Shared Preference I suggest using an instance of the current time for the key. no need to save any integer key values:
private void saveToSharedPreference(String myValue){
SharedPreferences sharedPre = getSharedPreferences("todoPref",android.content.Context.MODE_PRIVATE);
Editor editor = sharedPre.edit();
String key = String.valueOf(Calendar.getInstance().getTimeInMillis());
editor.putString(key,myValue);
editor.commit();
}
so whenever you want to add values to Shared Preferences use:
saveToSharedPreference("myValue");
and to load them all use:
loadData();
The Map Interface
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. read more...
SharedPreferences: Class Overview

Do like this -
1) save in shared preference like this -
private void saveToSharedPreference(){
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
editor = sharedPre.edit();
String myKey = "key"; // removed +a
String myValue = et.getText().toString();
editor.putString(myKey,myValue);
// editor.putInt("totalTask", a);
editor.commit();
}
2) load it like this -
private void loadData() {
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
int p = 1;
String myKey = "key"; // removed "+p"
String value = sharedPre.getString(myKey, "");
}

Don't compare with != null in while loop. Use below code and see if the problem solves:-
private void loadData(){
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
int p = 1;
String myKey = "key"+p;
String value = sharedPre.getString(myKey,"");
if(!value.equalsIgnoreCase("")){
Toast.makeText(this, sharedPre.getString(myKey,""),Toast.LENGTH_SHORT).show();
}
}

Related

How can I save to shredpreferences if arraylist is null?

Every time my Android app starts I get an arraylist, MatchingArrayList, from my server:
try {
JSONArray Object = new JSONArray(MatchingAsString);
//for every object in the Array
for (int x = 0; x < Object.length(); x++) {
final JSONObject obj = Object.getJSONObject(x);
MatchingArrayList.add(obj.getString("usernameMatch"));
}
It looks something like this: [+111, +222]
Then I save the arraylist to sharedpreferences like this:
SharedPreferences sharedPreferencesMAL = PreferenceManager.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor editorMAL = sharedPreferencesMAL.edit();
Gson gsonMAL = new Gson();
String jsonMAL = gsonMAL.toJson(MatchingArrayList);
editorMAL.putString("MatchingArrayList", jsonMAL);
editorMAL.commit();
So the next time the app is used, if MatchingArrayList has changed to [+111, +222, +333], for instance, it will overwrite the last used arraylist of [+111, +222]
It works well except if MatchingArrayList is null or is empty. The sharedpreferences don't update. I tried:
if (MatchingArrayList == null) {
SharedPreferences sharedPreferencesMAL = PreferenceManager.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor editorMAL = sharedPreferencesMAL.edit();
editorMAL.putString("MatchingArrayList", null);
editorMAL.commit();
} else {
//save MatchingArrayList into sharedpreferences so we can use it elsewhere
SharedPreferences sharedPreferencesMAL = PreferenceManager.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor editorMAL = sharedPreferencesMAL.edit();
Gson gsonMAL = new Gson();
String jsonMAL = gsonMAL.toJson(MatchingArrayList);
editorMAL.putString("MatchingArrayList", jsonMAL);
editorMAL.commit();
}
But still the last arraylist is being used. How can I fix this?
Instead of looking at my java arraylist I checked my response for being empty on the php side from my app. Like this:
if (response.isEmpty()) {
SharedPreferences sharedPreferencesMatchingContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor editorMatchingContactsAsArrayList = sharedPreferencesMatchingContactsAsArrayList.edit();
editorMatchingContactsAsArrayList.putString("MatchingContactsAsArrayList", "");
editorMatchingContactsAsArrayList.commit();
} else {
That fixed my problem, updated the sharedpreferences.

Java Android How To Save Multiple CheckBox To String If Checked and Store To SharedPref and Retrieve It As A String

So I have 2 screen one to store the other to retrieve. What I want ultimately is storing the checked checkbox into sharedPref, retrieve it as a STRING and put it inside an ArrayList to shuffle for a random STRING that was SELECTED.
So far I tried many solutions but none worked. I always get the unchecked checkbox as well. I only want checked even if I just select ONE of the checkbox. Any advise would be appreciated.
EDIT: I have solve the problem...at least for now. Look at the UpdateReceive.java to see the solution. But however for other screens I will have 9 Checkboxes and the possibilities are too tedious to do it this way. So are there any better methods out there?
Storing.java
SharedPreferences sharedMode = getSharedPreferences("MySharedMode", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedMode.edit();
editor.clear();
editor.commit();
if ( cbCool.isChecked() || cbHeat.isChecked()) {
editor.putBoolean("Cool", cbCool.isChecked());
editor.putBoolean("Heat", cbHeat.isChecked());
editor.commit();
}
Receieve.java
SharedPreferences sharedMode = getSharedPreferences("MySharedMode", Context.MODE_PRIVATE);
String heat = String.valueOf(sharedMode.getBoolean("Heat", false));
String cool = String.valueOf(sharedMode.getBoolean("Cool", false));
if (heat != null && cool != null) {
String m_heat = "Heat";
String m_cool = "Cool";
List<String> list = new ArrayList<String>();
list.add(m_heat);
list.add(m_cool);
Collections.shuffle(list);
String randMode = list.get(0);
tvMode.setText(randMode);
}
UpdatedReceive.java
if (heat == "true" && cool != "true") {
tvMode.setText("Heat");
}
else if (heat != "true" && cool == "true") {
tvMode.setText("Cool");
}
else if (heat =="true" && cool == "true") {
String m_heat = "Heat";
String m_cool = "Cool";
List<String> list = new ArrayList<String>();
list.add(m_heat);
list.add(m_cool);
Collections.shuffle(list);
String randMode = list.get(0);
tvMode.setText(randMode);
}

Saving a String value with SharedPreferences but for some reason it is not getting saved or due to other issue

I'm trying to save marker with Latlng and two strings with SharedPreferences and i'm doing a for loop to retrieve it when the activity is lunched again i had another question before because i couldn't delete the marker from the SharedPreferences So my mind is so missed up i can't figure it out what is the issue now please check the code below and any suggestions that could help i appreciated
I'm Using the et String so i match it to Marker title and on Marker Click i delete the Marker from sharedPreferences according to its title and already initilized the SharedPreferences in onCreated Method like so SharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
So I save the values like this,
int Int,cycler,IncreaseAmount;
String testSample;
private static final String StringLat= "Latitude",StringLng="Longitude",StringDis="Dis",StringName="Name";
String SinputNames = inputName.getText().toString();
Sinputdiscription = inputdiscription.getText().toString();
dLatitude = AddedLatLng.latitude;
dLongitude = AddedLatLng.longitude;
SharedPreferences.Editor editor = SharedPrefs.edit();
IncreaseAmount++;
editor.putInt("IJSS",IncreaseAmount);
IncreaseAmount = SharedPrefs.getInt("IJSS",0);
//SJSS = SinputNames;
//SJSS = Double.toString(dLatitude);
editor.putString("ErrorTest","Pulling up the info is working");
editor.putLong(SJSS+StringLat,Double.doubleToLongBits(dLatitude));
editor.putLong(SJSS+StringLng,Double.doubleToLongBits(dLongitude));
editor.putString(SJSS+StringName,SinputNames);
editor.putString(SJSS+StringDis,Sinputdiscription);
// editor.putString("lat"+ Integer.toString((IntCoords)), Double.toString(point.latitude));
editor.putString("ForLooper"+Integer.toString((IncreaseAmount)),SinputNames);
editor.apply();
and then pull it off from sharedPreferences
String CheckErrortest = SharedPrefs.getString("ErrorTest","Not working!");
Log.i("AlertSinput:",CheckErrortest);
cycler = SharedPrefs.getInt("IJSS",0);
if(cycler !=0) {
String Name="";
double Lat321,Lng321;
// Log.i("ifCycler","if Cycler != 0 is working");
Int = SharedPrefs.getInt("IJSS",0) +1;
for(int i=0; i< Int ; i++ ) {
Log.i("ForLoop:","The for loop is also working");
// editor.putString("ForLooper"+Integer.toString((IncreaseAmount)),SJSS+StringLat);
//Here i can't pull up the info
String iCheck = SharedPrefs.getString("Forlooper"+Integer.toString((Int)),"");
Log.i("TheMarkerName:","Should be"+iCheck);
Name = SharedPrefs.getString(iCheck+StringName,"Marker");
Lat321 = Double.longBitsToDouble(SharedPrefs.getLong(iCheck+StringLat,0));
Lng321 = Double.longBitsToDouble(SharedPrefs.getLong(iCheck+StringLng,0));
Log.i("Markertitle:#",Name);
Log.i("TestTheInteger:#",Integer.toString((Int)));
if(Lat321 !=0) {
AddedLatLng = new LatLng(Lat321,Lng321);
drawMarker(AddedLatLng,Name);
}
}
}
So the CheckErrortest and Log.i("ForLoop:","The for loop is also working");
are working Just fine but the String String iCheck = SharedPrefs.getString("Forlooper"+Integer.toString((Int)),"");
Is not working when i pull up the info for some reason and i couldn't figure out what is the issue anything that could help is appreciated thank you very much
I don't see you're commiting your changes. You need to do
editor.apply();
or
editor.commit();
All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()
You need to apply your changes after work with editor.
editor.commit();
or
editor.apply();

Android using SharedPreferences

I found out a common way to store data is Android's SharedPreferences. So I went out and tried to implement it with my application.
What I want to do:
My application retrieves weather details from the users current location, if the user desires he/she can add the location by pressing add to favorites. They can have up to 10 favorite locations. So I want to store the location description (exp: Dayton, OH), the latitude and longitude (So I may fetch the details when they want to see that weather). So Shared Preferences seem to fit my need.
What I did:
- I created a loop that would cycle through 10 keys (for 10 locations) an as long as the keys were null the location information would be saved. If the key was not null, it means the key has already been created.
My code:
public void writeNewLocation(String stringLat, String stringLon, String location) {
this.latitude = stringLat;
this.longitude = stringLon;
this.location = location;
pref = mContext.getSharedPreferences("favoritelocations", 0); // 0 - for private mode
Editor editor = pref.edit();
//Loop through all the favorite keys to find an open spot:
for(int i = 1; i <= 10; i++) {
//Test for current favorite key:
String value = pref.getString("favorite"+ i +"_location",null);
if (value == null) {
//The key does not exist so it can be created and written to:
//First write the location description:
editor.putString("favorite" + i + "_location", location);
//Next the write the latitude and lonitude values:
editor.putString("favorite" + i + "_latitude", latitude);
editor.putString("favorite" + i + "_longitude", longitude);
editor.commit();
i = 11;
} else {
//If at end of loop; Inform user:
if(i == 10) {
//Display an error:
//Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
//Create the AlertDialog characteristics:
builder.setMessage("You can only have up to 10 favorite locations. Delete some to make room.");
builder.setTitle("Message");
//Show the AlertDialog:
msgDialog = builder.create();
editor.commit();
i = 11;
} else {
//Back to top of loop.
}
}
}
//Commit to changes:
editor.commit(); // commit changes
}
So I loop through ten possible keys, if it hits 10, and all spots are taken, I alert the user. But when I call this method to create a favorite location, then call 1 of the 10 getters to display the information that should've been saved, I get a null. :( Is it too early in the morning over here or am I doing something wrong...
Thanks c:

Dynamically Read Properties file and draw Text boxes in javascript

I have a properties file with all the fields. dynamically I need to draw the text box with fields as read from the properties file and enter values and post it to controller in spring - java !
Example Properties File
name=String
age=int
address=string
How can I do this from java code..
For my idea, I will do it as below:
Using ajax to get fields from property file on server and return a list of field and type of field in a json format (key, value).
Now we have the data of those fields, then we generate them to your form using jquery or javascript.
Submit the form to server to get value.
Step 1 and 2 are quite easy, so I do not post the code; for step 3, you can try the method below to parse the params in query string to a map.
public static Map getMapFromQueryString(String queryString) {
Map returnMap = new HashMap();
StringTokenizer stringTokenizer = new StringTokenizer(queryString, "&");
while (stringTokenizer.hasMoreTokens()) {
String key, value;
String keyAndValue = stringTokenizer.nextToken();
int indexOfEqual = keyAndValue.indexOf("=");
if (indexOfEqual >= 0) {
key = keyAndValue.substring(0, indexOfEqual);
if ((indexOfEqual + 1) < keyAndValue.length()) {
value = keyAndValue.substring(indexOfEqual + 1);
} else {
value = "";
}
} else {
key = keyAndValue;
value = "";
}
if (key.length() > 0) returnMap.put(key, value);
}
return returnMap;
}
Now you can get all the value of dynamic fields on the form.
Hope this solution is helpful for you.

Categories

Resources