Android - SharedPreference.getBoolean retrieving false even if i am storing true? - android

I am using SharedPreference to store the state of checkboxes but even i am storing true in it , its still retrieving false.
Here is my code -
#Override
public void onPause()
{
super.onPause();
saveState();
}
#Override
public void onResume()
{
super.onResume();
loadState();
}
#Override
public void onRestart()
{
super.onRestart();
loadState();
}
public void saveState()
{
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
for(int i = 0; i < itemCheck.length; i++)
{
Boolean b = itemCheck[i];
Log.e(TAG, b.toString());
editor.putBoolean(i+"", itemCheck[i]);
}
}
public void loadState()
{
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
for(int i = 0; i < itemCheck.length; i++)
{
itemCheck[i] = sp.getBoolean(i+"", false);
Boolean b = itemCheck[i];
Log.e(TAG, b.toString());
}
for(int i = 0; i < itemCheck.length; i++)
{
lv.setItemChecked(i, itemCheck[i]);
}
}
Its giving me false because i set false as a default value in getBoolean which should be returned in the absence of predefined key. Please take a look and tell me what i did wrong. Thanks

You never call commit() on your editor I think :)
Try this:
public void saveState()
{
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
for(int i = 0; i < itemCheck.length; i++)
{
Boolean b = itemCheck[i];
Log.e(TAG, b.toString());
editor.putBoolean(i+"", itemCheck[i]);
}
editor.commit();
}

use editor.commit() after editor.putBoolean(i+"", itemCheck[i]);

Related

Android Getting a Set from SharedPrefs is corrupting the order

