how do i preserve item selected from spinner even after exiting app? - android

Here is my code below, which is getting item from spinner on click
public class SpinnerActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private Spinner spinner1,spinner2,spinner3;
private static final String[] sports = {
"Hockey","Cricket","Football","Basketball","Badminton","Tennis"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
spinner1 = (Spinner)findViewById(R.id.drop_down);
spinner2 = (Spinner)findViewById(R.id.drop_down2);
spinner3 = (Spinner)findViewById(R.id.drop_down3);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,sports);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
spinner2.setAdapter(adapter);
spinner3.setAdapter(adapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
How do I preserve the selected spinners' item even after exiting the application?

You can use SharedPreference to store the selected value position/id/string.
Simply add this line when you get String item
Editor edit = context.getSharedPreferences("Name_of_sf",Context.MODE_PRIVATE).edit();
edit.putString("selected_item", item);
edit.commit();
And can simply retrieve the value as
context.getSharedPreferences("Name_of_sf",Context.MODE_PRIVATE).getString("selected_item", "");

For more info #AnirudhSohil you could see the official documentation, it has a very detail examples, I hope that it helps you.
http://developer.android.com/training/basics/data-storage/shared-preferences.html

Related

Items in Spinner visible but onItemSelected Not Working

I am a beginner in Android. I have a spinner in my android code. It takes values from room database and once selected the value will be added to the listview. I have two issues
a) I am seeing values in my Spinner. But I am not able to select it and also onItemSelected for this spinner is not working
b) I would like to add a delete icon in my list view along with these values so that if the user is not interested in the value he can delete it.
Please can someone help me to resolve this?
Code is provided below:
public class MainActivity extends AppCompatActivity
{
private List<String> tasks = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private ListView consultantsList;
private Spinner spinner;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
consultantsRepository consrepo =
new consultantsRepository (getApplicationContext());
ArrayList<String> oncons = consrepo.getConsultants();
ArrayAdapter<String> consarrayadapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
oncons);
adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,tasks);
ListView consultantsList = (ListView) findViewById(R.id.ListToSend);
consultantsList.setAdapter(adapter);
spinner = (Spinner) findViewById(R.id.consSpinner);
spinner.setAdapter(consarrayadapter);
consarrayadapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinner.setOnItemSelectedListener
(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected
(AdapterView<?> parent, View view, int position, long id)
{
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(), item,
Toast.LENGTH_LONG).show();
tasks.add(item);
adapter.notifyDataSetChanged();
}
});
}
}
try-
String item=spinner.getSelectedItem().toString();

Android Spinner setSelection calls onItemSelected immidiately or not?

