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
Related
I need to save user input to shared preferences and also show it from shared preferences in a listview. How can I do this?
Right now my code adds to listview, but does not save it.
ListView listView;
Button AddWebsiteBtn;
EditText WebsiteName;
String[] ListOfWebsites = new String[]{};
SharedPreferences preferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
listView = (ListView) findViewById(R.id.list_of_websites);
AddWebsiteBtn = (Button) findViewById(R.id.btn_submit);
WebsiteName = (EditText) findViewById(R.id.website_name);
//using this part to add it to listview, maybe will need to remove it when shared preferences will work
final List< String > ListElementsArrayList = new ArrayList< String >
(Arrays.asList(ListOfWebsites));
final ArrayAdapter < String > adapter = new ArrayAdapter< String >
(AddActivity.this, android.R.layout.simple_list_item_1,
ListElementsArrayList);
listView.setAdapter(adapter);
AddWebsiteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListElementsArrayList.add(WebsiteName.getText().toString());
adapter.notifyDataSetChanged();
}
});
}
First you have to store all of your list item to ArrayList then Store ArrayList to SharedPreference
Variable declaration
SharedPreferences shared;
ArrayList<String> arrPackage;
Variable Initialization :
shared = getSharedPreferences("App_settings", MODE_PRIVATE);
// add values for your ArrayList any where...
arrPackage = new ArrayList<>();
.Store value to sharedPreference :
private void packagesharedPreferences() {
SharedPreferences.Editor editor = shared.edit();
Set<String> set = new HashSet<String>();
set.addAll(arrPackage);
editor.putStringSet("DATE_LIST", set);
editor.apply();
Log.d("storesharedPreferences",""+set);
}
Retrive value of sharedPreference:
private void retriveSharedValue() {
Set<String> set = shared.getStringSet("DATE_LIST", null);
arrPackage.addAll(set);
Log.d("retrivesharedPreferences",""+set);
}
You can use GSON for serializing your Array to JSON String so you can store it in SharedPreferences as usual String.
GSON examples you can find in that post
Convert your array of strings into a comma separate value (csv) string and save it. Use String.join(",", new String[]{"A", "B"}); in Java 1.8
When retrieving take is as a string and convert back to String array. use yourString.split(",")
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();
}
}
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
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.
I've create one spinner and I want to save all of spinner input when i close my application. How can I do? I think shared preferences can help me but i don't know how can use it!
This is my code:
private Spinner spinner;
private EditText Text;
private ArrayAdapter<String> adapter;
private Button addButton;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Text = (EditText) findViewById(R.id.et);
final List<String> planets = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.clienti_arrays)));
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, planets);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(adapter);
addButton = (Button) findViewById(R.id.add_new);
addButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
addNewSpinnerItem();
Collections.sort(planets);
}
});
}
protected void addNewSpinnerItem()
{
String textHolder = "" + Text.getText().toString();
adapter.add(textHolder);
}
public int compare(String s1, String s2) { return s1.toLowerCase().compareTo(s2.toLowerCase());
}
}
Thanks a lot for your help..
Override onPause() of Activity to save selected values in Shared Preferences when your application going to close as:
#Override
public void onPause()
{
// get Spinner Slected text here
String selectedtext = spinner.getSelectedItem().toString();
//Create SharedPreferences to store selected value
SharedPreferences spinnerPrefs = this.getSharedPreferences("spinnerPrefs",
MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = spinnerPrefs.edit();
prefsEditor.putString("spinner_selectedtext", selectedtext);
prefsEditor.commit();
super.onPause();
}
and to retrieve values saved in SharedPreferences :
SharedPreferences spinnerPrefs = this.getSharedPreferences("spinnerPrefs",
MODE_WORLD_READABLE);
String selectedtext = spinnerPrefs.getString("spinner_selectedtext",
"nothing_selected");
I detail how to do this in this post. Each time you enter an item in the edittext, it saves it to the spinner which holds the x last items you enter. The memory stays until you uninstall the app or manually clear the data.