use Two-dimensional list in spinner - android

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) {
}
});

Related

Spinner value not update

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);

How to get the Spinner value to save in a variable

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);
}
}
});

How To Display Specific Amount in Spinner?

I want to get information using putExtra() on another page and I can do it, but my only problem is always the default value the first value sample_array but i want to by default classDayIntent value is displayed in spinner
tip: The putExtra() received in Spinner is there
First Activity:
Intent intent = new Intent();
intent.putExtra("className" , className);
intent.putExtra("uniName" , uniName);
intent.putExtra("classDay" , classDay);
intent.setClass(context , AddNewClass.class);
context.startActivity(intent);
Second Activity:
Spinner spinner = (Spinner)findViewById(R.id.spinnerDay);
String className = getIntent().getStringExtra("className");
String uniName = getIntent().getStringExtra("uniName");
String classDayInent = getIntent().getStringExtra("classDay"); // How To Display classDayInent In Spinner....
className_EditeText.setText(className);
uniName_EditeText.setText(uniName);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this , R.array.sample_array , android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String classDay = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Strings:
<resources>
<string name="app_name">ClassManager</string>
<string-array name="sample_array">
<item>شنبه</item>
<item>یکشنبه</item>
<item>دوشنبه</item>
<item>سه شنبه</item>
<item>چهارشنبه</item>
<item>پنجشنبه</item>
<item>جمعه</item>
</string-array>
you can use add function of adapter.
since CharSequence is an interface, and the String class implements CharSequence so you can directly add string to adapter
adapter.add(classDayInent);
spinner.setAdapter(adapter);
Another issue is , createFromResources creates a immutable list mean it cannot add more items.
Solution : create your own adapter with mutable list
List<String> list = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.sample_array)));
ArrayAdapter<String> adapter = new ArrayAdapter<>(this , android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
list.add(0,classDayIntent);// to add received element at first position to display
spinner.setAdapter(adapter);
You can get your xml arraylist and then add to that:
List<String> ar = new LinkedList<String>(Arrays.asList(getResources().getStringArray(R.array.sample_array)));
ar.add("test");
i found correct answer :
String classDayInent = getIntent().getStringExtra("classDay");
List<String> list = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.sample_array)));
ArrayAdapter<String> adapter = new ArrayAdapter<>(this , android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
//find classDayIntent from List For get Position To Display
for (int i = 0; i < list.size(); i++)
{
if (classDayIntent.equals(list.get(i)))
{
spinner.setSelection(i);
}
}
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
classDay = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

Spinner 2 data not populating properly

I am trying to load spinner2 data based on spinner1 item selection. My spinner1 loads without any issues. I have got two categories in spinner1. Before selecting any value on spinner1, my spinner2 is loaded with second categories values.
EDIT:
One thing i realized now. i have got 2 values in spinner1(category). when nothing is selected in spinner1 , spinner2 is loaded with item2's values. if i select item1 in spinner1, it loads properly. If i select item2 in spinner1 nothing is populated in spinner2. Because of my hint addition there is some issue i think.
minimal spinner2 part in MainActivity
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
parent.getItemAtPosition(position).toString();
getSpinner2(id);
}
private void getSpinner2(Long id) {
MyRestClient.getForSpinner2(MainActivity.this, "MyRestService/product/"+id,
headers.toArray(new Header[headers.size()]), null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
ArrayList<String> spinnerArray2 = new ArrayList<String>();
final SpinnerAdapter2 spinnerAdapter2 = new SpinnerAdapter2(MainActivity.this, spinnerArray2);
for (int i = 0; i < response.length(); i++) {
try {
JSONObject c = response.getJSONObject(i);
String productArray = c.getString("product");
spinnerAdapter2.add(productArray);
}
catch (JSONException e) {
e.printStackTrace();
}
}
spinnerAdapter2.add("Select One");
spinner2.setAdapter(spinnerAdapter2);
spinner2.setSelection(spinnerAdapter2.getCount());
spinnerAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
and i have got this to show hint on spinneradapter2 class
#Override
public int getCount() {
int count = super.getCount();
return count > 0 ? count - 1 : count;
}
.
.
public View getView(int position, View convertView, ViewGroup parent) {
.
.
if (position == getCount()) {
viewHolder.product.setText("");
viewHolder.product.setHint(products);
} else {
viewHolder.product.setText(products);
}
}
Please try spinnerAdapter2.notifyDataSetChanged(); after adding all elements to your adapter. Maybe it will help. And I thik you should add this items to spinnerArray2 and then create adapter using this object.
You need to know that onitemselected will be called first time without user actions and since you are adding a hint you should check that position is larger than 0 which is the hint position if there is no hint then skip the check of zero position
so your new selection will be like
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position>0){
parent.getItemAtPosition(position).toString();
getSpinner2(position);
}
}
also
spinnerAdapter2.add("Select One");
call this before adding other values to the adapter to make sure it is in first location
Edit:
Put spinner2.setOnItemSelectedListener(MainActivity.this); inside spinner1 setOnItemSelectedListner.
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
parent.getItemAtPosition(position).toString();
spinner2.setOnItemSelectedListener(MainActivity.this);
Log.e("Position", ""+position);
if(position > 0){
getSpinner2(position);
} else {
Toast.makeText(getApplicationContext(), "Spinner oth postion is selected", Toast.LENGTH_SHORT).show();
}
}

Android: Pass iteration value to onItemSelectedListener

Hi I am creating a list of spinners dynamically based on a user choice. Here I am also implementing OnItemSelectedListener for each of the spinners, since there are multiple spinners I want to know which spinner's method is currently being accessed. Here's the code,
for (int i = 0; i < count; i++) {
ArrayList<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("one");
spinnerArray.add("two");
spinnerArray.add("three");
spinnerArray.add("four");
spinnerArray.add("five");
Spinner spinner = new Spinner(this);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Object item = parent.getItemAtPosition(position);
Log.d("vij-debug", "selector1 no is " + item);
Log.d("vij-debug", "selector1 id is"+ view.getId());
//medicineArray1[i][1]=(String)item;
// here I want to access the iteration value i
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_dropdown_item,
spinnerArray);
spinner.setAdapter(spinnerArrayAdapter);
Can anyone suggest a suitable solution?
Set the Spinner's tag to i upon creation, then retrieve it from the AdapterView<?> parent parameter in onItemSelected().
Spinner spinner = new Spinner(this);
spinner.setTag(i);
...
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
int spinnerNumber = parent.getTag();
}
...
}
);
you could use a List and store your spinner there. in your for loop
//inside for loop
List<Spinner> spinnerList=new ArrayList<Spinner>();
Spinner spinner = new Spinner(this);
spinnerlist.add(spinner);
//end
//outside for loop
for(int i=0;i<spinnerList.size();i++){
setListenerToSpinner(spinnerList.get(i));
}
//end
//function
public void setListenerToSpinner(Spinner spinner){
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Object item = parent.getItemAtPosition(position);
Log.d("vij-debug", "selector1 no is " + item);
Log.d("vij-debug", "selector1 id is"+ view.getId());
//medicineArray1[i][1]=(String)item;
// here I want to access the iteration value i
}
}

Categories

Resources