Save more than one item from ListView using SharedPreferences - android

I am trying to make a simple todo list app which will probably store only a few things.
After adding items in the ListView, and closing the app, the only entry that loads is the last one that is entered. How do I make all the entered entries show up after closing the app?
Code:
public class MainActivity extends ActionBarActivity {
EditText display;
ListView lv;
ArrayAdapter<String> adapter;
Button addButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (EditText) findViewById(R.id.editText1);
lv = (ListView) findViewById(R.id.listView1);
addButton = (Button) findViewById(R.id.button1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
lv.setAdapter(adapter);
LoadPreferences();
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String task = display.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
SavePreferences("LISTS", task);
}
});
}
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = data.edit();
editor.putString(key, value);
editor.commit();
}
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("LISTS", "None Available");
adapter.add(dataSet);
adapter.notifyDataSetChanged();
}}
Thanks in advance.

You should have to keep key different for each item you are adding to SharedPreferences, otherwise last item you added in preference will override the last one.

I won't suggest using SharedPreferences for making an app like a todo list.
Make a SQLite database and store your todos in that. Or you can save the todos in a JSON file which is also very simple to achieve.
Using SharedPreferences won't be efficient in this case as you will need to track the keys of all the todo preferences, which creates another overhead.
Check out this post by Lars Vogel about creating content providers and SQLite Databses:
Android SQLite database and content provider - Tutorial

Related

Saving and loading listview data using SharedPreferences

I am trying to save my listview items using SharedPreferences. I have somewhat managed to save and load items in the listview. I can add items to it, but when I load the listview after closing it, only the most recent added item is saved. Any help would be appreciated, thanks!
private EditText editTxt;
private ListView list;
private ArrayAdapter<String> adapter;
private ArrayList<String> arrayList;
private String item;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
editTxt = (EditText) findViewById(R.id.editText);
list = (ListView) findViewById(R.id.List);
arrayList = new ArrayList<String>();
adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item, arrayList);
list.setAdapter(adapter);
//load data here
LoadPreferences();
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
FloatingActionButton add = (FloatingActionButton) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (editTxt.getText().toString().length() == 0) {
Toast.makeText(MainActivity.this, "Please enter something into the text box",
Toast.LENGTH_SHORT).show();
} else {
item = editTxt.getText().toString();
arrayList.add(item);
adapter.notifyDataSetChanged();
//save data here
SavePreferences("List", item);
editTxt.setText("");
}
}
});
}
//save listview data
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = data.edit();
editor.putString(key, value);
editor.commit();
}
//load listview data
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("List", "Add an item...");
adapter.add(dataSet);
adapter.notifyDataSetChanged();
}
You try to save all of clicked items in one SharedPreferences repository. try to change name when save value to SharedPreferences - for example SavePreferences(item.getName(), item); where item.getName method return unique name for this item. But is a bad way. Good way is store multiple data in database.
This is happening because each time the user selects an item from the list, the previous item stored in Preferences is being replaced by the new item since every item is being stored with the same key.
You can try something like this
//save listview data
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String s=data.getString(key,""); //to fetch previous stored values
s=s+"!"+value; //to add new value to previous one
data.edit().putString(key,s).commit();
}
//load listview data
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("List", "Add an item...");
if(dataSet.contains("!")){ //to check if previous items are there or not
String rows[]=dataSet.split("!"); //to get individual rows of list
for(int i=0;i<rows.length;i++){
adapter.add(rows[i); //to add each value to the list
adapter.notifyDataSetChanged();
}
} else{
adapter.add(dataSet);
adapter.notifyDataSetChanged();
}
}

Trying to Implement shared preferences with a listview

can someone tell me what I am doing wrong here? I'm getting a null pointer exception for my listview... I am trying to use shared preferences to keep the values in my listview when I come back to it
Apologies if its a silly question but from my view everything is initialised and nothing is empty that shouldnt be, so it would be great if someone else could spot the issue :{)
public class MainActivity3 extends MainActivity{
EditText display;
ListView lv;
ArrayAdapter<String> adapter;
Button addButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (EditText) findViewById(R.id.editText5);
lv = (ListView) findViewById(R.id.listView2);
addButton = (Button) findViewById(R.id.button21);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
lv.setAdapter(adapter);
LoadPreferences();
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (display.getText().toString().equals("")) {
}
else {
String task = display.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
SavePreferences("LISTS", task);
}
}
});
}
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = data.edit();
editor.putString(key, value);
editor.commit();
}
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("LISTS", "None Available");
adapter.add(dataSet);
adapter.notifyDataSetChanged();
}
}
Apologies if its a silly question but from my view everything is initialised and nothing is empty that shouldnt be, so it would be great if someone else could spot the issue :{)
<ListView
android:layout_width="wrap_content"
android:layout_height="359dp"
android:id="#+id/listView2"
android:layout_alignParentTop="true"
android:layout_toStartOf="#+id/button21"
android:layout_alignRight="#+id/editText6"
android:layout_alignEnd="#+id/editText6" />
Could you put here your layout code?? Because the name of your components are not so good, So, maybe, you can be calling to another listView in another layout.
Could you try to delete your import line when you have android.R ? and then, import the correct.
If this doesn't work, up the code of layout, please :)
I am thinking about another solution. Go to listView and give it this id:
android:id="#android:id/list"
then, Go to MainActivity and write this:
public class YourClass extends ListActivity
So, to access to listView, you just have to use the next method:
getListView();
if you want to know more, see the oficial doc here
I hope It work

Android: to save values in ArrayList

