Trouble adding a Spinner in Android Studio - java

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!

Related

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

Spinner OnItemSelectedListener Not Working

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

Affect Second Spinner Choices based on First Spinner

So I can see that there are questions about this, but not in the scope of mine. I am buliding an app for Android that has two spinners. The first has an array of choices. However, I am not sure how to affect what choices the second one has based on the first one. I know that you can put in
AdapterView.OnItemSelectedListener
but I'm not sure how to implement this. I've read on this but it's not quite what I'm looking for. I'm also curious as to how I tell the spinner which array to choose, is it in the .xml or in the .java file?
Try this,
firstSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
string selectedValue = arg0.getSelectedItem().toString();
if(selectedValue.equalsIgnoreCase(string1)
{
ArrayAdapter<String> firstAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, firstArray);
secondSpinner.setAdapter(firstAdapter);//
}
else if(selectedValue.equalsIgnoreCase(string2)
{
ArrayAdapter<String> firstAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array2);
secondSpinner.setAdapter(firstAdapter);
}
}
Hope it will help you.
If it's a String array you could define it in XML then use getResource().getStringArray() or declare it in Java.
In your listener for the first spinner, you could do the following to set the choices for the second spinner.
secondSpinnerAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, newArray);
secondSpinner.setAdapter(secondSpinnerAdapter);
Tested and working
update the array list of second spinner in 1st spinner setOnItemSelectedListener
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
string str=spinner1.getSelectedItem().toString();
if(str.equals("spinner item"))//spinner item is selected item of spinner1
{
ArrayAdapter<String>adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, array1);
//adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner2.setAdapter(adapter1);//
}else if{
ArrayAdapter<String>adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array2);
//adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner2.setAdapter(adapter2);
}
}

How should i refresh my AutoCompleteTextView component?

I'm using this block of code:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Cidade cidade = (Cidade) arg0.getSelectedItem();
List<Bairro> bairros = RachandoTaxiController.getInstancia().getBairros(cidade);
myAutoComplete = (AutoCompleteTextView) getView().findViewById(R.id.completeOrigem);
myAutoComplete.addTextChangedListener(textWatcher);
myAutoComplete.setAdapter(new ArrayAdapter<Bairro>(getActivity(), android.R.layout.simple_dropdown_item_1line, bairros));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
There i have a Spinner and when i select an Item, i should set my AutoCompleteTextView (from holoeverywhere) based on user choice of Spinner.
If i do it statically, it works. My autocompletetextview answer as expected. But when i put it into onItemSelected, my autocompletetextview still like edittext.... Nothing happens...
How can i solve it?
I think you should put
myAutoCompl = (AutoCompleteTextView) getView().findViewById(R.id.completeOrigem);
myAutoComplete.addTextChangedListener(textWatcher);
these lines outside of OnItemClickListener.
Whenever you click on item, new instance of View from findViewById() is returned. Same for TextChangedListener. So try to put lines outside probably the best choice will be onCreate() method and it should works.

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