I have 2 spinners in an activity.
Based on the selection of one item in spinner1, relevant data should be loaded in spinner2. Consider spinner1 has data related to country and spinner2 has data related to state.
I should be able to get this done once the activity is created and if the user changes the selection in spinner1.
But I am stuck with populating the spinner2 data based on the saved value of spinner1.
I am calling spinner1.setSelection(indexSaved) but since I am only loading spinner2 in the onItemSelectedOf of spinner1, setSelection of spinner1 is not firing the onItemSelected.
Please let me know how I can achieve this.
I have done same thing in my project without any problem:
Below is code may be it help you:
On Create Method filled state list:
//initialize spinners
spinnerStateList = (Spinner) findViewById(R.id.spinnerStateList);
spinnerDistrictsList = (Spinner) findViewById(R.id.spinnerDistrictsList);
fillStateList();
public void fillStateList()
{
states = manage_states.fetchAllStates(getApplicationContext());
//add new element for select name
states.add(0,new RowItem("-1", "Select State"));
String[] spinnerArray = new String[states.size()];
for(int i= 0;i<states.size();i++)
{
spinnerArray[i] = states.get(i).getName();
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,spinnerArray);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerStateList.setAdapter(dataAdapter);
spinnerStateList.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
String selectedStateID = states.get(position).getId();
fillDistrictsSelectionChangeState(selectedStateID);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
public void fillDistrictsSelectionChangeState(String selectedStateID)
{
if(selectedStateID.equalsIgnoreCase("-1"))
{
linearLayoutDistrictsList.setVisibility(LinearLayout.GONE);
linearLayoutBlocksList.setVisibility(LinearLayout.GONE);
linearLayoutPHCList.setVisibility(LinearLayout.GONE);
linearLayoutSHCList.setVisibility(LinearLayout.GONE);
}
else
{
linearLayoutDistrictsList.setVisibility(LinearLayout.VISIBLE);
districts = manage_districts.fetchAllDistrictsByStateId(getApplicationContext(), selectedStateID);
//add new element for select name
districts.add(0,new RowItem("-1", "Select District"));
String[] spinnerArray = new String[districts.size()];
for(int i= 0;i<districts.size();i++)
{
spinnerArray[i] = districts.get(i).getName();
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,spinnerArray);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDistrictsList.setAdapter(dataAdapter);
spinnerDistrictsList.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
String selectedDistrictID = districts.get(position).getId();
fillBlocksSelectionChangeDistrict(selectedDistrictID);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}

How to control values and text in spinner

I want to build android app with spinner , I would like to appear in spinner some text , and when selected, it appears in TextView other text than the value of which is a selected.
for example , i want to appear in spinner website name (like= stackoverflow) and when select appear in TextView the website URL (like=https://stackoverflow.com/)
can anyone help me?
thanks in advance
First, you create yourself an Object:
public class LanguageObject {
private String title;
private String url;
public LanguageObject(String title, String url) {
this.title = title;
this.url = url;
}
public String getTitle() {
return title;
}
public Integer getUrl() {
return url;
}
}
Then, in your Activity/Fragment, you create an ArrayList with the objects you need:
ArrayList<SpinnerObject> spinnerObjectList = new ArrayList<SpinnerObject>();
spinnerObjectList.add(new SpinnerObject("Google", "www.google.com"));
spinnerObjectList.add(new SpinnerObject("StackOverflow", "www.stackoverflow.com"));
In addition to that, create a custom adapter that will handle your data:
public class SpinnerAdapter extends ArrayAdapter<SpinnerObject> {
public SpinnerAdapter (Context context, int textViewResourceId, ArrayList<SpinnerObject> spinnerObjects) {
super(context, textViewResourceId, spinnerObjects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
SpinnerObject spinnerObject = getItem(position);
if(view == null) {
LayoutInflater layoutInflater;
layoutInflater = LayoutInflater.from(getContext());
view = layoutInflater.inflate(android.R.layout.select_dialog_item, null);
if (view != null) {
TextView textView = (TextView) view.findViewById(android.R.id.text1);
textView.setText(spinnerObject.getTitle());
}
}
return view;
}
Now you can use this adapter on your Spinner, and get the url when one of the items was clicked.
You can add text to spinner like this:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
List<String> texts = new ArrayList<String>();
texts.add("Google");
texts.add("Facebook");
List<String> urls = new ArrayList<String>();
urls.add("www.google.com");
urls.add("www.facebook.com");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, texts);
spinner.setAdapter(adapter);
then you need to listen for item selected on spinner
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String url = urls.get(i);
// do with url whatever you need
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
// do nothing
}
});
For adding text in spinner you can use following code in onCreate()
Spinner locale;
ArrayList<String> lList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locale =(Spinner)findViewById(R.id.Cmblocale);
// bind data to Spinner(ComboBox)
lList =new ArrayList<String>();
lList.add("English");
lList.add("Canada");
lList.add("Chinese");
lList.add("French");
lList.add("Germany");
lList.add("Japan");
ArrayAdapter<String> cAdapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item,lList);
locale.setAdapter(cAdapter);
}
For Retrieving value use following code inside your setOnItemSelectedListener on spinner
if(locale.getSelectedItem().equals("English"))
{
txtText.setText(English);
}else if(locale.getSelectedItem().equals("Chinese"))
{
txtText.setText(Chinese);
}else if(locale.getSelectedItem().equals("Canada"))
{
txtText.setText(Canada);
}else if(locale.getSelectedItem().equals("French"))
{
txtText.setText(French);
}else if(locale.getSelectedItem().equals("Germany"))
{
txtText.setText(Germany);
}else if(locale.getSelectedItem().equals("Japan"))
{
txtText.setText(Japan);
}
Spinner spinner = (Spinner) findViewById(R.id.spinner); //create a spinner view in XML
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.your_array, android.R.layout.simple_spinner_item); // create adapter which has second parameter as the array which contains the values you want to show as entries of spinner
spinner.setAdapter(adapter); // set the adapter to your spinner and your spinner will show the values from array that you set in second parameter of adapter
To listen to the click on the options of the spinner
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
...
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
Now to show the appropriate link of the website for selected option from spinner you can have a map which has keys as same as the spinner values and values as websites as you want....
HashMap<String, String> nameWebsiteMap = new HashMap<String, String>();
nameWebsite.put("stack overflow","http://stackoverflow.com/"); // for example
So in onItemSelected you can simply do this
selectedSiteName = nameWebsite.get(parent.getItemAtPosition(pos).toString());
textView.setText(selectedSiteName);

Spinner data accept is mulfunctioning

