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) {
}
});
Related
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) {
}
});
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();
}
});
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) {
}
});
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();**
}
}
I would like to take the value of a spinner and convert it to a String to play about with.
Spinner s1 = (Spinner)findViewById(R.id.spinner1);
s1.setOnItemSelectedListener((OnItemSelectedListener) this);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.languages, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
I thought somthing like this would work....
private OnClickListener sendClickListener = new OnClickListener(){
public void onClick(View arg0) {
EditText dstName = (EditText) findViewById(R.id.destinationAddress);
EditText dstLanguage = (EditText) findViewById(R.id.spinner1);
String address = dstName.getText().toString();
String language = dstLanguage.getText().toString();
ops.createSocketConnection(language, address);
Notification notification = new Notification();
notification.vibrate = new long[] {100};
}};
Allas it does not....
I have looked at a few examples however I am not sure If they are directly related to my question.
Thanks in advance!
Try this:
OnItemSelectedListener itemSelectedHandler = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long row) {
String str = parent.getItemAtPosition(pos).toString();
// Do whatever you want with the string
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// Do nothing
}
};
//set the spinner's listener for select event
mSpinner.setOnItemSelectedListener(itemSelectedHandler);
Hmm, I'm not entirely sure what the question is, but if the issue is getting the value of a spinner, check out Spinner data to string:
You can use getSelectedItem to
get the currently selected item. If
you've bound to an
ArrayAdapter<String>, this will
be the value.
Of course, in this instance you're returning CharSequence, so you'd do
String strVal = getSelectedItem().toString();
Hope this helps,
Phil Lello