how can I save my spinner input? - android

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.

Related

Spinner not getting selected value

I am have 2 spinners that are set to initial values. I then expect the user to select new values. I am then trying to get those values. However, getSelectedItem() only returns the initial value - the change is not saved, even though the new selection shows up in the spinner:
Spinner spinner1 = (Spinner) view.findViewById(R.id.lessonTypeSpinner);
Spinner weatherConditionS = (Spinner) view.findViewById(R.id.weatherConditionSpinner);
spinner1.setSelection(hmlessonType.get(lessonType));
weatherConditionS.setSelection(hmWeatherCondition.get(weatherCondition));
Button update = (Button) view.findViewById(R.id.updateButton);
final String lessonTypeCopy = spinner1.getSelectedItem().toString();
final String weatherConditionCopy = weatherConditionS.getSelectedItem().toString();
pref = this.getActivity().getSharedPreferences(this.PREF_FILENAME, 0);
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor edit = pref.edit();
edit.putString("lessonType", lessonTypeCopy);
edit.putString("weatherCondition", weatherConditionCopy);
edit.apply();
}
});
Get the values inside onClick() method.
You should change it like this:
Spinner spinner1 = (Spinner) view.findViewById(R.id.lessonTypeSpinner);
Spinner weatherConditionS = (Spinner) view.findViewById(R.id.weatherConditionSpinner);
spinner1.setSelection(hmlessonType.get(lessonType));
weatherConditionS.setSelection(hmWeatherCondition.get(weatherCondition));
Button update = (Button) view.findViewById(R.id.updateButton);
pref = this.getActivity().getSharedPreferences(this.PREF_FILENAME, 0);
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String lessonTypeCopy = spinner1.getSelectedItem().toString();
final String weatherConditionCopy = weatherConditionS.getSelectedItem().toString();
SharedPreferences.Editor edit = pref.edit();
edit.putString("lessonType", lessonTypeCopy);
edit.putString("weatherCondition", weatherConditionCopy);
edit.apply();
}
});

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

How to store a variable in android

I want to store a variable in my project. In fact, I want the user to choose an option via a drop down list, and store the value of this variable to be able to still use it in my other activities
My spinner code :
public class MyAndroidAppActivity extends Activity {
private Spinner spinner1, spinner2;
private Button btnSubmit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
// add items into spinner dynamically
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
// get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MyAndroidAppActivity.this,
"OnClickListener : " +
"\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) +
"\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
Toast.LENGTH_SHORT).show();
}
});
}
}
You can use the SharedPreferences to store information for future use in your App.
http://developer.android.com/reference/android/content/SharedPreferences.html
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html
There are of course several other ways to solve it but this one is pretty straight forward.
More information about storage can be found here: http://developer.android.com/guide/topics/data/data-storage.html#pref
You can make this in two ways:
First method allows you to keep the data only while the application is running, the other method will keep the data even if the application is closed.
Create a class GlobalData
public enum GlobalData {
Data;
private boolean isBooleanVal= false;
public boolean isBooleanVal() {
return isBooleanVal;
}
public void setBooleanVal(boolean isQuizStartedAgain) {
this.isQuizStartedAgain = isBooleanVal;
}
}
And call it in other class:
GlobalData.Data.setBooleanVal(true);
OR
GlobalData.Data.isBooleanVal();
Using SharedPreferences
private SharedPreferences sharedpreferences;
private SharedPreferences.Editor editor;
sharedpreferences = getActivity().getSharedPreferences(ApplicationConstants.SHARED_PREFERENCES, Context.MODE_PRIVATE);
editor = sharedpreferences.edit();
editor.putBoolean(value,value);
editor.commit();
Example

Categories

Resources