I have a spinner which displays both options, but when I accept the female option, it still takes the answer as a male, any suggestions?
List<String> SpinnerArray = new ArrayList<String>();
SpinnerArray.add("Male");
SpinnerArray.add("Female");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, SpinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner Items = (Spinner) findViewById(R.id.genderSpinner);
Items.setAdapter(adapter);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
String selected = Items.getSelectedItem().toString();
if (selected.equals("Male")) {
inputGen = "Male";
}
if (selected.equals("Female")){
inputGen = "Female";
}
Following the official guide:
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
...
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
You can try a switch of position and then try your same conditions.

Android Spinners, changing Adapters

Alright, so I'm new to Android programming, so far my experience has been quite interesting and challenging. But I fear I have now encountered the first problem I'm not able to overcome on my own.
Simply put, all I want to do is have 2 Spinners:
1 for country selection
1 for province/state selection
What I want to accomplish is that when the user selects his/her country the province/state Spinner is updated with the correct adapter. Currently I'm only using 2 country for testing purposes.
When I launch the Activity, I get an exception and my app crashes.
Here's my code, any pointers would be appreciated !
public class ManageAccountActivity extends Activity {
final ArrayAdapter<CharSequence> adapterSexe = ArrayAdapter.createFromResource(ManageAccountActivity.this, R.array.sex_array_fr, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapterProvince = ArrayAdapter.createFromResource(ManageAccountActivity.this, R.array.province_array_fr, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapterStates = ArrayAdapter.createFromResource(ManageAccountActivity.this, R.array.state_array_fr, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapterCountry = ArrayAdapter.createFromResource(ManageAccountActivity.this, R.array.country_array_fr, android.R.layout.simple_spinner_item);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_management);
Spinner spinSexe = (Spinner) findViewById(R.id.spin_sex);
Spinner spinProvince = (Spinner) findViewById(R.id.spin_province);
Spinner spinCountry = (Spinner) findViewById(R.id.spin_country);
adapterSexe.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapterProvince.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapterStates.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapterCountry.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinSexe.setAdapter(adapterSexe);
spinProvince.setAdapter(adapterProvince);
spinCountry.setAdapter(adapterCountry);
spinCountry.setOnItemSelectedListener(new CountryOnItemSelectedListener());
}
public class CountryOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
setContentView(R.layout.account_management);
Spinner spinProvince = (Spinner) view.findViewById(R.id.spin_province);
if (parent.getItemAtPosition(pos).toString().equals("Canada")) {
spinProvince.setAdapter(adapterProvince);
} else {
spinProvince.setAdapter(adapterStates);
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
}
Here's the LogCat message I'm getting.
01-10 20:41:01.024: E/AndroidRuntime(1275):
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{gggolf.android.minutegolf/gggolf.android.minutegolf.ManageAccountActivity}:
java.lang.NullPointerException
You cannot instantiate your ArrayAdapter directly on class attribut, because createFromResource() use Context, and it's not exists at this time, do it in onCreate() methode instead.
In addition, you get spin province wrong in your listener, you can't call findViewById on view local variable, because it's not your layout, but an inflate of android.R.layout.simple_spinner_item
The good way:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Spinner spinProvince = (Spinner) findViewById(R.id.spin_province);
if (parent.getItemAtPosition(pos).toString().equals("Canada")) {
spinProvince.setAdapter(adapterProvince);
} else {
spinProvince.setAdapter(adapterStates);
}
}
Try having your Activity implement AdapterView.OnItemSelectedListener itself. Notice I've moved the Spinners and left out some of your code and replaced it with comments - make sure you include it where necessary...
public class ManageAccountActivity extends Activity
implements AdapterView.OnItemSelectedListener {
// Your ArrayAdapters as before
Spinner spinSexe = null;
Spinner spinProvince = null;
Spinner spinCountry = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_management);
spinSexe = (Spinner) findViewById(R.id.spin_sex);
spinProvince = (Spinner) findViewById(R.id.spin_province);
spinCountry = (Spinner) findViewById(R.id.spin_country);
// Call setDropDownViewResource on your ArrayAdapters
// Call setAdapter on your Spinners
spinCountry.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (parent.getItemAtPosition(pos).toString().equals("Canada")) {
spinProvince.setAdapter(adapterProvince);
} else {
spinProvince.setAdapter(adapterStates);
}
}
public void onNothingSelected(AdapterView parent) {
}
}
Why do you have setContentView(R.layout.account_management); in your onItemSelected() method? That should not be necessary.
Furthermore, you should instantiate your adapters in the onCreate() method of your activity, and pass your actual activity instance as the context.
And the code for retrieving the Spinner object in the select listener should be changed from
Spinner spinProvince = (Spinner) view.findViewById(R.id.spin_province);
into
Spinner spinProvince = (Spinner) findViewById(R.id.spin_province);
Calling findViewById() on the local view object in your select listener will return NULL because the view does not contain the Spinner.

Categories

Resources