I'm working with Android and Spinners and I need some help. I have a class that creates two spinners and a button. The first spinner is for my category, my second is for my sub-category. What I am trying to do is dynamically update the second spinner (spinner2). I've been trying to use adapter2.clear() but that crashes android, with an error "unable to start activity componentinfo unsupported operation"
Here is my code:
public class MyClass extends MyBaseClass
{
int category;
int sub_category;
ArrayAdapter<String> adapter2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quizes);
//CATEGORY INFO
final String[] items1 = new String[] {"One", "Two", "Three"};
final Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items1);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
//SUBCATEGORY INFO
final String[] items2 = new String[] {"SOne", "STwo", "SThree"};
final Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
adapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items2);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
// Capture our button from layout
Button button = (Button)findViewById(R.id.button1);
// Register the onClick listener with the implementation above
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
startActivity(new Intent(MyClass.this, GoToOtherClass.class));
}
});
//SELECTOR CONTROL FOR SPINNER1 {CATEGORY}
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
MyClass.this.category = spinner1.getSelectedItemPosition();
//OTHER STUFF
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
//SELECTOR CONTROL FOR SPINNER2 {SUB-CATEGORY}
spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
MyClass.this.sub_category = spinner2.getSelectedItemPosition();
//OTHER STUFF
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
return true;
}
}
I understand about the .clear()/.add() methods, but anytime I try clear()/add() my program crashes, what do I need to do to fix things so I can change the spinner2 contents for my sub-category list? Any advice would help, as I have spent hours doing things such as:
Object t=adapter2.getitem(0);
spinner2.remove((String) t);
or adapter2.clear() and a few other tricks and I have no further ideas left. I am still learning android. I've tried looking at some other posts here on stackoverflow and google but was not sure how to get their ideas working.
After you change the contents of the second Spinner, you need to call adapter2.notifyDataSetChanged(). Without that call, the UI won't update with the new contents of the Spinner, and you could also have problems referencing things that don't exist anymore.
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
}
});
}
}
Related
I am trying to use the searchable spinner library but it is not working, here is the code. The spinner works well, But I would really like the search feature too from the library
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityHome);
SearchableSpinner spinner = (SearchableSpinner) findViewById(R.id.spinner);
initControls();
}
private void initControls(){
SearchableSpinner spinner = (SearchableSpinner) findViewById(R.id.spinner);
spinner.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
isSpinnerTouched = true;
return false;
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(isSpinnerTouched){
selectedItem = adapterView.getItemAtPosition(i).toString();
code = getCode(selectedItem);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
proceed_button_new = (TextView) findViewById(R.id.proceed_button_new);
proceed_button_new.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
}
});
List<Food> data = getData();
List<String> foodNames = getFoodNamesFromData(data);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, foodNames);
spinner.setAdapter(adapter);
}
Based on information from Android: Create spinner programmatically from array. I can select room choices from spinner based on ArrayList. However,it never get inside the process setOnItemSelectedListener.I cannot figure out why does it happen.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_room);
SpaceRoomTable = (TableLayout) findViewById(R.id.tvSpaceRoomTable);
AddroomButton = (Button)findViewById(R.id.btLinkAddRoom);
Backtomenu = (Button) findViewById(R.id.bBackToMenu_DogTrack);
Delete = ContextCompat.getDrawable(this, R.drawable.bin);
dropdown = (Spinner) findViewById(R.id.spinListRoom);
summitDelete = (Button) findViewById(R.id.btDeleteSummit);
AddroomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent LinkToEditroom = new Intent (EditRoom.this,AddRoom.class);
startActivity(LinkToEditroom);
}
});
Backtomenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent LinkToHomeMenu = new Intent(EditRoom.this,HomeMenu.class);
EditRoom.this.startActivity(LinkToHomeMenu);
}
});
showRoom();
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,showitemName);
spinnerArrayAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdown.setAdapter(spinnerArrayAdapter);
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Log.d("TEST","selection is ");
Object Itemselected = adapterView.getItemAtPosition(i);
Toast.makeText(getApplicationContext(),"Inside"+String.valueOf(Itemselected),Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
In XML Layout :-
<Spinner
android:id="#+id/dropdown"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
then, in your activity findViewById like this:-
dropdown= (Spinner) findViewById(R.id.dropdown);
then Create an ArrayAdapter using the string array and a default spinner layout :-
ArrayAdapter<String> spinnerArrayAdapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,showitemName);
spinnerArrayAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdown.setAdapter(spinnerArrayAdapter);
For OnIemClickListener use like this:-
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
Spinner dropdown;
String[] showitemName = {"A","B","C","D","E"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dropdown= (Spinner) findViewById(R.id.dropdown);
dropdown.setOnItemSelectedListener(this);
ArrayAdapter<String> spinnerArrayAdapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,showitemName);
spinnerArrayAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdown.setAdapter(spinnerArrayAdapter);
}
//Performing action onItemSelected and onNothing selected
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(),"Inside" + parent.getItemAtPosition(position) , Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
More information:
You can check in details from these links:-
https://developer.android.com/guide/topics/ui/controls/spinner.html
https://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html
https://android--code.blogspot.in/2015/08/android-spinner-onitemselected.html
http://www.java2s.com/Code/Android/UI/SpinnerItemSelectedListener.htm
https://android--code.blogspot.in/2015/08/android-spinner-get-selected-item-text.html
For more Information about showroom method
public void showRoom()
{
refroom.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
int Length_Record = dataSnapshot.child("CurrentUser").child("Tracking").child("ListRoom").child("LIST_ROOM_LENGTH").getValue(int.class);
int RunRecord =0;
int printRoom =0;
final String userId = dataSnapshot.child("CurrentUser").child("UserId").getValue(String.class);
for (DataSnapshot zonesnapshot : dataSnapshot.child("CurrentUser").child("Tracking").child("ListRoom").getChildren())
{
if(printRoom!=Length_Record)
{
zonesnapshot.getValue();
String[] parts = String.valueOf(zonesnapshot.getValue()).split(",");
String part1 = parts[0]; // Room Id
String part2 = parts[1]; // Room Name
String part3 = parts[2]; // TypeRoom
String OnRoom = dataSnapshot.child("CurrentUser").child("Tracking").child("Location").getValue(String.class);
itemsName.add(part2+","+part3); // put to arraylist to prepare a room choice for deletion
showitemName.add(part2+"("+part3+")");
itemOfUser.put(userId+"Room"+printRoom,part2+","+part3); // keep room for each user
inRow(dataSnapshot.child("CurrentUser").child("UserId").getValue(String.class), RunRecord, part2, OnRoom, part3);
}
printRoom++;
}
summitDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
storageReference = storage.getInstance().getReferenceFromUrl("gs://********-*****.appspot.com/imagesRoom").child(userId).child(selection);
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Error Can not delete file",Toast.LENGTH_SHORT).show();
}
});
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
below code will get the selected item text automatically
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Log.d("TEST","selection is ");
String item = adapterView.getItemAtPosition(i).toString();
Toast.makeText(getApplicationContext(),"Inside"+item,Toast.LENGTH_SHORT).show();
}
I want to take the value in spinner and user press the ok Button and then start new activity from against the value of spinner. The string array is just like that. and I use two spinners value get and new activity start against the spinners
Spinner s, s1;
Button ok;
Object _globalString, _globalString2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, array_spinner);
s.setAdapter(adapter);
s1 = (Spinner) findViewById(R.id.spinner01);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, array_spinner01);
s1.setAdapter(adapter1);
//
// s2=(Spinner)findViewById(R.id.spinner02);
// ArrayAdapter<String> adapter2=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,array_spinner02);
// s2.setAdapter(adapter2);
ok = (Button) findViewById(R.id.btn_ok);
ok.setOnClickListener(this);
s.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
_globalString = parent.getItemAtPosition(position);
}
//#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
s1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
_globalString2 = parent.getItemAtPosition(position);
}
// #Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_ok) {
if (_globalString.equals("Honda") || _globalString2.equals("Civic")) {
startActivity(new Intent(getApplicationContext(), Civic.class));
} else if (_globalString.equals("Toyota") || _globalString2.equals("Gli")) {
startActivity(new Intent(getApplicationContext(), Toyota.class));
}
}
}
}
here is the code this can error generate. Sorry application has been stopped
so i stuck on this code.
use setOnItemSelectedListener instead of setOnItemClickListener:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Spinner s, s1;
Button ok;
Object _globalString, _globalString2;
String[] array_spinner = {"Honda", "Toyota"};
String[] array_spinner01 = {"Civic", "Gli"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, array_spinner);
s.setAdapter(adapter);
s1 = (Spinner) findViewById(R.id.spinner01);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, array_spinner01);
s1.setAdapter(adapter1);
//
// s2=(Spinner)findViewById(R.id.spinner02);
// ArrayAdapter<String> adapter2=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,array_spinner02);
// s2.setAdapter(adapter2);
ok = (Button) findViewById(R.id.btn_ok);
ok.setOnClickListener(this);
s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
_globalString = parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
_globalString2 = parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_ok) {
if (_globalString.equals("Honda") || _globalString2.equals("Civic")) {
startActivity(new Intent(getApplicationContext(), Civic.class));
} else if (_globalString.equals("Toyota") || _globalString2.equals("Gli")) {
startActivity(new Intent(getApplicationContext(), Toyota.class));
}
}
}
}
I have a page which consist of a spinner and a submit button. What I want to achieve is when user selects an item in the list and click on submit, it should take him to an other layout having a webview. Each item in the spinner should open different .html page in the layout.
What I have now is the item is being selected from the spinner, but I'm not sure how to perform onclick listener to it...
code for main activity is here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beef);
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
public void addListenerOnSpinnerItemSelection(){
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
//get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
btnSubmit = (ImageButton) findViewById(R.id.imageButton1);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*Nothing as of now*/
//I need to call the ID of the selected item from the spinner here and start new activity
}
});
}
}
code of CustomOnItemSelectedListener is here
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if (arg2 == 0) // First item selected
{
//Here I need to give an id for the .html file
}
else if (arg2 == 1) // Second
{
//Here I need to give an id for the .html file
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String selItem = arg0.get(arg2); // String representation of the selected item
if (arg2 == 0) // First item selected
{
}
else if (arg2 == 1) // Second
{
}
// etc
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
How to use if else statement when using spinner objects?
I wish to make a page like this in Android.
I have done the coding for the button and the spinners and I have used an array to store the values in the spinner.
My Problem: When I select some values in both the spinners and click on "SHOW FARE" button the fare is not generated??
public class HelloSpinner extends Activity implements OnClickListener {
/** Called when the activity is first created.
* #return */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.source_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
this, R.array.destination_array, android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
View v= findViewById(R.id.button);
v.setOnClickListener(this);
if(spinner.getSelectedItem().toString()=="Adarsh Nagar"
&& spinner1.getSelectedItem().toString()=="Rajiv Chowk")
{
TextView t= (TextView) findViewById(R.id.text);
t.setText("Fare:Rs. 16");
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button:
Intent i = new Intent(this,Fare.class);
startActivity(i);
break;
}
}
}
If anyone can spot error(s) in the code, I would appreciate the feedback!
Create setOnItemSelectedListener for both spinner and inside that store the selected Value in a string Variable..
After that in Button click Check you if Conditions..
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
selectedspinnervalue =s1.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
where the string variable selectedspinnervalue contains the value selected by the spinner..
Now in the Button Click check the condition like this :
yourbuttonobject.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(selectedvalueinspinner.equalsIgnoreCase("Adarsh Nagar")&& selectedvalueinspinner1.equalsIgnoreCase("Rajiv Chowk")){
// Your desired Code..
}
}
});