I have a Spinner with list of category, which get the data from JSON. I want to make, when an item other than All Category get selected, another spinner of subcategory become visible, and get loaded with data from JSON according to its category.
Previously I managed to do it but after left it for a few days and have other parts done, it no longer works.
Since the first one loaded into spinner is All Category, it triggered setOnItemSelectedListener() and hid subcategorySpinner. If other item get selected, subcategorySpinner still not shown.
Is there something wrong with the code logic? Please help.
categorySpinner = (Spinner) rootView.findViewById(R.id.categorySpinner);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.spinner_item, categoryList);
adapter2.setDropDownViewResource(R.layout.spinner_dropdown_item);
categorySpinner.setAdapter(adapter2);
categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
categoryString = categorySpinner.getSelectedItem().toString().replace(" ", "%20");
if (categorySpinner.getSelectedItem().toString().equals("All Category")) {
Log.d("debug", "all category");
subcategorySpinner.setVisibility(View.GONE);
} else {
Log.d("debug", "other than all category");
subcategorySpinner.setVisibility(View.VISIBLE);
generateSubcategorySpinner(Config.GET_SUBCATEGORY_URL+"?category="+categoryString);
}
}
});
change your code to
categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
categoryString = parent.getItemAtPosition(position).toString();
Log.d("debug", categoryString+"..."+position);
if (categoryString.equals("All Category")) {
Log.d("debug", "all category");
subcategorySpinner.setVisibility(View.GONE);
} else {
Log.d("debug", "other than all category");
subcategorySpinner.setVisibility(View.VISIBLE);
categoryString = categoryString.replace(" ", "%20")
generateSubcategorySpinner(Config.GET_SUBCATEGORY_URL+"?category="+categoryString);
}
}
Try this code snippet
Spinner dropdown = (Spinner) findViewById(R.id.type);
final String[] items = new String[]{"SELECT TYPE OF OFFER","PERCENTAGE", "AMOUNT", "ITEM"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.spinner_item, items);
dropdown.setAdapter(adapter);
String selectedItem = dropdown.getSelectedItem().toString();
try this
categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
categoryString = parent.getItemAtPosition(position).toString().replace(" ", "%20");
if (categoryString.equals("All Category")) {
Log.d("debug", "all category");
subcategorySpinner.setVisibility(View.GONE);
} else {
Log.d("debug", "other than all category");
subcategorySpinner.setVisibility(View.VISIBLE);
generateSubcategorySpinner(Config.GET_SUBCATEGORY_URL+"?category="+categoryString);
}
}
You can direcly use the, argument(position)
Instead of,
categoryString = parent.getItemAtPosition(position).toString();
You can use like,
categoryString = position.toString();
Well I don't quite get what I have done logically because it seems nothing much different but this solved it. Oh well.. whatever floats the boat, I guess.
Using suggestion by H Raval, I moved the if else into a method and now it works just like I wanted.
categorySpinner = (Spinner) rootView.findViewById(R.id.categorySpinner);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.spinner_item, categoryList);
adapter2.setDropDownViewResource(R.layout.spinner_dropdown_item);
categorySpinner.setAdapter(adapter2);
String str = categorySpinner.getSelectedItem().toString();
Log.d("debug", "str "+str);
categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
categoryString = parent.getItemAtPosition(position).toString();
Log.d("debug", categoryString+"..."+position);
subCategorySpinnerView(categoryString);
}
});
private void subCategorySpinnerView(String categoryString) {
if (categoryString.equals("All Category")) {
Log.d("debug", "all category");
subcategorySpinner.setVisibility(View.GONE);
} else {
Log.d("debug", "other than all category");
subcategorySpinner.setVisibility(View.VISIBLE);
categoryString = categoryString.replace(" ", "%20");
generateSubcategorySpinner(Config.GET_SUBCATEGORY_URL+"?category="+categoryString);
}
}
Related
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_listview);
myspinner = (Spinner)findViewById(R.id.spinnertype);
String provider = myspinner.getSelectedItem().toString();
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, type_arrays,R.layout.support_simple_spinner_dropdown_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
myspinner.setAdapter(adapter);
myspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Toast.makeText(parent.getContext(), "OnItemSelectedListener :" + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
i tried different kinds of toast but still it wont appear. what went wrong?
I viewed some posts and it says i cant use onclicklistener to a spinner
Have yout try this, that might help you
Toast.makeText(getApplicationContext(), "OnItemSelectedListener :" + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_SHORT).show();
or
Toast.makeText(YourActivity.this, "OnItemSelectedListener :" + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_SHORT).show();
Try using getContext() instead of getApplicationContext.
Ok, Let's check the codes again ;
Like i said, You'll need to use the current Activity Context.
For example, My Activity name is, MainActivity so, Use:
MainActivity.this This should be the context of that Activity.But i
think if you use your own code(parent.getContext()) inside the another
activity, It won't show up because it's somewhere else actually you
know
Also, You did something wrong here i guess (Something similiar : ArrayAdapter.createFromResource issue)
I just quote the answer:
Query the data, put it in a List or Array and use this constructor of
ArrayAdapter:
ArrayAdapter<CharSequence> dataAdapter1 = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, yourArrayOrList);
Update: So here it is:
Spinner myspinner = (Spinner)findViewById(R.id.spinnertype);
String provider = myspinner.getSelectedItem().toString();
ArrayAdapter<CharSequence> adapter =
new ArrayAdapter<CharSequence>(this, type_arrays, R.layout.support_simple_spinner_dropdown_item);
/*ArrayAdapter.createFromResource(this, type_arrays,R.layout.support_simple_spinner_dropdown_item);*/
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
myspinner.setAdapter(adapter);
myspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Toast.makeText(MainActivity.this, "OnItemSelectedListener :" + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Now it should work!
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();
}
}
Finally, solved it. This is the code . I just added a method for second spinner on setOnItemSelectedListner of first spinner. Now i can select a value in first spinner and corresponding value will come to second spinner like i have colleges in first spinner and when i select a college in first spinner second spinner will automatically give value corresponding to first spinner
mSpinnerModel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedModel = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected Model: " + selectedModel, Toast.LENGTH_LONG).show();
//method for second spinner
String sp1=String.valueOf(mSpinnerModel.getSelectedItem());
if(sp1.contentEquals("College1")){
List<String> list = new ArrayList<String>();
list.add("MAHARANI UNIVERSITY ");
list.add("MANIPAL ");
list.add("ITM UNIVERSITY ");
list.add("UNIVERSITY1");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item,list);
mSpinnerMake.setAdapter(dataAdapter);
}
selectedMake = parent.getItemAtPosition(position).toString();
if(sp1.contentEquals("College2")){
List<String> list = new ArrayList<String>();
list.add("ITM UNIVERSITY");
list.add("UNIVERSITY2");
list.add("UNIVERSITY3");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_dropdown_item,list);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter2.notifyDataSetChanged();
mSpinnerMake.setAdapter(dataAdapter2);
}
if(sp1.contentEquals("College3")){
List<String> list = new ArrayList<String>();
list.add("MANIPAL ");
list.add("UNIVERSITY4");
list.add("UNIVERSITY5");
ArrayAdapter<String> dataAdapter3 = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_dropdown_item,list);
dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter3.notifyDataSetChanged();
mSpinnerMake.setAdapter(dataAdapter3);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I have activity with 3 spinners and selection of 1st spinner is related to 2nd and 2nd selection is related to the 3rd, so I have the spinner code one inside one.
CrustSp, SizeSp and extraDescriptionOneSP are the 3 spinners I have. I have loaded the items to the Spinners and I can select a value as well. But my problem is whenever i made a selection in CrustSp and SizeSp doesn't show in MyOnItemSelectedListener(). But if I made a selection in extraDescriptionOneSP it shows inside MyOnItemSelectedListener().
I can't figure where I have gone wrong, anyone can point out where I have gone wrong it will be really helpful.
This the code
crust = Utils.removeDuplicatesFromList(crust);
ArrayAdapter<String> dataAdapterCru = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, crust);
dataAdapterCru
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
crustSP.setAdapter(dataAdapterCru);
crustSP.setOnItemSelectedListener(new MyOnItemSelectedListener(
ActivityPizzaCustomize.this) {
public void onNothingSelected(AdapterView<?> arg0) {
}
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
String crustSelectedItem = crustSP.getSelectedItem()
.toString();
List<String> resultSizes = getFilteredSizes(crustSelectedItem);
ArrayAdapter<String> dataAdapterDes = new ArrayAdapter<String>(
ActivityPizzaCustomize.this,
android.R.layout.simple_spinner_item,
resultSizes);
dataAdapterDes
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sizeSP.setAdapter(dataAdapterDes);
sizeSP.setOnItemSelectedListener(new MyOnItemSelectedListener(
ActivityPizzaCustomize.this) {
public void onNothingSelected(AdapterView<?> arg0) {
}
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
String sizeSelectedItem = sizeSP
.getSelectedItem().toString();
List<String> resultTopping = getFilteredToppings(sizeSelectedItem);
extraDescriptionOneSP
.setOnItemSelectedListener(new MyOnItemSelectedListener(
ActivityPizzaCustomize.this));
ArrayAdapter<String> dataAdapterExtraDesOne = new ArrayAdapter<String>(
ActivityPizzaCustomize.this,
android.R.layout.simple_spinner_item,
resultTopping);
dataAdapterExtraDesOne
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
extraDescriptionOneSP
.setAdapter(dataAdapterExtraDesOne);
extraDescriptionOneSP
.setAdapter(new NothingSelectedSpinnerAdapter(
dataAdapterExtraDesOne,
R.layout.contact_spinner_row_nothing_selected,
ActivityPizzaCustomize.this));
}
});
}
});
MyOnItemSelectedListener method,
public class MyOnItemSelectedListener implements OnItemSelectedListener {
Activity activity;
String StrOneSPPosition;
public MyOnItemSelectedListener(Activity p_activity) {
activity = p_activity;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// check which spinner triggered the listener
switch (parent.getId()) {
case R.id.sp_crust: {
String StrCrustSPPosition = String.valueOf(crustSP
.getSelectedItemPosition());
System.out.println("crust = " + StrCrustSPPosition);
System.out.println("crust = " + position);
CrustSPPosition = Integer.parseInt(StrCrustSPPosition);
}
I don't see you using the selected position to determine the data for next spinner. BTW you should not make new adapter for each selection, instead reuse the once made adapter.
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
}
}