Perform click event on Spinner to execute code in onItemSelected - java

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

Related

How do I populate a spinner inside spinner.setOnItemSelectedListener(...)?

As the title puts my query, I want to populate my spinner only when the user clicks it i.e., the spinner will initially be empty, when the user clicks it then and only then should all the items show. I tried out the following code:
if (spin1 != null) {
spin1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
ArrayList<String> arr=new ArrayList<String>();
arr.add("Hello");
arr.add("Hey");
arr.add("Yo");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(view.getContext(), android.R.layout.simple_spinner_item,arr);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
assert spin1 != null;
spin1.setAdapter(adapter);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {}
});
}
But my above code is not working. The spinner is empty when I click on it. Can you please tell me why and how to fix this issue?
You can register TouchListener to set Adapter for the Spinner on the first click like in the code snippet shown below:
// array list to populate the spinner's item
List < String > array = new ArrayList < > ();
array.add("Nepal");
array.add("India");
array.add("China");
// create adapter instance from the array list
ArrayAdapter < String > adapter = new ArrayAdapter < > (requireContext(),
android.R.layout.simple_spinner_item, array);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// register on item selected listener as usual
binding.testSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView << ? > parent, View view, int position, long id) {
Toast.makeText(requireContext(), array.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView << ? > parent) {}
});
// set on touch listener as we cant set onclick listener in spinner
// because it is made to throw exception
binding.testSpinner.setOnTouchListener((v, event) - > {
// set the adapter in the touch event
// ACTION_UP occurs when user releases the finger
if (event.getAction() == MotionEvent.ACTION_UP) {
binding.testSpinner.setAdapter(adapter);
}
// return false as we dont want to consume the event
// but want to allow it to propagate in the parent view hierarchy
return false;
});

Android Multiple Spinner

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.

Set visibility TableLayout based item selected on Spinner

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!

findViewById not working in static function

I found error in findViewById in static function.
my function is--
public static void onYearSelect() {
Spinner yearSelector;
String yearName;
yearSelector = (Spinner) findViewById(R.id.year_submit);
yearName = yearSelector.getSelectedItem().toString();
}
is there any way to solve this error!
can i store value of Spinner in yearName as String
You need to add view inside function as parameter.
public static void onYearSelect(View view) {
Spinner yearSelector;
yearSelector = (Spinner) view.findViewById(R.id.year_submit);
yearName = yearSelector.getSelectedItem().toString();
}
The view which contains your layout data.
When you call that function add onYearSelect(rootView) here rootView have the layout view.
EDIT 1:
What is View here ?
A View in Android is a widget that displays something. Buttons, listviews, imageviews, etc. are all subclasses of View. When you say "change view" I assume you mean change the layout by using setContentView(). This usually only needs to be done once per activity. An Activity is basically what you are referring to as a screen.
You can read more here.
Set setOnItemSelectedListener on spinner object and inside onItemSelected() you can set value of yearName. Like below,
yearSelector.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String yearName = parentView.getItemAtPosition(position).toString()
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}});

Pass String variables by reference to setOnItemSelectedListener of multiple Spinners

OK, I've read around and see that Java only passes by value, not by reference so I don't know how to accomplish this.
I've 6 Spinners in an Android Activity that are populated with different SQLite queries.
The code to populate each Spinner and set the OnItemSelectedListener is very similiar so I was hoping to refactor to one method and call it 6 times with each Spinner ID and Sqlite query.
How do I get the Spinner onItemSelectedListener to change the right instance member on each different Spinner?
public void fillSpinner(String spinner_name, final String field_name) {
// This finds the Spinner ID passed into the method with spinner_name
// from the Resources file. e.g. spinner1
int resID = getResources().getIdentifier(spinner_name, "id",
getPackageName());
Spinner s = (Spinner) findViewById(resID);
final Cursor cMonth;
// This gets the data to populate the spinner, e.g. if field_name was
// strength = SELECT _id, strength FROM cigars GROUP BY strength
cMonth = dbHelper.fetchSpinnerFilters(field_name);
startManagingCursor(cMonth);
String[] from = new String[] { field_name };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter months = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, cMonth, from, to);
months.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(months);
// This is setting the Spinner Item Selected Listener Callback, where
// all the problems happen
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Cursor theCursor = (Cursor) parent.getSelectedItem();
// This is the problem area.
object_reference_to_clas_member_of_field_name = theCursor
.getString(theCursor.getColumnIndex(field_name));
}
public void onNothingSelected(AdapterView<?> parent) {
// showToast("Spinner1: unselected");
}
});
}
You call this method like this fillSpinner("spinner1","strength");.
It finds the spinner with id spinner1 and queries the database for the strength field. field_name, which is strength in this example had to be declared a final variable to be used in the onItemSelectedListener or I'd get the error Cannot refer to a non-final variable field_name inside an inner class defined in a different method.
But how do I get the onItemSelectedListener to change the value of a different instance member when each different Spinner is used? This is the all important line of code:
object_reference_to_clas_member_of_field_name = theCursor .getString(theCursor.getColumnIndex(field_name));
I can't use a final String as the variable will obviously change when the user selects a different value. I've read around a good bit and am stumped to a solution. I can just copy and paste this code 6 times and forget about refactoring but I'd really like to know the elegant solution. Post a comment if you don't understand my question, I'm not sure if I explaned myself well.
You can do it, by passing additional class as parameter of fillSpinner method:
A. Create interface
public interface OnSpinnerValueSelected {
void onValueSelected(String selectedValue);
}
B. Change your method a bit:
public void fillSpinner(String spinner_name, final String field_name,
final OnSpinnerValueSelected valueChangeListener) {
// Prepare spinner
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Cursor theCursor = (Cursor) parent.getSelectedItem();
valueChangeListener.onValueSelected(theCursor
.getString(theCursor.getColumnIndex(field_name)));
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
C. provide listener:
fillSpinner("spinner1","strength", new OnSpinnerValueSelected() {
public void onValueSelected(String selectedValue) {
yourObject.setField(selectedValue);
}
});
Refactor your listener to a new "class". Initialize with the right arguments/instances as required so that the repeated "code" is reusuable.
Right, this is how I managed it but I'm still open to new suggestions for an accepted answer and I also created a bounty.
I didn't create a new class like panzerschreck suggested so I'm posting this as a new answer to my own question. Bit of a hack but I just created an if..then..else statement in the listener to check what spinner was selected and then set a different instance member.
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Cursor theCursor = (Cursor) parent.getSelectedItem();
if (field_name.equalsIgnoreCase("strength")) {
strength=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("ring")) {
ring_gauge=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("country")) {
country=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("wrapper")) {
wrapper=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("length")) {
length=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("price")) {
price=theCursor.getString(theCursor.getColumnIndex(field_name));
}
// showToast(category);
}
public void onNothingSelected(AdapterView<?> parent) {
// showToast("Spinner2: unselected");
}
});
Here are the class members
private String strength,ring_gauge,country,wrapper,length,price;
Bit of hack but without Java allowing objects to be really passed by reference, it's all I could do.

Categories

Resources