Android Spinner: Cannot selected - android

I have the code, which unfortunately does not work as it should. More specifically, we can not choose from the second spinner. Here is the code. Thank you in advance for your help.
public class Zamiana extends Activity {
public Spinner spinner1;
public Spinner spinner2;
final ArrayList<Spanned> kon = new ArrayList<Spanned>();
[...]
spinner1 = (Spinner) findViewById(R.id.test);
spinner2 = (Spinner) findViewById(R.id.test2);
ArrayList<Spanned> adapter = new ArrayList<Spanned>();
adapter.add(Html.fromHtml("t0"));
adapter.add(Html.fromHtml("t1"));
adapter.add(Html.fromHtml("t2"));
[...]
ArrayAdapter<Spanned> kontrol = new ArrayAdapter<Spanned>(this,
android.R.layout.simple_spinner_item, adapter);
kontrol.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(kontrol);
spinner1.setOnItemSelectedListener(wyznacz);
spinner1.setOnItemSelectedListener(wyznacz);
ArrayAdapter<Spanned> kontrola = new ArrayAdapter<Spanned>(this,
android.R.layout.simple_spinner_item, kon);
kontrola.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(kontrola);
}
public OnItemSelectedListener wyznacz=new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
switch(arg2){
case 0:
kon.clear();
kon.add(Html.fromHtml("t0"));
break;
case 1:
kon.clear();
kon.add(Html.fromHtml("t1"));
break;
case 2:
kon.clear();
kon.add(Html.fromHtml("t2"));
break;
[...]
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
Thanks you very much for all help :)

For the spinners I have created I have only used three methods that I would override (onCreate, onItemSelected, onNothingSelected). I am confused why you have an OnItemSelected Listener above your onItemSelected Method since the onItemSelected Method is called when an item is selected.
It's not the best answer and more detail of what your spinner is suppose to achieve would be great but having the onItemSelected Method within an OnItemSelected Event Listener just seems to kind of stand out above everything else.
Hope this helps or points you in the right direction. Good Luck! plus post more code and details about your spinner.

Related

Android dependent spinners - onItemSelected does not fire

I tryed to create two dependent spinners. I know there is more than enough of this type of question, but nothing fixed my problem. It seems onItemSelected does not fire at all. I want the second (townships_spinner) change when first spinner (divisions_spinner) is selected or changed. Let's say I have states and cities, when I select the state a want to display only cities from given state. Spinners are created dynamicaly.
That's my code:
public class RegistrationActivity extends Activity implements AdapterView.OnItemSelectedListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
createLayout();
}
public void createLayout(){
division_spinner = new Spinner(this);
ArrayAdapter division_adapter = new ArrayAdapter(this,R.layout.spinner,divisions.getList());
divisions_id = viewer.getValueByKey(viewer_form.getViewers_form_viewers_inputname());
division_spinner.setAdapter(division_adapter);
division_spinner.setSelection(divisions.getIndex(divisions_id));
division_spinner.setOnItemSelectedListener(this);
township_spinner = new Spinner(this);
ArrayAdapter township_adapter = new ArrayAdapter(this,R.layout.spinner,townships_map.get(divisions_id));
if (divisions_id == null) {
township_spinner.setEnabled(false);
}
String value = viewer.getValueByKey(viewer_form.getViewers_form_viewers_inputname());
township_spinner.setSelection(townships.getIndex(value, divisions_id));
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Toast.makeText(RegistrationActivity.this, "Yes",Toast.LENGTH_LONG);
if(arg0.equals(division_spinner)) {
Toast.makeText(RegistrationActivity.this, "Yes - You got it!",Toast.LENGTH_LONG);
township_spinner.setEnabled(true);
ArrayAdapter township_adapter = new ArrayAdapter(this, R.layout.spinner, townships_map.get(((Division)division_spinner.getSelectedItem()).getDivisions_id().toString()));
township_spinner.setAdapter(township_adapter);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}
But "Yes" even "Yes - you got it!" toast does not appear.
I guess I miss something stupid, but I cant find it.
you're implementing AdapterView.onItemSelected.
...Just try this instead
Spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Toast.makeText(topThis, "selected", Toast.LENGTH_LONG).show();
//Call other spinner here to update.
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText(topThis, "nothing selected", Toast.LENGTH_LONG).show();
}
});
Edit: as Prasad says. If you don't have setContentView(View); your activity won't have an xml to inflate, so your views will never get created into anything.
I made a series of mistakes that led to the fact that it did not work as I expected.
First: I forgot to call **show()** on Toast.makeText()
Second: I make a huge mistake when creating ArrayList. I filled ArrayList with data, then I put the list to HashMap and after that I called ArrayList.**clear()**. Which led to override the HashMap values, and that was why it seemed, the spinner was not changing at all...
Well... I feel quite silly ...

Using Spinner to change layouts

