ArrayList saved in Shared Preferences behaving strangely - android

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.

Related

data not being inserted into ListView dynamically

I'm having issues where I have a button that is essentially a "favorites" button that saves a URL from a webview sesson and adds it to a listview in another class called favorites. It is doing this through sharedpreferences due to a lack of finding a better way to do it. The issue I'm having is when I try to save another URL it just overwrites the URL that is currently there and doesn't add another row. My code for webview that has the button is:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_share) {
shareURL();
Toast.makeText(this, getString(R.string.share),
Toast.LENGTH_SHORT).show();
}
if (id == R.id.action_favorite) {
changeIcon();
Snackbar.make(findViewById(android.R.id.content), "Saved for later", Snackbar.LENGTH_LONG).show();
String url = getIntent().getDataString();
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("URL", url );
edit.apply();
}
return super.onOptionsItemSelected(item);
}
// code for my "favorites" class is below:
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems = new ArrayList<String>();
//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites_list);
ListView listView = (ListView) findViewById(R.id.favoritesList);
adapter = new ArrayAdapter<String>(this,
R.layout.custom_lv,
listItems);
listView.setAdapter(adapter);
SharedPreferences bb = getSharedPreferences("my_prefs", 0);
String m = bb.getString("URL", "");
listItems.add(m);
adapter.notifyDataSetChanged();
}
Any help would be greatly appreciated!
--- EDIT --
With FnR's code it's still only adding the latest "saved" url in favorites list view, updated code is below:
--Favorites code--
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites_list);
ListView listView = (ListView) findViewById(R.id.favoritesList);
adapter = new ArrayAdapter<String>(this,
R.layout.custom_lv,
listItems);
listView.setAdapter(adapter);
getListFromSharedPreferences();
}
private List<String> getListFromSharedPreferences() {
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
Set<String> set = prefs.getStringSet("URL", null);
List<String> urlList = new ArrayList<>();
if (set != null) {
urlList = new ArrayList<>(set);
listItems.add(String.valueOf(set));
adapter.notifyDataSetChanged();
}
Log.e("size",urlList.size()+"");
return urlList;
}
-- Webview code --
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_share) {
shareURL();
Toast.makeText(this, getString(R.string.share),
Toast.LENGTH_SHORT).show();
}
if (id == R.id.action_favorite) {
changeIcon();
Snackbar.make(findViewById(android.R.id.content), "Saved for later", Snackbar.LENGTH_LONG).show();
String url = getIntent().getDataString();
putSharedPreferences(url);
}
return super.onOptionsItemSelected(item);
}
private void putSharedPreferences(String url) {
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
Set<String> set = prefs.getStringSet("URL", null);
if (set != null) {
set.add(url);
edit.putStringSet("URL", set);
edit.apply();
}
}
You are using same SharedPreferences key that means when you add a new url you are overriding already existing url.You need to store urls in a list . For this you can use SharedPreferences.Editor.putStringSet. Example is here
Save ArrayList to SharedPreferences.
private void putSharedPreferences(String url) {
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
Set<String> set = prefs.getStringSet("key", null);
if (set != null) {
set.add(url);
edit.putStringSet("key", set);
edit.apply();
}
}
private List<String> getListFromSharedPreferences() {
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
Set<String> set = prefs.getStringSet("key", null);
List<String> urlList = new ArrayList<>();
if (set != null) {
urlList = new ArrayList<>(set);
}
Log.e("size",urlList.size()+"");
return urlList;
}
What you need to do is add the previous saved URLs to the new Set before adding to SharedPreference.
private void putSharedPreferences(String url) {
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
Set<String> previousSet = prefs.getStringSet("key", null);
Set<String> set = new HashSet<>();
if (previousSet != null) {
set.addAll(previousSet);
}
set.add(url);
edit.putStringSet("key", set);
edit.apply();
}
}
The reason behind adding all previous saved data to new HashSet is that modifying the returned instance will not guarantee the data consistency or if its been modified at all. You can see documentation here for more explanation.

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