I have a method like this:
public static void setSearchHistory(Activity activity, int channelId) {
SharedPreferences sp = getSharedPreferences(activity);
SharedPreferences.Editor prefsEditor = sp.edit();
Set<String> searchHistory = sp.getStringSet("searchHistory", new LinkedHashSet<String>());
List<String> shList = new ArrayList<>();
shList.addAll(searchHistory);
if(shList.size() > 0) {
boolean wasAdded = false;
for(int i=0;i<shList.size();i++) {
Integer channelID = Integer.parseInt(shList.get(i));
if(channelId == channelID) {
shList.remove(i);
shList.add(0, String.valueOf(channelId));
wasAdded = true;
break;
}
}
if(!wasAdded) {
shList.add(0, String.valueOf(channelId));
}
} else {
shList.add(String.valueOf(channelId));
}
if(shList.size() > 10) {
for(int i=10;i<shList.size();i++) {
shList.remove(i);
}
}
searchHistory = new LinkedHashSet<>(shList);
prefsEditor.putStringSet("searchHistory", searchHistory);
prefsEditor.apply();
}
This method does get channelId param and add it in the first position of the Set and save back to SharedPreferences. It also controls if channelId is already in the list. If so, it removes channelId from current position and adds it in the first position. Then it removes last items until its size is 10.
I put the List back to Set, the order of the list is right. I also took screenshot for them:
The Set after the List added to it:
But when I get the Set back from SharedPreferences like below, the order of the list is mixed-up very randomly.
SharedPreferences sp = getSharedPreferences(activity);
Set<String> searchHistory = sp.getStringSet("searchHistory", new LinkedHashSet<String>());
List<String> shList = new ArrayList<>();
shList.addAll(searchHistory);
The Set after saved to SharedPreferences:
This is really annoying, I don't want it to mix up the order. :(
Any help will be appreciated. Thanks.
I found a workaround from another question: here
I totally removed Setobjects and replace them with JSONArray saving into SharedPrefs just String as follows;
Putting List into SharedPrefs:
public static void setSearchHistory(Activity activity, int channelId) {
try {
SharedPreferences sp = getSharedPreferences(activity);
SharedPreferences.Editor prefsEditor = sp.edit();
JSONArray searchHistory;
List<String> shList = new ArrayList<>();
if(sp.getString("searchHistory", null) != null) {
searchHistory = new JSONArray(sp.getString("searchHistory", null));
for(int i=0;i<searchHistory.length();i++) {
shList.add(searchHistory.get(i).toString());
}
}
if(shList.size() > 0) {
boolean wasAdded = false;
for(int i=0;i<shList.size();i++) {
Integer channelID = Integer.parseInt(shList.get(i));
if(channelId == channelID) {
shList.remove(i);
shList.add(0, String.valueOf(channelId));
wasAdded = true;
break;
}
}
if(!wasAdded) {
shList.add(0, String.valueOf(channelId));
}
} else {
shList.add(String.valueOf(channelId));
}
if(shList.size() > 10) {
for(int i=10;i<shList.size();i++) {
shList.remove(i);
}
}
searchHistory = new JSONArray(shList);
prefsEditor.putString("searchHistory", searchHistory.toString());
prefsEditor.apply();
} catch (JSONException e) {
e.printStackTrace();
}
}
And getting List from SharedPrefs:
public static List<Channel> getSearchHistory(Activity activity) {
try {
SharedPreferences sp = getSharedPreferences(activity);
List<String> shList = new ArrayList<>();
if(sp.getString("searchHistory", null) != null) {
JSONArray searchHistory = new JSONArray(sp.getString("searchHistory", null));
for(int i=0;i<searchHistory.length();i++) {
shList.add(searchHistory.get(i).toString());
}
}
List<Channel> channelList = new ArrayList<>();
for(int i=0;i<shList.size();i++) {
Channel channel = Channel.findChannelByID(Integer.parseInt(shList.get(i)), activity);
channelList.add(channel);
}
return channelList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
Works like a charm. Yay!

Cant save string with shared preferences

I have two strings that I want to save them I wrote the code as shown below
public class MainActivity extends Activity {
Button result;
EditText b951, b9511, sum95, t95, p95
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LoadPreferences();
result = (Button)findViewById(R.id.btn1);
b951 = (EditText)findViewById(R.id.b951);
b9511 = (EditText)findViewById(R.id.b9511);
sum95 = (EditText)findViewById(R.id.sum95);
p95 = (EditText)findViewById(R.id.p95);
t95 = (EditText)findViewById(R.id.t95);
}
public void close (View v){
SavePreferences("p2b951", b951.getText().toString());
SavePreferences("p2b9511", b9511.getText().toString());
finish();
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String p1b951 = sharedPreferences.getString("p2b951", "1");
String p1b9511 = sharedPreferences.getString("p2b9511", "1");
b951.setText(p1b951);
b9511.setText(p1b9511);
}
public void result (View v) {
try {
int ib951 = Integer.parseInt(b951.getText().toString());
int ib9511 = Integer.parseInt(b9511.getText().toString());
int iisum95 = (ib9511-ib951);
sum95.setText(String.valueOf(iisum95));
int isum95 = Integer.parseInt(sum95.getText().toString());
int ip95 = Integer.parseInt(p95.getText().toString());
int pp95 = (isum95*ip95);
t95.setText(String.valueOf(pp95));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
But it seems there is a problem with this two lines:
b951.setText(p1b951);
b9511.setText(p1b9511);
I tried this
b951.setText(String.valueOf.p1b951);
b9511.setText(String.valueOf.p1b9511);
Also the problems still exist
When I open the application and when the loadpreferences is called the app will force close
The logcat show me that the error is with this two lines for sure it's just with the first line coz he didn't get the second but they are the same so they are wrong wroted
Any help??
Change onCreate() as follows:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
result = (Button)findViewById(R.id.btn1);
b951 = (EditText)findViewById(R.id.b951);
b9511 = (EditText)findViewById(R.id.b9511);
sum95 = (EditText)findViewById(R.id.sum95);
p95 = (EditText)findViewById(R.id.p95);
t95 = (EditText)findViewById(R.id.t95);
LoadPreferences();
}
This is because you are using the EditTexts in the LoadPreferences() without calling findViewById() on the EditTexts.
You can follow and help from like codes. such as
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
it any confused about this then follow this link

ArrayList saved in Shared Preferences behaving strangely

In my app I have been using shared preferences for saving various types of data. I have been able to get the desired result using shared preferences before but I haven't been able to solve an issue with it.
I am saving an ArrayList in shared preferences in onPause method, getting saved data in OnCreate method and clearing the preferences in onBackPressed method. I have been able to finish this activity and still be able to get the ArrayList's data in Oncreate, but when I press the phone's back button twice and when the activity is created again I loose the data in ArrayList.
Here are parts of my code:
public class RecipientAddressActivity extends FragmentActivity {
private ArrayList<Person> prev_recArray;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipient_address);
prev_recArray = new ArrayList<Person>();
loadPreferences();
addListeners();
}
private void loadPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Gson gson = new Gson();
if (prev_recArray.size() == 0) {
int prev_recArraysize = sharedPreferences.getInt(
"Prev_Rec_Size", 0);
if (prev_recArraysize > 0) {
for (int i = 0; i < prev_recArraysize; i++) {
String json = sharedPreferences.getString(
"PrevRecList_" + i, "");
Person p = gson.fromJson(json, Person.class);
prev_recArray.add(p);
}
}
}
}
}
In a button's click event, I add an item in the prev_recArray:
{
Intent Recipient_info = new Intent();
Person recipient = new Person(edt_rec_name.getText().toString(),
edt_rec_addr1.getText().toString(), edt_rec_addr2.getText()
.toString(), edt_rec_city.getText().toString(), edt_rec_state
.getText().toString(), edt_rec_pcode.getText().toString(),
edt_rec_country.getText().toString());
prev_recArray.add(recipient);
// ...
finish();
}
private void showRecPicker() {
final RecipientPicker rec_picker = RecipientPicker
.newInstance("Select a Recipient");
Log.e("Before passing it to getAllRecipients Size", "RecPicker = "
+ prev_recArray.size());
rec_picker.getAllRecipients(prev_recArray);
if ((prev_recArray.size() == 0)) {
AlertDialog no_recipients = new AlertDialog.Builder(
RecipientAddressActivity.this).create();
no_recipients.setMessage("No previous recipients.");
no_recipients.setButton(RESULT_OK, "OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
});
no_recipients.show();
} else {
rec_picker.setListener(new RecipientPickerListener() {
#Override
public void onSelectRecipient(Person p) {
loadPersonValues(p);
rec_picker.dismiss();
}
});
rec_picker.show(getSupportFragmentManager(), "RECIPIENT_PICKER");
}
}
#Override
protected void onPause() {
Log.e("In RecipientAddress", "On Pause");
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
for (int i = 0; i < prev_recArray.size(); i++) {
String json = gson.toJson(prev_recArray.get(i));
editor.putString("PrevRecList_" + i, json);
}
editor.putInt("Prev_Rec_Size", prev_recArray.size());
editor.commit();
super.onPause();
}
#Override
public void onBackPressed() {
Log.e("Phone's back button is presed", "Clearing SP");
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
super.onBackPressed();
}
Can someone please point out if I'm doing something wrong or missing something.

