I'm sure I'm missing something simple, but I am having some logic issues with my code. I am working on a converter app. I will be using two spinners to select between to do conversions. Ex. inches to feet. I am using two simple methods to test before fleshing out all of the code. Right now if I select the value for SpinnerA in the app first, and then select the value for SpinnerB, it doesn't calculate. If I select SpinnerB first and then SpinnerA, it works. What am I missing?
spinnerA = (Spinner)getView().findViewById(R.id.spinnerA);
spinnerB = (Spinner)getView().findViewById(R.id.spinnerB);
adapterA = ArrayAdapter.createFromResource(getContext(),
R.array.conversions, android.R.layout.simple_spinner_item);
adapterA.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapterB = ArrayAdapter.createFromResource(getContext(),
R.array.conversions, android.R.layout.simple_spinner_item);
adapterB.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerA.setAdapter(adapterA);
spinnerB.setAdapter(adapterB);
spinnerA.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
tempA = parent.getItemAtPosition(position).toString();
if (tempA.equals("Inches") && tempB.equals("Centimeters")){
textView.setText(String.valueOf(halfMyNum(100)));
}
else if (tempA.equals("Centimeters")){
if (tempB.equals("Inches")){
textView.setText(String.valueOf(doubleMyNum(12)));
}
}
else{
textView.setText("Please select a valid option");
}
//Toast.makeText(getContext(), parent.getItemAtPosition(position)+ " Selected"
//, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerB.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
tempB = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
When you are selecting an item from spinnerA first, tempA is initialized and item listener for spinnerA is called but tempB is not yet initialized.
Then, when you select item from spinnerB, tempB is initialized and item listener for spinnerB is called. In your case, you only called the method in item listener method for spinnerA, so when you select item from spinnerB nothing actually executes. One possible solution is to call the desired method in item listener for spinnerB as well.
Related
In an Android app, I have a SpinnerAdapter that I am using to display expiration years of credit cards. My variable expirationYears contains an array of Strings with years from "2020" to "2029". It was declared as String[] expirationYears = new String[10]; and then with a function I set the ten years as Strings, from current year and then the nine subsequent years after that for a total of ten elements in the array. When I run it, this is what I see:
Everything is perfect so far. The only problem is that when as you see in the image above, 2020 is the year selected by default. That is the first element in the expirationYears array. But I want to set 2021 as default (the second element of the array). This is what my code has:
Spinner spinnerYearCreditCardPayment;
SpinnerAdapter creditCardYearAdapter = new SpinnerAdapter(Payment.this, expirationYears);
creditCardYearAdapter
.setDropDownViewResource(android.R.layout.spinner_dropdown_item);
spinnerYearCreditCardPayment.setAdapter(creditCardYearAdapter);
spinnerYearCreditCardPayment
.setOnItemSelectedListener(new OnItemSelectedListener() {
..........
});
I was expecting to have some property available to define which element I want to show by default. Something like creditCardYearAdapter.setSelectedItem(INDEX_NUMBER). But that property does not exist. Do you know how I could set the default selected item so that it is not the first element of the array (2020) but the second (2021)? Thank you.
UPDATE 1:
Following The_Martian's answer, this was what I did:
spinnerYearCreditCardPayment
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
arg0.setSelection(1);
cardYear = (String) spinnerYearCreditCardPayment
.getSelectedItem();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Now I correctly see the second element of the array ("2021") as the default selection.
The problem is that when I use arg0.setSelection(1);, I choose another year and it does not respond. The selected year remains "2021" even thought I am trying to change the year.
You can do similar to the following. I am just giving you an idea here.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
parent.setSelection(position + 1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Try this snippet
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
int seleccion=parent.getSelectedItemPosition();
spinner.setSelection(position)
});
}
You can select the spinner item based on value instead of position. Can refer the example below-
String value = "to be selected value";
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
if (value != null) {
int spinnerPosition = adapter.getPosition(value);
mSpinner.setSelection(spinnerPosition);
}
I want to make Spinner to set Visibility of table, i have 2 Array String "cuboid and cylinder". if i select Cuboid , cubeT table is visible and cyclinderT table is Invisible. and if i select Cylinder , cylinderT table is Visible and cubeT is Invisible.
Sample code welcome. Thank you for your time.
You can set an OnItemSelectedListener to your Spinner then using the int position argument to decide what action to take.
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
switch (position) {
case Cuboid:
cubeT.setVisibility(View.VISIBLE);
cylinderT.setVisibility(View.GONE);
break;
....
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) { }
});
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String text = ((Spinner)spinner).getSelectedItem().toString();
if (Intrinsics.areEqual(text, "Cuboid")) {
//Your code here to set your "table" as cubeT if it's image in imageview
//if it's a "tableLayout" you may create 2 different layouts included and..:
setContentView(R.layout.your_cubeT_layout);
} else if (Intrinsics.areEqual(text, "Cylinder")) {
setContentView(R.layout.your_cyclinderT_layout);
}
} //when it comes to use different layouts on the same activity, generally suggestions made over fragments to make your code more dynamic but i don't know how to do that...
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
I'm not using java since years so i might code bad... So no warranty!
String chooseTime[] = {"7.00 - 9.00", "9.00 - 11.00", "11.00 - 13.00", "13.00 - 15.00", "15.00 - 17.00", "17.00 - 18.30" };
spTimeConsegna = (Spinner)
rootView.findViewById(R.id.timeChooseConsegna);
adapterChooseTimeConsegna = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, chooseTime);
adapterChooseTimeConsegna.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spTimeConsegna.setAdapter(adapterChooseTimeConsegna);
chooseTimeConsegna = chooseTime[spTimeConsegna.getSelectedItemPosition()];
I want to save the selected value of the spinner in the chooseTimeConsegna String, but it always saves the first value of the chooseTime string array indifferently what is choosen in the spinner. Why?
I think you are doing this in onCreate method, so it's only called when that activity is started, not every time you select things on spinner. Try something like this:
yourSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String chooseTime[] = {"7.00 - 9.00", "9.00 - 11.00", "11.00 - 13.00", "13.00 - 15.00", "15.00 - 17.00", "17.00 - 18.30" };
chooseTimeConsegna = chooseTime[position];
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
This method is gonna be called every time you select something on your spinner, and argument position is the position of the selected item in the spinner.
Replace:
chooseTimeConsegna = chooseTime[spTimeConsegna.getSelectedItemPosition()];
With:
spTimeConsegna.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
chooseTimeConsegna = chooseTime[position];
}
});
You should be good to go.
I am trying to write a simple app for android. I want to display toast message if there is no item is selected in spinner. .I use two progress bar to do this.I have tried the code given below.
String selection =sp.getSelectedItem().toString();
System.out.println("selected item "+selection);
if(selection=="[selection]")
Toast.makeText(getActivity(), "gfdgdghfhf", Toast.LENGTH_SHORT).show();
return false;
use a string value as flag of selection
String status="not_selected";
yourSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
MyData d = items[position];
status=d.getValue();
}
public void onNothingSelected(AdapterView<?> parent) {
status="not_selected";
}
});
if(status.equqls("not_selected"){
//show toast here
}
I want to perform a click on a Spinner element automatically after my activity has been loaded completely.
I use this code to set up the spinner and adapter:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_data);
getActionBar().setDisplayHomeAsUpEnabled(true);
mSpinnerDay = (Spinner) mTable.findViewById(R.id.spieltag_choice);
mAdapterSpinnerDay = new ArrayAdapter<CharSequence>(this, R.layout.custom_spinner);
mAdapterSpinnerDay.setDropDownViewResource(R.layout.custom_spinner);
mSpinnerDay.setAdapter(mAdapterSpinnerDay);
}
private void setUpSpinnerListener(final IGameData data) {
mSpinnerDay.post(new Runnable() {
public void run() {
mSpinnerDay.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
for (GameDayData d : data.getGameDay()) {
if (d.getName().equals(adapterView.getSelectedItem().toString())) {
TableRow row = (TableRow) mTable.findViewById(R.id.row_punkte_tag);
TextView t = (TextView) row.findViewById(R.id.punkte_tag);
t.setText("Punkte: " + d.getScore());
TableRow row2 = (TableRow) mTable.findViewById(R.id.row_position_tag);
TextView t2 = (TextView) row2.findViewById(R.id.position_tag);
t2.setText("Position: " + d.getPosition());
return;
}
}
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});
}
});
}
public void onTeamCheckReadComplete(IGameData data) {
for (GameDayData d : data.getGameDay()) {
mAdapterSpinnerDay.add(d.getName());
}
}
I try to perform the click with following code after I have set the adapter to the spinner:
mSpinnerDay.setSelection(0, true);
View view = (View) mSpinnerDay.getChildAt(0);
long id = mSpinnerDay.getAdapter().getItemId(0);
mSpinnerDay.performItemClick(view, 0, id);
But this does not work. Could somebody tell me how I can perfom a click on a spinner element automatically? When I select the spinner item over touch event in the application everything works fine.
Regards,
Sandro
Corrected Solution
As I understand it, you have a spinner with items A, B, C, and D. You want item A pre-selected. You also want the user to be able to select A, B, C, and D and perform an action based on that.
In the onCreate() method:
mSpinner.setAdapter(myAdapter);
mSpinner.setOnItemSelectedListener(this); // have the activity implement
// OnItemSelectedListener interface
doAction(0);
Then implement the onItemSelected action like so:
#Override
void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
doAction(position);
}
You must implement the doAction(int position) method to handle how to update your activity based on the position of the item in your adapter. Clear?
Read more about this item and how to use it here:
http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html
I dont think you are calling setUpSpinnerListener from the code that you have posted. Even if you are calling it, i dont think it is advantageous to post a runnable to setuplistener.
Move all the code in runnable to just after setAdapter