AdapterView not found [Spinner] - java

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

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 onClick listener

I would like to call an action every time my spinner selects a new item. The current setup is that an action is called when a button is pressed.
My approach:
Create a new function: public void onSpinnerItemSelection(View V){...}
Then in content_home.xml I would add onSpinnerItemSelection to onClick for Spinner.
This isn't working. I'm not familiar with Android errors and I'm struggling to interpret these errors.
Unfortunately, myApp has stopped
Caused by: java.lang.RuntimeException: Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead
Step by step:
1ªDeclare variables from the layoutSpinner sp; the arraylist in this case ArrayList listTeams; and the adapter Adapter adapter;
2ªinstances
private void instances() {
sp = (Spinner) findViewById(R.id.spinner);
listaTeam = new ArrayList();
3º add items for the adapter
private void listAdapter() {
listaTeam.add(new Equipo(R.string.Atleti));
adaptador = new Adaptador(MainActivity.this, listaEquipo);
sp.setAdapter(adapter);
now we make actions, use onItemSelected.
public void onItemSelected(AdapterView parent, View view, int position, long id) {
Toast.makeText("this is my team", Toast.LENGTH_LONG).show();
}
https://www.youtube.com/watch?v=H3W0-Nv664I
Here is an example:
mSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Toast.makeText("log", "position = " position, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText("log", "onNothingSelected", Toast.LENGTH_LONG).show();
}
});

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!

getting unfortunately stopped error when i define onItemSelectedListener

I really can't understand what is the problem.
This running very well.
super.onCreate(savedInstanceState);
setContentView(R.layout.select);
Resources r = getResources();
values = r.getStringArray(R.array.values);
sSelect = (Spinner) findViewById(R.id.sSelect);
tvSelect = (TextView) findViewById(R.id.tvSelect);
But this isn't working.
super.onCreate(savedInstanceState);
setContentView(R.layout.select);
Resources r = getResources();
values = r.getStringArray(R.array.values);
sSelect = (Spinner) findViewById(R.id.sSelect);
tvSelect = (TextView) findViewById(R.id.tvSelect);
sSelect.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
});
I really want to know what is the problem. Also how can i know what is the problem? There is no error reporting in android programming?
EDIT: setOnItemClickListener cannot be used with a spinner Which listener can i use with spinner? I don't want to use onItemSelectedListener because It run when app start.
You have to use the onItemSelectedListener for the Spinner. Then, use the item[0] value as "not selected" or something like that. When you want to call the dialog, write something like:
if(item[position] > 0)
{
//start dialog
}
Just guessing, but chances are you have a typo in sSelect resource name, and a NullPointerException when calling setOnItemClickListener.
Double check there's a Spinner named sSelect in your select layout.
EDIT
The right listener for Spinner is.-
AdapterView.OnItemSelectedListener
sSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, android.view.View v, int position, long id) {
}
public void onNothingSelected(AdapterView<?> parent) {
}
});

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.

Categories