Android SharedPreferences not loading and saving properly

I've been getting null returns from getting strings from my saved preferences. I'm not sure how savedpreferences worked but my understanding was that when call a sharedpreferences, it creates the keypair file on the phone so you can come back to it later.
My program is essentially a string creation application. When you press a button, it creates a string to send as an sms. My settings activity page has four edittexts that save whatever is inside them with a buttonclick and returns to the main activity. The final button creates a String by getting the value from the keyvalue pair and constructs the message. However, I've always gotten null for each of the values.
Heres the code for the settings page and then the main page. Please ask if I could add more, I didn't add ALL of the code, just the sharedpreferences portions.
public SharedPreferences sp;
public Editor e;
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settingmenu);
//SP
sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
// named preferences - get the default ones and finish with it
e = sp.edit();
Button tt = (Button)findViewById(R.id.savebutton);
tt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
public void save(View view)
{
//THINGS HAPPEN HERE WITH SHARED PREFERENCES :(
savethethings();
this.finish();
return;
}
public String finishedtext(String userstring)
{
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
if(smsintroduction.isEmpty())
{
if(smsbody.isEmpty())
{
if(checkboxtext.isEmpty())
{
if(checkboxmessage.isEmpty()) //topkek for most AND statements Ive ever put in in if/then form
{
//Essentially the DEFAULT if they're ALL null
smsbody = "Hi "+ userstring +"! This is coming from jake's phone and it wants to send a text so we can talk or whatever. ";
}
}
}
}
Toast.makeText( this, "Creating text, then press send!", Toast.LENGTH_LONG).show();
String thetext = "";
thetext = smsintroduction + " " + smsbody + " " + checkboxtext;
return thetext;
}
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
// if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
// {
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
Create java class named SessionManger and put all your methods for setting and getting SharedPreferences values. When you want to save value use the object of this class and set and get the values.
Sample code given below.
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences("name_that_you_use", PRIVATE_MODE);
editor = pref.edit();
editor.apply();
}
public void setIntroMessage(String data) {
editor.putString("intro", data);
editor.commit();
}
public String getIntroMessage() {
return pref.getString("intro", null);
}
}

Previously added items are added again when saving an ArrayList using SharedPreferences

