Save an array to sharedpreferences and show it in listview - android

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(",")

Related

Loading SharedPreferences in another activity

Here's the problem. In my second class, I'm trying to load the SharedPreferences. Below I'll also include my first class.
//set label for journal questions
public TextView journalQuestionLabel;
public int counter = 0;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_journal);
//TODO: Send saved preferences here
preferences = getSharedPreferences("grammarOption", MODE_PRIVATE);
int selection = preferences.getInt("grammarOption", -1);
Log.d("in onCreate", "preferences = " + selection);
}
When I test it, my debug log always prints -1. It won't load my shared preferences. What am I doing wrong?
I've tried the other answers on here and every tutorial, but they aren't working. Here is my code to set up and save my spinner preferences. I've checked this and it's working.
private void setupSpinner() {
// Create adapter for spinner. The list options are from the String array it will use
// the spinner will use the default layout
final ArrayAdapter grammarSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.array_grammar_options,
android.R.layout.simple_spinner_dropdown_item);
// Specify dropdown layout style - simple list view with 1 item per line
grammarSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
//Apply the adapter to the spinner
grammarChoiceSpinner.setAdapter(grammarSpinnerAdapter);
//Create shared preferences to store the spinner selection
SharedPreferences preferences = getApplicationContext().getSharedPreferences
("Selection", MODE_PRIVATE);
editor = preferences.edit();
// Create the intent to save the position
grammarChoiceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//receive the string of the option and store it
int grammarOptionPosition = grammarChoiceSpinner.getSelectedItemPosition();
//put the string in the editor
editor.putInt("grammarOption", grammarOptionPosition);
editor.commit();
//make a toast so the user knows if it's not "select"
if (grammarOptionPosition != 0) {
Toast.makeText(getApplicationContext(), "Choice saved.",
Toast.LENGTH_SHORT).show();
}
}
// Because AdapterView is an abstract class, onNothingSelected must be defined
#Override
public void onNothingSelected(AdapterView<?> parent) {
mGrammar = 0;
}
});
}
Here it's called in onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opening);
//find the spinner to read user input
grammarChoiceSpinner = (Spinner) findViewById(R.id.spinner);
setupSpinner();
You are passing wrong String in getSharedPreferences(String, int).
preferences = getSharedPreferences("Selection", MODE_PRIVATE);
int selection = preferences.getInt("grammarOption", -1);
Log.d("in onCreate", "preferences = " + selection);
Give this a try.
I hope it helps.
Make sure your SharedPreference key is same in both the class or even throughout the whole App.
While saving do like -
SharedPreferences preferences = getSharedPreferences("MY_PREFS", MODE_PRIVATE);
preferences.edit().putInt("grammerOption", 1).apply();
While Getting data from prefs do like -
SharedPreferences preferences = getSharedPreferences("MY_PREFS", MODE_PRIVATE);
int option = preference.getInt("grammerOption", -1);
PS,
Key for preference(which is MY_PREFS here) must be the same.

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

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

Save more than one item from ListView using SharedPreferences

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

how can I save my spinner input?

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.

Categories

Resources