In my code, there are Spinners for countries and their cities. When I start app, the lists of Spinners are ordering alphabetically.
The application will be opened with the last closed settings. For example:
If we select France for country and Paris for city from spinners.
Then, exit from app. Start again. First element of state_spin will be France, city_spin will be Paris.
how can I do it. thanks..
state_spin = (Spinner) findViewById(R.id.spinner1);
city_spin = (Spinner) findViewById(R.id.spinner2);
new spinner1_countries(context,UrlMain,arrayAdpt_state,state_spin).execute();
//to get state lists from a website
state_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final String[] stateList = spinner1_countries.stateList;
new spinner2_city(context, arrayAdpt_state,city_spin).execute(); //to get city lists
}
public void onNothingSelected(AdapterView<?> arg0) { } });
city_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
......
You can store the previously selected options in SharedPreferences. When your app starts again, load these default values from SharedPreferences and set them as default for your selectors.
Find a nice tutorial here
When the User selects something in the spinner, save the position to SharedPreferences:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
...
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("1st_spinner", position);
editor.apply();
}
When Your app is started get the position an set the spinner:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
int position = sp.getInt("1st_spinner", 1);
state_spin.setSelection(position);
Related
In an Android app, I have a SpinnerAdapter that I am using to display expiration years of credit cards. My variable expirationYears contains an array of Strings with years from "2020" to "2029". It was declared as String[] expirationYears = new String[10]; and then with a function I set the ten years as Strings, from current year and then the nine subsequent years after that for a total of ten elements in the array. When I run it, this is what I see:
Everything is perfect so far. The only problem is that when as you see in the image above, 2020 is the year selected by default. That is the first element in the expirationYears array. But I want to set 2021 as default (the second element of the array). This is what my code has:
Spinner spinnerYearCreditCardPayment;
SpinnerAdapter creditCardYearAdapter = new SpinnerAdapter(Payment.this, expirationYears);
creditCardYearAdapter
.setDropDownViewResource(android.R.layout.spinner_dropdown_item);
spinnerYearCreditCardPayment.setAdapter(creditCardYearAdapter);
spinnerYearCreditCardPayment
.setOnItemSelectedListener(new OnItemSelectedListener() {
..........
});
I was expecting to have some property available to define which element I want to show by default. Something like creditCardYearAdapter.setSelectedItem(INDEX_NUMBER). But that property does not exist. Do you know how I could set the default selected item so that it is not the first element of the array (2020) but the second (2021)? Thank you.
UPDATE 1:
Following The_Martian's answer, this was what I did:
spinnerYearCreditCardPayment
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
arg0.setSelection(1);
cardYear = (String) spinnerYearCreditCardPayment
.getSelectedItem();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Now I correctly see the second element of the array ("2021") as the default selection.
The problem is that when I use arg0.setSelection(1);, I choose another year and it does not respond. The selected year remains "2021" even thought I am trying to change the year.
You can do similar to the following. I am just giving you an idea here.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
parent.setSelection(position + 1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Try this snippet
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
int seleccion=parent.getSelectedItemPosition();
spinner.setSelection(position)
});
}
You can select the spinner item based on value instead of position. Can refer the example below-
String value = "to be selected value";
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
if (value != null) {
int spinnerPosition = adapter.getPosition(value);
mSpinner.setSelection(spinnerPosition);
}
I have a profile activity where user select there country for the first time ,after that when user wish to change the country he will go to profile activity there he should see the previous selected country in the spinner and then he must be able to select another country from the spinner.
I am trying to update my profile activity ,I have a spinner named country in it..I am using set selected for getting the previous selected value .i am getting the value but when i am trying to change that value its not happening .
The Country_value is string
Below is the code for spinner :
country_adapter_list = new ArrayAdapter(MyProfile.this, R.layout.support_simple_spinner_dropdown_item,Country_listItems);
country = (Spinner) findViewById(R.id.sp_country);
country.setAdapter(country_adapter_list);
country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
country.setSelection(Country_listItems.indexOf(country_value));
country_data = Country_listItems.get(position);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
OnItemSelected() method will select the item present in list at position.
The setSelection() will internally call the onItemSelected() to set the selected item in the spinner. So calling setSelection() inside onItemselected() will not help you.
Try below code.
#Override
public void onItemSelected(AdapterView<?> **adapterView**, View view,int position, long l) {
**adapterView**.setSelection(Country_listItems.indexOf(country_value));
country_data = Country_listItems.get(position);
}
Your code is working fine, but it will not set selection on Spinner if "country_value" is not found in arraylist that you set.
Video Link
String chooseTime[] = {"7.00 - 9.00", "9.00 - 11.00", "11.00 - 13.00", "13.00 - 15.00", "15.00 - 17.00", "17.00 - 18.30" };
spTimeConsegna = (Spinner)
rootView.findViewById(R.id.timeChooseConsegna);
adapterChooseTimeConsegna = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, chooseTime);
adapterChooseTimeConsegna.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spTimeConsegna.setAdapter(adapterChooseTimeConsegna);
chooseTimeConsegna = chooseTime[spTimeConsegna.getSelectedItemPosition()];
I want to save the selected value of the spinner in the chooseTimeConsegna String, but it always saves the first value of the chooseTime string array indifferently what is choosen in the spinner. Why?
I think you are doing this in onCreate method, so it's only called when that activity is started, not every time you select things on spinner. Try something like this:
yourSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String chooseTime[] = {"7.00 - 9.00", "9.00 - 11.00", "11.00 - 13.00", "13.00 - 15.00", "15.00 - 17.00", "17.00 - 18.30" };
chooseTimeConsegna = chooseTime[position];
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
This method is gonna be called every time you select something on your spinner, and argument position is the position of the selected item in the spinner.
Replace:
chooseTimeConsegna = chooseTime[spTimeConsegna.getSelectedItemPosition()];
With:
spTimeConsegna.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
chooseTimeConsegna = chooseTime[position];
}
});
You should be good to go.
I am trying to write a simple app for android. I want to display toast message if there is no item is selected in spinner. .I use two progress bar to do this.I have tried the code given below.
String selection =sp.getSelectedItem().toString();
System.out.println("selected item "+selection);
if(selection=="[selection]")
Toast.makeText(getActivity(), "gfdgdghfhf", Toast.LENGTH_SHORT).show();
return false;
use a string value as flag of selection
String status="not_selected";
yourSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
MyData d = items[position];
status=d.getValue();
}
public void onNothingSelected(AdapterView<?> parent) {
status="not_selected";
}
});
if(status.equqls("not_selected"){
//show toast here
}
I have a problem. In my activity i have a ListView whose values are compiled from a Database. The database returns three columns: _Id, AccountName and Comments. What i want is that the when the user clicks on one of the items in the listView, that Item's position will be extracted and then that position will be compared with the postion in the ArrayList which has the data and then when the specific field and row is found out, the _Id field will be taken out and passed to another activity in the form of a String.
You may not have understood much; this might help:
public void search(View view){
final ListView vLst_IDCommName=(ListView)findViewById(R.id.lst_IDCommName);
EditText vTxt_searchTxt=(EditText)findViewById(R.id.search_txt);
String srch_str= vTxt_searchTxt.getText().toString();
if(srch_str.length()>0){
//The DataSource for the LstView
List<Comment> values = datasource.getContacts(srch_str);
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this, android.R.layout.simple_list_item_1, values);
vLst_IDCommName.setAdapter(adapter);
}
else{
Toast.makeText(getBaseContext(), "Please type in a value to proceed!", Toast.LENGTH_LONG).show();
}
vLst_IDCommName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Here I want to create a function that will take the position of the item clicked
//and then searched for that position in the ArrayList and then return the _Id of
//the account whose value was clicked.
}});
}
This code I used to get data:
public List<Comment> getContacts(String search_str) {
List<Comment> comments = new ArrayList<Comment>();
String srch_str=(String) search_str;
Cursor cur_comments= database.rawQuery("Select * from comments where acc_name like('%"+srch_str+"%')"+" "+ "or comment like('%"+srch_str+"%')", null);
cur_comments.moveToFirst();
while (!cur_comments.isAfterLast()) {
Comment comment = cursorToComment(cur_comments);
comments.add(comment); cur_comments.moveToNext();
}
cur_comments.close();
return comments;
}
Any feedback would be appreciated.
you can try
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String currentId=yourArrayList.get(position).toString();
}
vLst_IDCommName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Object s=parent.getItemAtPosition(position);
String j=s.toString();
}});