In my app I have 3 activities A,B and C. In Activity A when a button is pressed it starts Activity B and an empty arraylist is passed to it using putExtra. In Activity B, if the arraylist is empty it starts Activity C which adds an item in the ArrayList and passes it to Activity B. Activity B then displays and the arraylist. In Activity B there is a 'back' button which when pressed restarts the Activity A. In Activity A, the number of items in the arraylist is displayed and when an EditText is pressed, starts Activity B. Activity B now shows the items in the ArrayList since the ArrayList is not empty. This works fine but something strange happens. When displaying the items in the ArrayList the previous item/s is/are somehow getting added again. If the ArrayList has 1 item it works fine. But when 2 or more are added, somehow some items are added more than once and can be any random number. The size keeps increasing when I travel between Activity A and B.
Here is part of my code:
In Activity A:
Here Activity B is started when button btn_rec is clicked.
btn_rec = (ImageButton) findViewById(R.id.btn_rec);
btn_rec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent rec_Intent = new Intent(FlipCardActivity.this,
RecipientsActivity.class);
rec_Intent.putExtra("RecArray", RecipientArray);
startActivityForResult(rec_Intent, NO_OF_RECIPIENTS);
}
});
EditText displays the number of items in the ArrayList and when clicked starts Activity B.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == NO_OF_RECIPIENTS && resultCode == RESULT_OK) {
RecipientArray = (ArrayList<Person>) data.getSerializableExtra("RecArray");
if (RecipientArray.size() > 0) {
edt_rec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Log.e("In edt onclick", "Hello");
if (RecipientArray.size() == 0) {
Intent new_rec_Intent = new Intent(
FlipCardActivity.this,
RecipientAddressActivity.class);
startActivity(new_rec_Intent);
} else {
Intent rec_Intent = new Intent(
FlipCardActivity.this,
RecipientsActivity.class);
rec_Intent.putExtra("RecArray", RecipientArray);
startActivityForResult(rec_Intent, NO_OF_RECIPIENTS);
}
}
});
}
}
}
EditText starts Activity B when size of ArrayList is >0 else it starts Activity C.
In activity B:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RecipientArray = (ArrayList<Person>) getIntent().getSerializableExtra(
"RecArray");
Log.e("Recipient Array", "size = " + RecipientArray.size());
if (RecipientArray.size() == 0) {
Intent rec_addr_Intent = new Intent(RecipientsActivity.this,
RecipientAddressActivity.class);
rec_addr_Intent.putExtra("RecArray", RecipientArray);
startActivityForResult(rec_addr_Intent, REC_INFO);
} else {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
int size = prefs.getInt("size", 0);
for (int i = 0; i < size; i++) {
String json = prefs.getString("RecList_" + i, "");
Gson gson = new Gson();
Person p = gson.fromJson(json, Person.class);
RecipientArray.add(p);
}
// Log.e("RecListActivity","Size of arraylist"+RecipientArray.size());
this.m_adapter = new CustomListAdapter(RecipientsActivity.this,
R.layout.recipients_list, RecipientArray);
}
setContentView(R.layout.activity_recipients);
list = (ListView) findViewById(R.id.rec_list);
list.setAdapter(m_adapter);
addListenerForButtons();
}
protected void onPause() {
super.onPause();
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
Editor editor = prefs.edit();
Gson gson = new Gson();
// String json = gson.toJson(RecipientArray);
for (int i = 0; i < RecipientArray.size(); i++) {
String json = gson.toJson(RecipientArray.get(i));
editor.putString("RecList_" + i, json);
editor.putInt("size", i);
}
editor.apply();
}
In onPause the ArrayList's value is saved.
The ArrayList is 'RecipientArray' which contains Objects of type 'Person'.
Kindly, help me solve this problem asap. Please let me know if more details are required.
A previous comment:
You shouldn't use an uppercase letter at the begining of a variable name. It is confusing, since it looks like a class name, and also it can lead you to some troubles. You should rename your RecipientArray to recipientArray everywhere.
Lets get into your problem.
Im not sure if I understand your code, but what i can see (look at my coments:)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//here you retrieve the array coming from Activity A
RecipientArray = (ArrayList<Person>) getIntent().getSerializableExtra(
"RecArray");
if (RecipientArray.size() == 0) {
///...
} else {
//here, you add to the array, all the preferences from the array
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
int size = prefs.getInt("size", 0);
for (int i = 0; i < size; i++) {
String json = prefs.getString("RecList_" + i, "");
Gson gson = new Gson();
Person p = gson.fromJson(json, Person.class);
RecipientArray.add(p);
}
// ...
}
}
//here, when the activity is going to be closed, you save all the items in the array to the sharedpreferences
protected void onPause() {
super.onPause();
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
Editor editor = prefs.edit();
Gson gson = new Gson();
// String json = gson.toJson(RecipientArray);
for (int i = 0; i < RecipientArray.size(); i++) {
String json = gson.toJson(RecipientArray.get(i));
editor.putString("RecList_" + i, json);
editor.putInt("size", i);
}
editor.apply();
}
So what you are doing,
from A to B: you pass the array and add the elements in saved preferences.
from B to A: save all the elements to shared preferences (now you have the elements from the array coming from A, and also the previous elements from shared preferences, so your shared preferences is bigger)
from A to B: you pass the array again, and adds the elements from that bigger sharedpreferences, that as we saw in point 2, already contains all the elements, also the ones form the array, so you are duplicating them.
so think about what do you need, probably you dont have to pass the array between A and B, or you dont have to save it to Shared preferences, or you have to check what items do you save. Think about what you really need, the problem is in those lines

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

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

Categories

Resources