Using the below code I want to simply change layouts upon spinner value selection. However, when my activity loads, the spinner never loads the values to be selected.
Oddly enough when I remove the code for (and everything below it)
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
the spinner values show up again.
public class ListCarsActivity extends Activity implements OnItemClickListener, OnClickListener, OnItemSelectedListener {
public static final String TAG = "ListCarsActivity";
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_cars);
spinner = (Spinner) findViewById(R.id.spinner3);
ArrayAdapter adapter= ArrayAdapter.createFromResource(this,R.array.domain,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
// initialize views
initViews();
}
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onItemSelected(AdapterView<?> arg0, View view,
int position, long row_id) {
switch(position){
case 1:
setContentView(R.layout.list_cars);
break;
case 2:
setContentView(R.layout.list_owners);
break;
}
setContentView(R.layout.list_cars);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
The spinner you are referring to is in your first activity. After you have replaced the content, the spinner isn't there anymore. If you have another spinner in the second layout, you have to reconnect it and set the listener again. Basically you have to run your onCreate stuff after every setContentView...
As a side note, whatever you are trying to do, this is probably not the way to go. To show another full layout, better use another activity.

Dialog Spinner does not return value

I have a dialog setup that has two spinners connected to a cursor. I have worked through a couple of problems with the help of this site, but I can not seem to get past this point. Everything I find are things I have already tried.
The problem is that when I click on a spinner selection or click Submit to exit the dialog, the spinner value is not the value it should be. I am getting the package name with some code. I am trying to get the string from the spinner with .getSelectedItem().toString();
I currently have the code set up to use onItemSelected, but before that I tried to use the getItemSelected once Submit was clicked. Neither seem to work.
Here is the code for this section.
At the end the values are going into a textview. The value shown is "android.database.sqlite.sqliteCursor#414175e0"
Any ideas?
private void transfer() {
dialog = new Dialog(this, android.R.style.Theme_Holo_Light_Dialog_MinWidth);
dialog.setContentView(R.layout.transfer_dialog);
dialog.setTitle(R.string.transfer_accounts);
Button btnCancel = (Button)dialog.findViewById(R.id.btnCancel);
Button btnSubmit = (Button)dialog.findViewById(R.id.btnSubmit);
Cursor load_spinner = mDbHelper.spinnerAccounts();
startManagingCursor(load_spinner);
String[] columns = new String[] { RegisterDbAdapter.ACCOUNTS_ACCOUNT };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, load_spinner, columns, to);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerFrom = (Spinner)dialog.findViewById(R.id.spinnerFrom);
spinnerTo = (Spinner)dialog.findViewById(R.id.spinnerTo);
spinnerFrom.setAdapter(mAdapter);
spinnerTo.setAdapter(mAdapter);
dialog.show();
spinnerFrom.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View arg1, int arg2, long arg3) {
fromAccount = parent.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
spinnerTo.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View arg1, int arg2, long arg3) {
toAccount = parent.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
btnCancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
btnSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
tvFrom.setText(fromAccount);
tvTo.setText(toAccount);
dialog.dismiss();
}
});
}
You need two separate adapters for two spinners.
You are only using one... each time you make a selection, the adapter sets your selection to your choice ( for both of the spinners since you have the same adapter backing each one ).
Create a second adapter and things should work more like you expect.
Also, try this in your onItemSelected method (using the parameter names you show):
String fromAccount = parent.getItemAtPosition(arg2).toString();
I think you have to use your cursor to get the String you want. Arg2 should be the selected position. Use it to place your cursor to the right data row and use the getstring method of the cursor to get the string from the database column.
So I finally got it to work. Thanks for the suggestions, I really do appreciate them, but they didn't work for me. I am not sure why the code will not return the value, since the way I tried it supposedly works for others.
Anyway, I found a way to get my values by using 'Long arg3'. Since it holds the rowId of the value in the table, I used that to return the selection in the spinner. I am posting the code for this below.
Thanks again.
The code from the selected spinner:
spinnerFrom.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View arg1, int arg2, long arg3) {
getAccountName(arg3);
fromAccount = returnAccount;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
And here is the method I wrote to return the value I wanted. I put it a separate method because it is getting used from multiple spinners. The code:
private void getAccountName(long arg3) {
if (returnAccount != null){
returnAccount = null;
}
RegisterDbAdapter tAdaptor = new RegisterDbAdapter(this);
tAdaptor.open();
Cursor tCursor = tAdaptor.fetchAccount(arg3);
startManagingCursor(tCursor);
returnAccount = tCursor.getString(1);
}

Is there a way for a spinner option to open another spinner?

I want it where when someone clicks an option in a Spinner, it opens another spinner with more options. Also, is there a way for an "Other" option to open an EditText where someone can input their selection if theirs isn't available in the Spinner?
Example:
Spinner 1 has these options:
iOS
Android
And if they select iOS, another spinner comes up immediately where the options are all the iPhone versions. (i.e., titled "Which iPhone do you have?")
And if they select Android, it does the same thing, but with Android devices.
AND if their phone isn't on the second spinner, they type the model of their phone in.
How could I do this if I have the first spinner already in my code?
P.S., if needed, I can post the code for the first spinner, though it's pretty standard.
Basically build your second spinner programmatically depending on which option they choose. I'd add "other" to each second spinner. If they choose "other" then you can display the text box.
I hope this will be useful to you.
Try this Code...
public class MainActivity extends Activity {
Spinner sp1,sp2;
ArrayAdapter<String> adp1,adp2;
List<String> l1,l2;
int pos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l1=new ArrayList<String>();
l1.add("A");
l1.add("B");
sp1= (Spinner) findViewById(R.id.spinner1);
sp2= (Spinner) findViewById(R.id.spinner2);
adp1=new ArrayAdapter<String> (this,android.R.layout.simple_dropdown_item_1line,l1);
adp1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp1.setAdapter(adp1);
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
pos=arg2;
add();
}
private void add() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), ""+pos, Toast.LENGTH_SHORT).show();
switch(pos)
{
case 0:
l2= new ArrayList<String>();
l2.add("A 1");
l2.add("A 2");
adp2=new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_dropdown_item_1line,l2);
adp2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp2.setAdapter(adp2);
select();
break;
case 1:
l2= new ArrayList<String>();
l2.add("B 1");
l2.add("B 2");
adp2=new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_dropdown_item_1line,l2);
adp2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp2.setAdapter(adp2);
select();
break;
}
}
private void select() {
// TODO Auto-generated method stub
sp2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Test "+arg2, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}

Android custom listview, setOnItemSelectedListener not working

I'm just beginning Android development, and I'm working to get a Custom listview with a checkbox working. I've created a base class that extends Activity, Created an Adapter and overrode the getView() method to add the checkbox to the listview. I'm assuming I need to do this because I need something equivalent to didSelectRowIndexAtPath from Obj C to update my model. Please let me know if there's an alternate way of doing this too!
Now in my base class, I have the following code -
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout);
setContentView(R.layout.facilityscreen);
/* Static Data source */
facilityModel = new FacilityDataModel[2];
facilityModel[0] = new FacilityDataModel();
facilityModel[1] = new FacilityDataModel();
facilityModel[0].setFacilityName("Test 1");
facilityModel[0].setFacilityID("Facid0001");
facilityModel[0].setChecked(false);
facilityModel[1].setFacilityName("Test 2");
facilityModel[1].setFacilityID("Facid0002");
facilityModel[1].setChecked(true);
facilityListView = (ListView) findViewById(R.id.facilityListView);
FacilityScreenAdapter adapter = new FacilityScreenAdapter(this, facilityModel);
facilityListView.setAdapter(adapter);
myPatBtn = (Button) findViewById(R.id.myPatBtn);
myPatBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int i=0;
i++;
}});
facilityListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int i=0;
i++;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
My problem now is the setOnItemSelectedListener isn't getting called at all. Been struggling with this for a couple of hours now, and I can't figure out why it wouldn't get called at all.
Any help is much appreciated!
Thanks,
Teja.
I know this is an outdated answer but I'm going to write it just in case some other fellow who has the same "problem" bumps onto this page :
The solution to the above problem which is not a problem but just a misunderstanding is that the ListView.onItemSelected() event is fired up, upon :
1) Navigating through the emulators-cross handles or
2) as far-as my HTC-Hero is concerned, the rolling-action on the white little roller-ball.
You don't have to extend your activity explicitly to a ListActivity.
Here's my tiny little code which retrieves a phone number from
a TextView control, inside a listview item.
When the user either touches the list item or scrolls through the list with
the little roller-ball the below Events, fire up and MakeACall() method is called :
myList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long i)
{
TextView myPhone = (TextView)view.findViewById(R.id.txtphone);
MakeACall(myPhone.getText().toString());
}
});
myList.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long i)
{
TextView myPhone = (TextView)view.findViewById(R.id.txtphone);
MakeACall(myPhone.getText().toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I hope that was helpful... :)
There exists already the possibility to have a ListView with checkboxes.
public class List11 extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, GENRES));
final ListView listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private static final String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
};
}
I've taken this from the APIDemos 'cause it was the simplest. You can then get the selected items by using:
long[] selectedIds = getListView().getCheckItemIds();
What you may also be interested in is the CheckedTextView which is used internally in the list.
To the part of the onListItemClick problem
Try to extend from ListActivity rather than Activity. Then override the onListItemClick. That should work.
use
setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// here you code
}
})
instead of setOnItemSelectedListener
As setOnItemSelectedListener is called when item is being selected not clicked so to get clicked item you must use setOnItemClickListener this will work
You should set all focusable items in custom list layout to false:
android:focusable="false"
also I think you should not use attributes like android:clickable="true" for them.
The lack of the item selected listener getting called is by design and is based on which mode the device is in. In touch mode, there is no focus and no selection. Your UI should use widgets that differentiate between touch for selection versus touch for scrolling. Radio buttons, for example, are good when there is a single selection choice.

Categories

Resources