Spinner OnItemSelectedListener Not Working - java

I am in the middle of creating an android app ...I have two Spinner drop down lists. it seems that I cannot get the OnItemSelectedListener to work properly. I get no errors when an item is selected , it just returns null..I spent all day trying to figure out what I did wrong..with no luck.
below is the relevent code.please let me know if you need any more code
//grab the user defined make and model for the listing search
spin_make = (Spinner) findViewById(R.id.spinr_make);
spin_model = (Spinner) findViewById(R.id.spinr_model);
//load the drop downs
ArrayAdapter<String> makeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, make_list);
spin_make.setAdapter(makeAdapter);
//set the item selected listener for the make drop down
spin_make.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
model_list.clear();
new LoadModelListsTask().execute();
ArrayAdapter<String> modelAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, model_list);
spin_model.setAdapter(modelAdapter);
_make = make_list.get(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

Related

without selecting how to pass the spinner value

Hi in the below code I have a edit button .If I am click on edit button setting the spinner values to the spinner .
click on edit button spinner value is setting the adapter.
String speclizations = getArguments().getString("speclization_name");
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, Specializationnames);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSpecialization.setAdapter(dataAdapter1);
if(spinnerSpecialization.getSelectedItem().equals(0)){
speclizations = getArguments().getString("speclizations");
Log.d("salutation_names",salutation_names);
}else {
speclizations=spinnerSpecialization.getSelectedItem().toString();
}
Same value I am passing after click on save button I am passing the spinner value without selecting want to pass the same value.but it is throwing an error.
spinner.getslecteditem().toString();//null
Can any one help me how to resolve the issue.
Try this
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
if(spinner.getslecteditem().equals(0))
{
//Display a toast message to select any values from the Spinner
}
else {
str = spinner.getslecteditem().toString();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});

OnClickListener doesn't work as expected

