I am to android coding and have what I hope will be a simple question. I have an app that has a demographics page, with various spinners (although I will only use 1 for this example). The spinners are already populated, but the user can save them once they have made their choice so every time they open this app the previous choices are there.
My code to load the values into the spinner is
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_demographics);
// Show the Up button in the action bar.
setupActionBar();
SharedPreferences prefs = getSharedPreferences("data_file", MODE_PRIVATE);
int ageValue = prefs.getInt("Age", 0);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
//set the default according to value
spinner.setSelection(ageValue);
}
and then my code to save the data is
public void submitDemo(View view) {
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
int ageValue = spinner.getSelectedItemPosition();
//save the current data from the spinner
SharedPreferences prefs = getSharedPreferences("data_file", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("Age", ageValue);
editor.commit();
finish();
}
I'm not bothered about capturing the value when they change the spinner, just simply at the end. I know it's probably something simple that I'm missing, but if anyone can help I would greatly appreciate it
First, set an adapter:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(),
android.R.layout.simple_spinner_item,
getResources().getStringArray(R.array.your_string_array));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
If setSelection(value) doesn't work try with
spinner.setSelection(ageValue, true);
This will "animate" the selection, i.e. scroll it to the selected position.
Related
I have two Spinners. In onCreate i setup listeners for them. At some other places i populate them.
Now I am not sure what the best practice is for handling these spinners when screen orientation changes. Should i store all values and selected item in sharedPreferences somehow or in savedInstanceState?
If you can, please advise me in a prefered way and also include some sample code for handling spinners. The goal here is to keep the values and selected item thru the lifecycle.
I will include code at request or if needed.
Thanks
Try this, onSaveInstanceState for Screen Orientation for saving your selected value of spinner,According to my choice shared preference is not good choice for saving selected values of spinner.
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("mySpinner", mySpinner.getSelectedItemPosition());
// do this for each or your Spinner
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize all your visual fields
if (savedInstanceState != null) {
mySpinner.setSelection(savedInstanceState.getInt("mySpinner", 0));
// do this for each of your text views
}
}
Add android:configChanges="orientation|screenSize" in your AndroidManifest file, it will keep spinner value selected on orientation change.
User Spinner Like this:
mSpinner = findViewById(R.id.spinner);
ArrayList<String> stringArrayList = new ArrayList<>();
for (int i = 0; i < 6; i++) {
stringArrayList.add("List Item " + i);
}
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, stringArrayList);
spinner.setAdapter(arrayAdapter);
What I have is a Settings activity on which I choose the language via spinner. When I change it to Russian for example the language changes, but when I open the Settings menu again the selected item on the spinner is the first item (English) and not the current one (Russian).
This is my spinner
Resources res = getResources();
language = res.getStringArray(R.array.languages_arrays);
Spinner spinner = (Spinner) findViewById(R.id.toolbar_spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, R.layout.spinner_item_dropdown,
language);
spinner.setAdapter(adapter);
What do I need to change in the spinner in order to show the selected language?
If you want to set the previous selected item of a spinner you have to store the selected item and then set your selection :
here's an example wish i'am getting my previous selected item then fetching the item's position from he's array adapter
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String language = preferences.getString("language", "");
if(!language.equalsIgnoreCase(""))
{
int spinnerPosition = arrayAdapter.getPosition(language);
spinner.setSelection(spinnerPosition);
}
You can store your data as below :
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
SharedPreferences.Editor editor = preferences.edit();
editor.putString("language",spinner.getSelectedItem().toString(););
editor.apply();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
For that u need to set spinner value programatically
for (int i=0 ;i<languages.length;i++)
{
if(languages[i] = "RUSSIAN")//change it according to ur prrefence
spinner.setSelection(i);
}
You have to save previous selected value somewhere in your app. When you open setting again check for that value and find position of it in array. Once you find location of it set Spinner selection to that position like below:
spinner.setSelection(position_of_selected_item);
the question is quite obvious but still nothing worked for me. In my application i'm selecting value from spinner and wanna to let spinner to show selected value after restarting application. to store spinner value i'm using shared preferences But when restarts application logcat shows null pointer error. Here's code
String options[]={"-Select-", "Domino's","Pizza Hut", "Pizza Bite"};
Spinner spin;
int formatposition;
fSpinner = (Spinner)findViewById(R.id.fSpinner);
ArrayAdapter<String> adp = new ArrayAdapter<String> (MainActivity.this,android.R.layout.simple_spinner_dropdown_item,options);
fSpinner.setAdapter(adp);
To store spinner selected value:
Editor editee = preferences.edit();
editee.putInt("lastindex", spin.getSelectedItemPosition());
editee.commit();
To restore shared preferences when application restarts
protected void onCreate(Bundle savedInstanceState) //onCreate is called when the activity is starting
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context=this;
listViewSMS=(ListView)findViewById(R.id.lvSMS); //view that shows items in a vertically scrolling list
btnaddnew = (Button)findViewById(R.id.btnaddnew);
btnaddnew.setOnClickListener(this);
formatposition = preferences.getInt("lastindex", 0);
spin.setSelection(formatposition);
}
How could array find index without name of array??
Try this one to solve:-
spinposition = preferences.getInt("lastindex", 0);
spin.setSelection(spinposition);
I'm trying to implement a listview and what I want exactly is:
The app launches, 1 item from ListView is being chosen and starts a webview. This step is done
But what I want is that 2. time when I launch the app, it will start from that item and not show the list again. So it will continue always to start on that item I pressed first time.
I hope someone can show me a tutorial I can follow or some keyword I will try to see if I can do it.
*UPDATE --> Code
public class AndroidListViewActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
ListView lv = getListView();
SharedPreferences prefs = getSharedPreferences("PREFERENCE", MODE_PRIVATE);
boolean firstrun = prefs.getBoolean("firstrun", true);
if (firstrun) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstrun", false);
editor.apply();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getApplicationContext(), EnkeltView.class);
// sending data to new activity
i.putExtra("url", "https://google.dk");
startActivity(i);
}
});
}
// Save the state
getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.edit()
.putBoolean("firstrun", false)
.commit();
}
}
Use SharedPreference works like a DB but in a small scale:SharedPreference
Android documentation: This data will persist across user sessions (even if your application is killed).
So SharedPreferences shouldn't be getting wiped when a device reboots or force closes.
you can store item in shared preferences in 1st time and during second time you can check if your shared Preference is not null then It launch the application with item stored in it.
I'm trying to save a Spinner value into a ListPreference. I can't get it to work. I've tried to get this working for a long time now. Does anyone have a solution or can anyone point me in the right direction.
So this is what I have:
SharedPreferences preferences;
private static final String KEY_WEIGHT_PREFERENCE = "weightunit";
...
preferences = PreferenceManager.getDefaultSharedPreferences(this);
...
This is the main part, both the Spinner and the ListPreference grab the same data from an array xml.
SharedPreferences.Editor edit = preferences.edit();
Spinner weight = (Spinner) findViewById(R.id.weightUnitSpinner);
int selectedPosition = weight.getSelectedItemPosition();
edit.putInt(KEY_WEIGHT_PREFERENCE, selectedPosition);
edit.commit();
Thanks!
What isn't working?
There's a sample app called Spinner that contains a sample Spinner. It saves the state of the Spinner to saved preferences in onPause(), and restores it in onResume().
I found the answer, the SpinnerValue needs to be saved as a string in order to get recognized by the ListPreference.
Here's my final code:
private void updatePreferenceWeightValue() {
SharedPreferences.Editor edit = preferences.edit();
Spinner weight = (Spinner) findViewById(R.id.weightUnitSpinner);
int selectedPosition = weight.getSelectedItemPosition();
String weightValue = "";
weightValue = Integer.toString(selectedPosition);
edit.putString(KEY_WEIGHT_PREFERENCE, weightValue);
edit.commit();
}