check radio button missed value

i have an issue, to memorize values of EditText and RadioButtons i add #onResume and #onPause methods, it works fine for Edit Text but the problem is that the radio buttons appear checked but when i click to register the value into database, i have message (No value detected), what should i do to resolve the issue ? is there a solution !!!
#Override
protected void onPause()
{
super.onPause();
SharedPreferences prefs3 = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs3.edit();
editor.putBoolean("questionA", rm_13_1.isChecked());
editor.putBoolean("questionB", rm_13_2.isChecked());
editor.putBoolean("questionC", rm_14_1.isChecked());
editor.putBoolean("questionD", rm_14_2.isChecked());
editor.putBoolean("questionE", rm_14_3.isChecked());
// Commit the edits!
editor.commit();
}
#Override
protected void onResume(){
super.onResume();
SharedPreferences prefs3 = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
rm_13_1 = (RadioButton)findViewById(R.id.rm_13_1) ;
rm_13_2 = (RadioButton)findViewById(R.id.rm_13_2);
rm_14_1 = (RadioButton)findViewById(R.id.rm_14_1) ;
rm_14_2 = (RadioButton)findViewById(R.id.rm_14_2);
rm_14_3 = (RadioButton)findViewById(R.id.rm_14_2);
Boolean rm_13_1A = false;
Boolean rm_13_2A = false;
Boolean rm_14_1A = false;
Boolean rm_14_2A = false;
Boolean rm_14_3A = false;
rm_13_1A = prefs3.getBoolean("questionA",false);
rm_13_2A = prefs3.getBoolean("questionB",false);
rm_14_1A = prefs3.getBoolean("questionC",false);
rm_14_2A = prefs3.getBoolean("questionD",false);
rm_14_3A = prefs3.getBoolean("questionE",false);
rm_13_1.setChecked(rm_13_1A );
rm_13_2.setChecked(rm_13_2A );
rm_14_1.setChecked(rm_14_1A );
rm_14_2.setChecked(rm_14_2A );
rm_14_3.setChecked(rm_14_3A );
}
pref=PreferenceManager.getDefaultSharedPreference(this)
try

Function always returns false after commiting sharedpreferences without any error

I problematic parts are the following:
public class MainActivity extends BaseActivity implements
OnContactsInteractionListener, OnAdModeListener {
private SharedPreferences sp;
private SharedPreferences.Editor ed;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = this.getSharedPreferences("me.name",
MODE_PRIVATE);
ed = sp.edit();
private boolean parseIntent(Intent intent) {
if (intent.getAction().equals("SHOW_PHONE_CALL_LIST")
&& sp.getBoolean("SHOW_SECOND", false)) {
try {
goToPage(1);
int random = sp.getInt("RANDOM", 9999);
counterAdsAndLoad("2", random);
//ed is editor object
ed.putString("MP3PATH", "");
ed.putBoolean("SHOW_SECOND", false);
ed.commit()
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
ed.remove("RANDOM").commit();
return false;
}
I debugged because of the unreasonably bad behavior, I saw the following:
The if condition was true, as I expected and after the second commit() the program jumps to return false.
What could be the reason?
try this...
public class MainActivity extends BaseActivity implements
OnContactsInteractionListener, OnAdModeListener {
private SharedPreferences sp;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = getSharedPreferences("me.name",
MODE_PRIVATE);
}
private boolean parseIntent(Intent intent) {
if (intent.getAction().equals("SHOW_PHONE_CALL_LIST")
&& sp.getBoolean("SHOW_SECOND", false)) {
try {
goToPage(1);
int random = sp.getInt("RANDOM", 9999);
counterAdsAndLoad("2", random);
//ed is editor object
SharedPreferences.Editor ed = sp.edit();
ed.putString("MP3PATH", "");
ed.putBoolean("SHOW_SECOND", false);
ed.commit()
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
SharedPreferences.Editor ed = sp.edit();
ed.remove("RANDOM").commit();
return false;
}
Make sure you have follow this.
Create a SharedPrefrences reference.
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
Create a reference of SharedPreferncesEditor
SharedPreferences.Editor editor = prefs.edit();
Put Values in Editor
editor.putBoolean("SHOW_SECOND", true);
editor.putString("MP3_PATH", "");
Commit the edits at the end
editor.commit();

Categories

Resources