I want to save values in ArrayList with SharedPreference. Then, I want to call values in ArrayList from another class, but it is not saving. How can I do this? With SharedPreferences? To save File? Or create Sqlite? Thank you for helping.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button saveButton = (Button)findViewById(R.id.button);
final Button delButton = (Button)findViewById(R.id.delButton);
final ListView listView = (ListView)findViewById(R.id.listView);
final EditText editText = (EditText)findViewById(R.id.editText);
final ArrayList<String> arrayList = new ArrayList<String>();
SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("numbers", arrayList.toString());
editor.commit();
String arrayString = sharedPref.getString("numbers", null);
final ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
saveButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String str = editText.getText().toString();
Integer cout = listView.getCount()+ 1;
String str1 = cout.toString().concat("."+str);
arrayList.add(listView.getCount(), str1);
arrayAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Data Saved", Toast.LENGTH_SHORT).show();
editText.setText(" ");
}
});
delButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
arrayList.remove(arrayList.size()-1);
arrayAdapter.notifyDataSetChanged();
}
});
}
I think you can not do this editor.putString("numbers", arrayList.toString()); because object.toString() does not convert the ArrayList to String it just make something weird like "#Object3223rw", take a look to this post instead Save ArrayList to SharedPreferences
Save list:
editor.putString("List", TextUtils.join(",", myList));
Get list:
String serialized = sharedPref.getString("List", null);
myList = Arrays.asList(TextUtils.split(serialized, ","));
An observation that works on a List not ArrayList because asList return List. Tofasio's answer does not work if you have duplicate strings that works with set.
My understanding is to use SharedPreference only to save simple key-value pairs (bool, float, int, long and string) and not as a data storage. If you need to save more complex data objects (including lists and arrays), you'll need to serialize/deserialize and save on disk.
http://developer.android.com/guide/topics/data/data-storage.html

Using JSONArray with SavePreferences to save data from ListView

i am quite new at coding for android. I tried to use SavePreferences in order to save User Inputted data for a ListView. However this method resulted in only saving the last item that the user inputted, not the entire ListView.(i think this was because i was overwriting the key so that it would only show the last value)
Then it was suggested that i should use a JSONArray but I could not understand what happened.
My Code using JSONArray is below:
Note: there are a bunch of errors on the JSONArray since i dont think i used the correct Key.
public class TaskPage extends SherlockActivity {
EditText display;
ListView lv;
ArrayAdapter<String> adapter;
Button addButton;
ArrayList<String> dataSetarrlist = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (EditText) findViewById(R.id.editText1);
lv = (ListView) findViewById(R.id.listView1);
addButton = (Button) findViewById(R.id.button1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice);
lv.setAdapter(adapter);
LoadPreferences();
// setChoiceMode places the checkbox next to the listviews
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String task = display.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
SavePreferences("LISTS", task);
}
});
}
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
JSONArray array = new JSONArray(data.getString(key, value));
SharedPreferences.Editor editor = data.edit();
editor.putString(key, value);
editor.commit();
}
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
JSONArray dataSet1 = new JSONArray(data.getString("LISTS", "None Available"));
for(int i = 0; i<dataSet1.length(); i++)
adapter.add(dataSet1.getString(i));
adapter.notifyDataSetChanged();
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,dataSetarrlist);
lv.setAdapter(adapter);
// setChoiceMode places the checkbox next to the listviews
}
I am quite confused at this point so can someone please show me where Im going wrong and provide some example code. I almost certain it is because I am not using the key and value correctly to save the data but i cant seem to get this correct
Lastly, is there another method where I dont have to use the JSONArray so that it will still show all the user inputs in the listview.
EDITED CODE IS BELOW
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String task = display.getText().toString();
adapter.add(task);
dataSetarrlist.add(task);
adapter.notifyDataSetChanged();
SavePreferences("LISTS", dataSetarrlist.toString());
}
});
}
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = data.edit();
editor.putString("LISTS", dataSetarrlist.toString());
editor.commit();
}
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("LISTS", dataSetarrlist.toString());
ArrayList<String> dataSetarrlist = new ArrayList<String>();
dataSetarrlist.add(dataSet);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,dataSetarrlist);
lv.setAdapter(adapter);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// setChoiceMode places the checkbox next to the listviews
}
Your TextView (display) only contains 1 value. On the OnClickListener of addButton, you should add "task" on your array & pass the array to SavePreferences instead of "task":
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String task = display.getText().toString();
adapter.add(task);
dataSetarrlist.add(task);
adapter.notifyDataSetChanged();
SavePreferences("LISTS", dataSetarrlist);
}
});
}
You should modify SavePreferences to process the ArrayList.

Android: Store array of strings in shared preferences dynamically

I have only one edittext in my app from which I want to store strings array on button click. Just like history of any browser. I want to show the stored strings when my app starts. I have been trying to use shared preferences with single textview. I have attached the code for my activity.
public class MainActivity extends Activity {
Button insert;
EditText edt;
TextView txt1, txt2, txt3, txt4, txt5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.search_word);
txt1 = (TextView) findViewById(R.id.txt1);
insert = (Button) findViewById(R.id.insert);
insert.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
String text = edt.getText().toString();
editor.putString("key", text);
editor.commit();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_SHORT)
.show();
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(this);
String text = app_preferences.getString("key", "null");
txt1.setText(text);
}
}
My only one textview is populating, I want to show last five search history using this. Please give me some idea regarding this.
Serialize your data. Array -> String and String can be saved to the preference, maybe use JSON to encode / decode your data.
http://developer.android.com/reference/org/json/JSONObject.html
http://www.json.org/

Categories

Resources