I have one screen with two spinners. The choices in the second spinner depend on the user choice in the first spinner.
Here is my code:
For the first spinner:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.oman_states));
final MaterialBetterSpinner materialDesignSpinner = (MaterialBetterSpinner)
findViewById(R.id.states_list); // states spinner
materialDesignSpinner.setAdapter(arrayAdapter);
for the second spinner:
final MaterialBetterSpinner materialDesignSpinner2 = (MaterialBetterSpinner)
findViewById(R.id.hospitals_list);
and I implemented the following listener in the second spinner:
materialDesignSpinner2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (materialDesignSpinner.getText().toString() == getString(R.string.muscat)) {
ArrayAdapter<String> muscatHospitals = new ArrayAdapter<>(v.getContext(),
android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.muscat_hospitals));
materialDesignSpinner2.setAdapter(muscatHospitals);
} else if (materialDesignSpinner.getText().toString() == getString(R.string.albatna)) {
ArrayAdapter<String> albatnaHospitals = new ArrayAdapter<>(v.getContext(),
android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.albatan_hospitals));
materialDesignSpinner2.setAdapter(albatnaHospitals);
} else if (materialDesignSpinner.getText().toString() == getString(R.string.musandam)) {
ArrayAdapter<String> smaelHospitals = new ArrayAdapter<>(v.getContext(),
android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.musandam_hospitals));
materialDesignSpinner2.setAdapter(smaelHospitals);
} else if (gm.spinnerChecking(materialDesignSpinner)) {
Toast.makeText(v.getContext(), getString(R.string.choose_state_first), Toast.LENGTH_LONG).show();
}
System.out.println("Working");
}
});
when I press on the spinner, the application crashes
showing the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Filter.filter(java.lang.CharSequence,
android.widget.Filter$FilterListener)' on a null object reference
at
android.widget.AutoCompleteTextView.performFiltering(AutoCompleteTextView.java:971)
at
com.weiwangcn.betterspinner.library.material.MaterialBetterSpinner.onFocusChanged(MaterialBetterSpinner.java:49)
how can I make the second spinner choices based on the first spinner?
UPDATE:
after applying #dominicoder solution, the onItemSelected is not executed for some reason because System.out.println() doesn't print "work" to the console.
Here is the code for the onItemSelected :
materialDesignSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
secondSpinnerAdapter.clear();
secondSpinnerAdapter.addAll(getStringsForPosition(position));
System.out.println("works");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
A couple of things:
Do NOT do string comparisons using == in Java. Use String.equals()
Use the position of the selection of the first spinner to determine what to show, not the text that happens to be showing in that position.
You should update the state of the second spinner in response to the changing of the state of the first spinner, not checking the first spinner state when it's time to show something in the second spinner
You should create just one adapter for your second spinner that you update as needed, instead of creating a new instance each time.
With these suggestions in mind, I would recommend something more like this:
// Second adapter is a class field
private ArrayAdapter<String> secondSpinnerAdapter;
// Initialize it ONCE in onCreate with no items to begin with
secondSpinnerAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line);
materialDesignSpinner2.setAdapter(secondSpinnerAdapter);
// When something is selected in the first adapter,
// update the options in the second adapter
materialDesignSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
secondSpinnerAdapter.clear();
secondSpinnerAdapter.addAll(getStringsForPosition(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
private String[] getStringsForPosition(int position) {
switch(position) {
case 0: return getResources().getStringArray(R.array.musandam_hospitals);
// Add other cases
}
}
This eliminates string equality checks, removes duplication, and makes the intent "when something in the first spinner is a selected, update the options in the second spinner" much clearer.
Hope that helps!
you shouldn't set an on click listener. instead of that do this
materialDesignSpinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

Trouble adding a Spinner in Android Studio

KEEPING FOR HISTORIC. SKIP TO EDIT.
I am having trouble adding a spinner to an android app I'm developing. I haven't developed the code yet to go in the app, but just to do some testing I have it sending a toast message to let me know it works. According to this page: http://developer.android.com/guide/topics/ui/controls/spinner.html You can use User to create events by having OnItemSelected be called in another class.
public class SpinnerActivity extends EditJobActivity implements AdapterView.OnItemSelectedListener {
#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)
Toast.makeText(SpinnerActivity.this, "It worked", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
That's it's own class. I call it with this:
//Prepare the first (Job Discovery) spinner
Spinner mJobDiscovery = (Spinner) findViewById(R.id.SpinJobDiscovered);
// Create an ArrayAdapter using the string array and a default spinner layout
JobDiscoveryAdapter = ArrayAdapter.createFromResource(this,
R.array.spin_JobDiscoveryHome, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
JobDiscoveryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
mJobDiscovery.setAdapter(JobDiscoveryAdapter);
mJobDiscovery.setOnItemSelectedListener(this);
However, I get this error:
SetOnItemSelectedListener(android...) in AdapterView cannot be applied to (com...Activity)
It asks me to cast it to (AdapterView.OnItemSelectedListener) but when I do I get errors because I can't cast the activity to an OnItemSelectedListener. What am I missing here? I'm a bit new to Android Programming, so I'm sorry if this is an easy answer...
EDIT:
After speaking with Bhush_techidiot, he sent me to some resources that helped, however I'm having trouble finalizing my implementation. Now my SpinnerActivity temporarily looks like this:
public class SpinnerActivity extends EditJobActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_job);
/*for fill your Spinner*/
List<String> SpinnerArray = new ArrayList<String>();
SpinnerArray.add("Item 1");
SpinnerArray.add("Item 2");
SpinnerArray.add("Item 3");
SpinnerArray.add("Item 4");
SpinnerArray.add("Item 5");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, SpinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner) findViewById(R.id.SpinJobDiscovered);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Object item = arg0.getItemAtPosition(arg2);
if (item != null) {
Toast.makeText(EditJobActivity.this, item.toString(),
Toast.LENGTH_SHORT).show();
}
Toast.makeText(EditJobActivity.this, "Selected",
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
but I don't know how to call SpinnerActivity from my EditJobActivity, so I'm getting the error: "... is not an enclosing class" on EditJobActivity. Should I be making a new layout for this spinner?
Check the following links. Make sure you keep your solutions as simple as you can also don't hesitate to try complicated things once you get the simple one working :) Understand the extending and implementing classes and you are good to go!
Android Spinner - onItemSelected / setOnItemSelectedListener not triggering
setOnItemSelectedListener of Spinner does not call
How to get the value of a selected item in a spinner?
All the best!

Select the items in Spinner dynamically through code

I am working on a project in which I need to dynamically add TextView and Spinner as well. I was able to add these two things dynamically from my program.
Now when I was trying to select some items in the Spinner, it was not selecting those items.
Does I need to do anything to make that item selected in Spinner?
for (Map.Entry<String, String> entry : mapColumns.entrySet()) {
spinnerArray = new ArrayList<String>();
final TextView rowTextView = new TextView(cont);
final Spinner spinner = new Spinner(cont);
rowTextView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
spinner.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
for(String s: entry.getValue().split(",")) {
System.out.println(s);
s = s.replaceAll("[^a-zA-Z0-9]+","");
spinnerArray.add(s);
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(cont, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
rowTextView.setText(entry.getKey());
rowTextView.setTypeface(null, Typeface.BOLD);
spinner.setAdapter(spinnerArrayAdapter);
layout.addView(rowTextView);
layout.addView(spinner);
}
Here mapColumns will hev Key-Value pair. So in the Spinner all the items are getting shown from the Value of that map.
Problem Statement:-
Now I need to make sure if anybody is selecting any items in the Spinner, it should get selected and visible to naked eye.
How can I do that based on my code. Thanks for the help.
Below is the image-
Try use this code :
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(con,
android.R.layout.simple_spinner_item, spinnerArray);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Add an OnItemSelectedListener to your spinner:
spinner.setAdapter(spinnerArrayAdapter);
// add the listener
spinner.setOnItemSelectedListener(this);
Then, implement the listener in your activity:
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
}

AdapterView not found [Spinner]

I'm currently on my first Spinner. But I kinda got stuck during the onItemSelectedListener, since I cannot implement it. I first tried to follow the method of CommonWares book but it would work - but my method now doesn't work either.
At first I tried to let my activity implement the AdapterView directly - but the only consequence was that eclipse told me that the interface AdapterView is not available and asked me to create it ... however I got the very same error now again.
public class Lunchplace extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mensa);
Context c = getApplicationContext();
Spinner dateSelection = (Spinner)findViewById(R.id.date);
//ArrayAdapter<String> aa = new ArrayAdapter<String>(this, android.R.)
// get all the little tidbits of extra informations
Bundle extras = getIntent().getExtras();
String location = extras.getString("Mensa");
// this function will download the Lunchfile - if necessary
Data lunchData = new XMLData(c);
// set the header text
TextView mensaname = (TextView)findViewById(R.id.header);
mensaname.setText(location);
// get the spin view out of the xml
Spinner spin = (Spinner)findViewById(R.id.date);
// attach it to an adapter
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, R.array.days, android.R.layout.simple_spinner_item);
// I should be able to put a custom layout of the spinner in there.. I bet
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
spin.setOnClickListener(
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
);
// set the current day of the week as the default selection
spin.setSelection(Tools.getDayOfWeek());
// get the tablelayout
TableLayout tl = (TableLayout)findViewById(R.id.MenuTable);
lunchData.getMenuforDay(c,tl,location);
TextView counterTV = new TextView(c, null, R.style.MenuField);
}
}
Does anybody have any Idea on how I can solve that problem?
There is nothing special with implementing the OnItemSelectedListener. Try smth like this:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if ("YourDayToHandle".equals(spinner.getSelectedItem())) {
// do smth useful here
}
}
public void onNothingSelected(AdapterView<?> parent) {}
});

Categories