Spinner onClick listener - java

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

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

Android: make a single item in a listview clickable [duplicate]

This question already has answers here:
Android - How to create clickable listview?
(5 answers)
Closed 8 years ago.
I currently have a ListView id=listview, which I am populating with an ArrayList id=myarraylist. Here is how I do it:
final ListView listview = (ListView) findViewById(android.R.id.list);
myarraylist = (ArrayList<String>) getArray();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mylist);
myarraylist.add(...And then some other stuff I add...);
//This is the part I want to focus on
myarraylist.add("Reset High Scores");
adapter.notifyDataSetChanged();
listview.setAdapter(adapter);
Now, I want the entry Reset High Scores in my ListView to be clickable, and when it is clicked, I want it to do Some Stuff. I know for buttons all you do is set an onClickListener
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
..Some Stuff..
}
});
My question is, how can I make Some Stuff happen when the element Reset High Scores is clicked in the ListView
Edit: This is what I have so far
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#Override
String myString = (String) parent.getAdapter().getItem(position);
if(myString.equals("Clear High Scores")) {
//Stuff
}
}
});
ListView, just like Button, has the ability to set a click listener, but for ListView, the name of the method is setOnItemClickListener(). Instead of using OnClickListener, though, it uses a class called OnItemClickListener, which is more advantageous for using with ListView. The method looks as follows:
yourListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id)
{
// some stuff
}
}
)
Now the advantage of this is that you can check what's contained at the position you've pressed, so the way you could tackle your problem could look something like this:
yourListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id)
{
String myString = (String) parent.getAdapter().getItem(position);
if(myString.equals("Reset High Scores"))
{
// Do what you want
}
}
});
/**
* Creates a new instance
*/
public void onListItemClick(ListView l, View v, int position, long id) {
// Notify the parent activity of selected item
super.onListItemClick(l, v, position, id);
//Do stuff
}
that should get ya started... Andrew is right though.

Item being selected automatically from spinner?

my issue is that whenever I add a lecture to the array list in the next activity, it calls back to this activity and updates it. However, for some reason onItemSelected is called right away as soon as I get back to the calling activity and I'm sent to the Lecture activity (the displayLectureIntent is started right away) as soon as I get back to the calling activity without even actually selecting anything from the spinner.
Could it be that as soon as I add something to the spinner, the spinner chooses the first object as default and therefore it "selects" it? Thanks
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_class_manager0);
Intent receivedIntent = getIntent();
if (receivedIntent.hasExtra("lectureManagerExtra")) {
lectureManager = (LectureManager) getIntent().getSerializableExtra("lectureManagerExtra");
update();
} else {
lectureManager = new LectureManager();
}
}
public void update() {
Spinner spinner = (Spinner) findViewById(R.id.lecturespinner);
ArrayAdapter<String> lectureadapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_dropdown_item, lectureManager.getLectureNames());
lectureadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(lectureadapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "HEYYY", Toast.LENGTH_LONG).show();
Intent displayLectureIntent = new Intent(getBaseContext(), LectureActivity.class);
displayLectureIntent.putExtra("lectureExtra",
lectureManager.returnLecture(adapterView.getItemAtPosition(position).toString()));
startActivity(displayLectureIntent);
}
#Override
public void onNothingSelected(AdapterView<?> adapter) {}
});
}
please add "select" string on lectureManager.getLectureNames() array at the top
so that the array's size is increased by 1
And setSelectedIndex to 0 .
and
modify onItemSelected method as followings
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "HEYYY", Toast.LENGTH_LONG).show();
Intent displayLectureIntent = new Intent(getBaseContext(), LectureActivity.class);
displayLectureIntent.putExtra("lectureExtra",
lectureManager.returnLecture(adapterView.getItemAtPosition(position).toString()));
**if(position !=0){
startActivity(displayLectureIntent);
}
else{
Toast.makeText(getApplicationContext(), " select the lecture.", Toast.LENGTH_LONG).show();**
}
}

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 to Get user input from a Text Entry Box in Android?

in an android website, I found an article about how to create a text entry widget that provides auto-complete suggestions. (Following is the link to the site; and it shows all the codes).
http://developer.android.com/resources/tutorials/views/hello-autocomplete.html
Can anyone please tell me how I can capture the input entered by the user? For example, if the user chooses “Canada”, is there a way I can know the result in the “HelloAutoComplete.java” activity? Any help would be greatly appreciated.
public class HelloAutoComplete extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
String[] countries = getResources().getStringArray(R.array.countries_array);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, countries);
textView.setAdapter(adapter);
textView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (adapterView.getItemAtPosition(i).toString().equals("Canada")) {
Toast.makeText(getApplicationContext(), "Result Canada", Toast.LENGTH_SHORT).show();
} //Does not get an out put when I select Canada.
}
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
} }
textView.getText();
textView.getText().toString(); // If you need an actual String
Currently your code does not hook up the listener to the text view.
You need to either (a) use an immediate listener:
textView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (adapterView.getItemAtPosition(i).toString().equals("Canada")) {
Toast.makeText(getApplicationContext(), "Result Canada", Toast.LENGTH_SHORT).show();
}
}
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Or (b) if you want to use the activity as the listener (I wouldn't) have it implement the interface and set the itemSelectedListener to this. But yuck.
To set the selected text into another text element, a few changes must be made. First, the layout must now include the autocomplete "component", and the additional text view. We set the "parent" layout to vertical orientation, create a new horizontal layout for the autoselect stuff, and add a new text view.
<LinearLayout xmlns:a="http://schemas.android.com/apk/res/android"
a:orientation="vertical"
a:layout_width="fill_parent"
a:layout_height="wrap_content"
a:padding="5dp">
<LinearLayout a:orientation="horizontal"
a:layout_width="fill_parent"
a:layout_height="wrap_content">
<TextView a:layout_width="wrap_content"
a:layout_height="wrap_content"
a:text="Country"/>
<AutoCompleteTextView a:id="#+id/autocomplete_country"
a:layout_width="fill_parent"
a:layout_height="wrap_content"
a:layout_marginLeft="5dp"/>
</LinearLayout>
<TextView a:id="#+id/selected_country"
a:layout_height="wrap_content"
a:layout_width="fill_parent"/>
</LinearLayout>
The activity gets a new TextView instance property, which I'm calling selectedCountry. I'm not showing its declaration. The onCreate method looks it up by ID, and the select listener just updates it.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Text view for selected country.
selectedCountry = (TextView) findViewById(R.id.selected_country);
textView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
selectedCountry.setText(adapterView.getItemAtPosition(i).toString());
}
public void onNothingSelected(AdapterView<?> adapterView) { }
});
}
The best way would be to set an "item selected listener" which will notify you when the user has picked something from the available entries. See the docs. With this you can get the item from the adapter that they picked (and, conversely, whatever you defined for that item's text).
Example:
textView.setOnItemSelectedListener( new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View selectedView,
int selectedPosition, long selectedId) {
//do stuff here
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
Try this:
textView.getText().toString();
Then display it through Toast.
Use :
textView.getText().toString()

Categories