How can I save to shredpreferences if arraylist is null? - java

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.

Related

How to return a JSONObject with a method using volley? (android studio)

I am making a weather app where I use a weather API and Volley to get the JsonObject with a request, then parse the values and display the values in textViews in another activity(screen).
I am now calling this method below in my MainActivity and using Intent to send the values to my displayInfo activity.
public void getInfoMethod(){
String finalUrl ="";
String cityName = searchBar.getText().toString().trim();
RequestQueue rQ = Volley.newRequestQueue(getApplicationContext());
//create a requestQueue to add our request into
finalUrl = leftApiUrl+cityName+rightApiUrl;
StringRequest sR = new StringRequest(Request.Method.POST, finalUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
result = "";
try {
JSONObject allJsonRes = new JSONObject(response);
String name = allJsonRes.getString("name");
double visibility = allJsonRes.getDouble("visibility");
int timeZone =allJsonRes.getInt("timezone");
//Creates a new JSONArray with values from the JSON string.
//try/catch are mandatory when creating JSONObject
//now we extract values from this JsonObject
JSONArray weatherJsonArr = allJsonRes.getJSONArray("weather");
//store []weather
//1.to get mainDescription and subDescription
//store the []weather part into weatherJsonArr
//inside this JsonArray,we store the only JsonObject as weatherBlock
//{}0
//then get different values from this subJsonObject
JSONObject weatherBlock = weatherJsonArr.getJSONObject(0);
//this includes id,main,description,icon
String mainDescription = weatherBlock.getString("main");
//get the string under key "main" e.g. "rain"
String subDescription = weatherBlock.getString("description");
//e.g."moderate rain"
JSONObject mainBlock = allJsonRes.getJSONObject("main");
//access {}main
double temp_in_C = mainBlock.getDouble("temp");
//get temperature from {}main
double temp_feel = mainBlock.getDouble("feels_like");
double temp_min = mainBlock.getDouble("temp_min");
double temp_max = mainBlock.getDouble("temp_max");
double pressure = mainBlock.getDouble("pressure");
double humidity = mainBlock.getDouble("humidity");
JSONObject windBlock = allJsonRes.getJSONObject("wind");
//get wind{}
double windSpeed = windBlock.getDouble("speed");
double degree = windBlock.getDouble("deg");
///
JSONObject sysBlock = allJsonRes.getJSONObject("sys");
String country = sysBlock.getString("country");
///
result += "Current weather in "+ name+", "+country+": "
+"\ntime zone: "+ timeZone
+"\nvisibility: "+ visibility
+"\nTemperature: "+Math.round(temp_in_C)+"°C"
+"\n"+mainDescription
+"\n("+subDescription+")"
+"\nWind speed : "+ windSpeed+" meters per minute"
+"\ndegree: "+degree
+"\ntemp feel:"+Math.round(temp_feel)+"°C"
+"\nmin: "+Math.round(temp_min)+"°C/"+"max"+Math.round(temp_max)+"°C"
+"\npressure: "+pressure
+"\nhumidity: "+humidity;
//then send these values to the displayInfo activity
//using Intent and putExtra
Intent i =new Intent(MainActivity.this,displayInfo.class);
i.putExtra("city",name);
i.putExtra("mainD",mainDescription);
i.putExtra("subD",subDescription);
i.putExtra("temp",temp_in_C);
i.putExtra("tempMax",temp_max);
i.putExtra("tempMin",temp_min);
i.putExtra("tempFeel",temp_feel);
i.putExtra("pressure",pressure);
i.putExtra("humidity",humidity);
i.putExtra("visibility",visibility);
i.putExtra("speed",windSpeed);
i.putExtra("deg",degree);
i.putExtra("timezone",timeZone);
startActivity(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error,check network or spelling",Toast.LENGTH_SHORT).show();
}//note that .show() is necessary for the message to show
});
rQ.add(sR);
//add the request into the queue,Volley will handle it and send it
//and then onResponse() or onErrorResponse() will run
//https://developer.android.com/training/volley/simple
}
It works fine by now, but the problem is, now I want to implement the observer pattern, get the JsonObject in my MainActivity(subject) and make the observers(displayInfo.class for now) to get the latest JsonObject from subject, so I need a method that could return the JSONObject in the MainAvtivity, what should I do to implement this method for observer pattern?
(not using inbuilt Observer interface)
Firstly I suggest putting your getInfoMethod() in a helper class. This will allow for easier re-usability.
Next, I wouldn't gather your result in your first activity. Instead, I would build the URL like you are. Then create an Intent to your second activity and pass the URL as a string with i.putExtra(finalUrl.toString).
In your second activity, have a loading spinner visible, that gets set to 'gone' at the end of processing your result. If an error occurs you can always call finish() to send you back to your first activity.
Optionally you could create a POJO for the results and use Jackson to map the results to an object. It'll be easier to pass the one object around instead of working with every little bit of a JSONObject. JSONObjects are fine, but once you have the data the way you want it, you should map it to a class if you are expecting to work with the object for any length of time.

SharedPreferences editor not executing

In the following piece of code, one of the mEditor lines, doesn't appear to execute.
I've tried many different combinations so far, but can't get it to execute properly. The value is not set at all.
If i try to use the value, like in a Toast, I will receive a ResourcesNotFound Exception
Initialization of SharedPreference in my onCreateView, Fragment
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
mEditor = mSharedPreferences.edit();
public void onClick(View view) {
int round_number = mSharedPreferences.getInt(getString(R.string.pref_round_played),0);
if (round_number == 0){
game_team.setBackgroundResource(R.drawable.t);
game_team.setVisibility(View.VISIBLE);
knap_bund.setVisibility(View.INVISIBLE);
knap_top.setText("Next Strat");
mEditor.putString(getString(R.string.pref_chosen_team), "T");
mEditor.putInt(getString(R.string.pref_round_played),round_number + 1);
mEditor.apply();
//Show CT side Pistol round here//
}
Following code is used in my onClick, which has other sharedPreferences, working the exact same way, which executes fine.
The first line executes just fine, but the second line containing 'putInt' isn't executing as intended.
mEditor.putString(getString(R.string.pref_chosen_team), "T");
mEditor.putInt(getString(R.string.pref_round_played), 1);
mEditor.apply();
Example of working code:
else if(round_number <= 30){
mEditor.putInt(getString(R.string.pref_round_played),round_number + 1);
mEditor.apply();
}
UPDATE
Just to clarify due to the comments. It's only this one occasion where the sharedPreferences won't work. I use it about 15 other places in this fragment, with no issues at all
I will receive a ResourcesNotFound Exception
I think R.string.pref_round_played is not exist,check it for your strings.xml
you're not posted for your detailed code so do it like this below to save values in shared preference
public static final String PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME , MODE_PRIVATE).edit();
editor.putString("name", "john");
editor.putInt("id", 123);
editor.apply();
Retrieve the data from shared preference
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", ""); // you can put default value if you need
int idName = prefs.getInt("id", 0);
if this is not works for you please post your full code
Update
change your code to this one
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor mEditor = mSharedPreferences .edit();

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();

What I missing when tried to retrieve data from Shared Preferences

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();
}
}

Categories

Resources