This is my Country spinner, in this i take the country id and pass in ApiGetState with country code i am getting state list, after getting state list i want to set it in State Spinner, I have done everything but if i select country first time its working fine but if i change the country, state spinner not updating, am i miss something in this code?
country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
scountry = parent.getItemAtPosition(position).toString();
String cCode = scountry.substring(0, scountry.indexOf("-"));
countryCode = Integer.parseInt(cCode);
ApiGetStates(countryCode);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I set the values on StateSpinner here from server:-
public void onResponse(Call<StatesModel> call, Response<StatesModel> response) {
if (response.isSuccessful()){
StatesModel model = response.body();
List<StatesModel.StatesModelDetail> list = model.getData();
for (int i = 0; i < list.size(); i++){
stateData = list.get(i);
String stateName = stateData.getName();
String code = stateData.getId();
String finalname = code + "-" + stateName;
arrayList.add(finalname);
ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.simple_spinner_dropdown, arrayList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
state.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
i done this thing. Just clear the arraylist before "ApiGetStates(countryCode);" and call "adapter.notifyDataSetChanged();" outside "for loop" as per Sandeep Pareek. e.g:-
arrayList.clear();
ApiGetStates(countryCode);
Related
I know there are several questions around this, but do not quite get how to solve it.
The problem is that I am showing some values from local SQlite database, the different options are shown ok and I can select them and the value displayed is ok. the problem is that when I try to save it, the getSelectedItem, gets the first item on the list. Any help or suggestions on how to solve it would be great.
Product product = new Product();
productsList = product.getProducts();
Spinner spinnerProduct = findViewById(R.id.spinnerProduct);
String[] arrayProduct = new String[productsList.size()];
for(int i = 0; i < productsList.size(); i++) {
arrayProduct[i] = productsList.get(i).nameProduct;
}
ArrayAdapter<String> adapterProduct = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arrayProduct);
adapterProduct.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerProduct.setAdapter(adapterProduct);
spinnerProduct.setOnItemSelectedListener(onItemSelectedListener1);
String productSelected=spinnerProduct.getSelectedItem().toString();
AdapterView.OnItemSelectedListener onItemSelectedListener1 =
new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Product product = new Product();
productsList = product.getProducts();
int[] arrayProduct = new int[productsList.size()];
for(int i = 0; i < productsList.size(); i++) {
arrayProduct[i] = productsList.get(i).stockCurrent;
}
String productStock = String.valueOf(arrayProduct[position]);
product_amount_available.setText(productStock);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
};
A spinner uses Event listening so you cannot just do below in a linear fashion:
spinnerProduct.setOnItemSelectedListener(onItemSelectedListener1);
String productSelected=spinnerProduct.getSelectedItem().toString();
Basically what your code is doing is setting the listener, and immediately after, it's getting some arbitrary/default value from your spinnerProduct object. But you haven't even entered any input to the spinner yet. You must process all the UI and business logic in the event listener's onItemSelected() method only.
You need to implement OnItemSelectedListener and override
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
}
More info can be found here https://developer.android.com/guide/topics/ui/controls/spinner#SelectListener
Thanks for the help. I solved it. I made the global variables.
int idProduct,idStorage;
String productSelected,storageSelected;
first fill the spinners
Product product = new Product();
productsList = product.getProducts();
Storage storage = new Storage();
storageList = storage.getStorage();
Spinner spinnerProduct = findViewById(R.id.spinnerProduct);
spinnerProduct.setOnItemSelectedListener(this);
Spinner spinnerStorage = findViewById(R.id.spinnerStorage);
spinnerStorage.setOnItemSelectedListener(this);
String[] arrayProduct = new String[productsList.size()];
for(int i = 0; i < productsList.size(); i++) {
arrayProduct[i] = productsList.get(i).nameProduct;
}
ArrayAdapter<String> adapterProduct = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arrayProduct);
adapterProduct.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerProduct.setAdapter(adapterProduct);
spinnerProduct.setOnItemSelectedListener(this);
String[] arrayStorage = new String[storageList.size()];
for(int i = 0; i < storageList.size(); i++) {
arrayStorage[i] = storageList.get(i).nameStorage;
}
ArrayAdapter<String> adapterStorage = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arrayStorage);
adapterStorage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerStorage.setAdapter(adapterStorage);
spinnerProduct.setOnItemSelectedListener(this);
then, as suggested implemented the onclicklisteners
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
if(adapterView.getId() == R.id.spinnerProduct)
{
idProduct=(int) adapterView.getSelectedItemId();
productSelected=adapterView.getSelectedItem().toString();
Product product = new Product();
productsList = product.getProducts();
int[] arrayProduct = new int[productsList.size()];
for(int i = 0; i < productsList.size(); i++) {
arrayProduct[i] = productsList.get(i).stockCurrent;
}
String productStock = String.valueOf(arrayProduct[pos]);
product_amount_available.setText(productStock);
}
else if(adapterView.getId() == R.id.spinnerStorage)
{
storageSelected=adapterView.getSelectedItem().toString();
idStorage=(int) adapterView.getSelectedItemId();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
and at last I passed the values into the method triggered by a button
btnSaveTransferProduct.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
saveTransferProduct(idProduct,productSelected, idStorage, storageSelected);
}
}
});
I have a spinner which populates data after an API call. I need to add an item that says "select one" as a first item in spinner. This item should not be able to be selected. I tried several ways online, but not able to implement it in my code since the array is filled after the api call and couldn't figure out a correct way to add "select one" item to that array.. Could anyone tell me how to do this in my code?
public void TEMPLATE_PARSE(JSONArray array) {
TemplateArrayList = new ArrayList<>();
TemplateNames = new ArrayList<String>();
for (int i = 0; i < array.length(); i++) {
JSONObject json = null;
try {
json = array.getJSONObject(i);
ModelTemplate GetTemplateDataModel = new ModelTemplate();
GetTemplateDataModel.setTemplateID(json.getInt("TemplateID"));
GetTemplateDataModel.setTemplateText(json.getString("TemplateText"));
TemplateArrayList.add(GetTemplateDataModel);
TemplateNames.add(TemplateArrayList.get(i).getTemplateText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
} // Close for loop here
if (array.length() != 0) {
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, simple_spinner_item, TemplateNames);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinTemplate.setAdapter(spinnerArrayAdapter);
spinTemplate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.i("ssssmIsSpinnerFirstCall",mIsSpinnerFirstCall.toString());
if(!mIsSpinnerFirstCall) {
selectedTemplateID = TemplateArrayList.get(position).getTemplateID();
String selectedTemplateText = TemplateArrayList.get(position).getTemplateText();
editText.setText(selectedTemplateText);
saveInSp("selectedTemplateID", String.valueOf(selectedTemplateID));
templateSelected = true;
}
mIsSpinnerFirstCall = false;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
First add Select One at position 0 to TemplateNames and then create adapter and set it to Spinner
TemplateNames.add(0, "Select One");
And then inside onItemSelected, check selected position and do whatever you want.
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position == 0)
// Skip or show validation message if you want
else {
// Do your actual task here
...
selectedTemplateID = TemplateArrayList.get(position - 1).getTemplateID();
String selectedTemplateText = TemplateArrayList.get(position - 1).getTemplateText();
...
}
}
i have a list :
[{
"catid": 1,
"title": "windows"
},
{
"catid": 2,
"title": "Android",
}
]
i want show list titles in spinner.
when user select a title, variable (int)selected_item equals corresponding catid.
for example when user select title "Android" from spinner , (int)selected_item = 2;
public void setupcatspinner(ArrayList<String> titles,ArrayList<Integer> catids){
final Spinner s1 = findViewById(R.id.spinner);
ArrayAdapter<String> adap=new ArrayAdapter<>
(this, android.R.layout.simple_spinner_item, titles);
adap.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adap);
s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// (int)selected_item = ???
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
https://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html#onItemSelected(android.widget.AdapterView%3C?%3E,%20android.view.View,%20int,%20long)
Therefore selected_item = titles.get(position).get(0), assuming 0 is the index of catid the the two dimensional list titles.
You can maintain two different list one for ids and other for titles. Set OnItemSelectedListener to spinner and you will get the selected item position , get the corresponding id from catId list.
Check the code below,
// List containing all category ids
ArrayList<String> catIdList = new ArrayList<>();
// List containing all titles
ArrayList<String> titleList = new ArrayList<>();
// Store the data in respective lists
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if(jsonObject.has("catid")){
catIdList.add(jsonObject.getString("catid"));
}
if(jsonObject.has("title")){
titleList.add(jsonObject.getString("title"));
}
}
You can pass titleList to SpinnerAdapter.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
String catId = catIdList.get(position);
String title = titleList.get(position);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
I have a json array like below and want to select corresponding id when an option is selected from spinner which is also dynamic i.e. also a json array which is displayed in Spinner
{
"DoctorName": ["0001 DR. Sameer", "0001 DR.Krishna murti", "110 Mr. Ram", "4 Mr. Yash Pathak.", "99 Dr. Varma"],
"DoctorId": [3,2,110,4,99]
};
and I have to do it into Android. Any help will be appreciated.
1.First Create a class
public class DoctorName
{
public String id = "";
public String name = "";
public void setId(String id)
{
this.id = id;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public String getId()
{
return id;
}
// A simple constructor for populating our member variables for this tutorial.
public DoctorName( String _id, String _name)
{
id = _id;
name = _name;
}
// The toString method is extremely important to making this class work with a Spinner
// (or ListView) object because this is the method called when it is trying to represent
// this object within the control. If you do not have a toString() method, you WILL
// get an exception.
public String toString()
{
return( name );
}
}
2.create another class
MainClass.java
ArrayList<DoctorName> doctList = new ArrayList<DoctorName>() ;
for(int i=0;i<arr_name.length;i++)
{
doctList.add(new DoctorName(arr_id[i],arr_name[i]));
}
//fill data in spinner
//ArrayAdapter<DoctorName> adapter = new ArrayAdapter<DoctorName>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, answers);
ArrayAdapter <DoctorName>adapter= new ArrayAdapter<DoctorName>
(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item,doctList );
Doctor_selection.setAdapter(adapter);
Doctor_selection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
DoctorName doctorName = (DoctorName) parent.getSelectedItem();
Log.i("SliderDemo", "getSelectedItemId" +doctorName.getId());
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
You have to use ArrayAdapter to show the json array values into spinner
Spinner spinner = new Spinner(this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list_values); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
//Set on item select Listener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// here you can get your selected id
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
For more check here.
Create two arrays, that is DoctorName and DoctorId
Create dynamic HashMap using above arrays, put all the values in key - value form by using for loop. But for this the length of both above arrays should be same.
HashMap<String, String> hash;
for(int i = 0; i < DoctorName.size() ; i++) {
hash = new HashMap<String, String>();
hash.put(DoctorId.get(i), DoctorName.get(i));
}
For spinner send only doctor name list from Map (hash), and onclick of spinner gets its Id that is doctorId.
Write below code in Spinner onclick
String name = spinner.getSelectedItem().toString();
String id = hash.get(name);
In id you will get the corresponding id of selected name.
Hope It helps :)
I have a simple Spinner implemented as:
vehicle = json.getJSONArray("vehicle");
for(int i = 0; i < vehicle.length(); i++){
JSONObject c = vehicle.getJSONObject(i);
//put json obkject on variable
String id = c.getString("id");
String name = c.getString("name");
String capacity = c.getString("capacity");
String cost = c.getString("cost");
String v = name + " ("+capacity + " Liters)";
vehicleList.add(v);
// Set Spinner Adapter
mySpinner.setAdapter(new ArrayAdapter<String>(OrderDetails.this,android.R.layout.simple_spinner_dropdown_item,vehicleList));
// Spinner on item click listener
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,View arg1, int position, long arg3) {
car = vehicleList.get(+position);
Toast.makeText(getApplicationContext(), car, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
car = null;
}
});
}
I wanted to grab the value of "ID" in the car variable. Is it possible with above implementation?
Thanks in advance.
try to replace your item click listener with this ...
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View view,
int position, long id) {
int spinnerItem = spinner.getSelectedItemPosition();
car = vehicleList.get(spinnerItem);
Toast.makeText(getApplicationContext(), selectedId, Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// nothing to do here :|
}
});
//EDIT
you can create another list that hold values of IDs ... and then add values to it as vehicleList ...
idList.add(id);
and then just call when item is selected in spinner
String selectedId = idList.get(spinnerItem);
Returns the position selected.
mySpinner.getSelectedItem()
or
mySpinner.getSelectedItemPosition()