Global variable inside Spinner onItemSelected does not work - android

I've been thinking about this a long while but realy can't figure out what the problem is. The first code piece works in one of my activities. selectedUser is globally declarend and I can use it everywhere.
spUsers.setAdapter(new MyAdapter(this, R.layout.user_sp_row,userArray));
spUsers.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int index = spUsers.getSelectedItemPosition();
selectedUser = userList.get(index).get(Constants.TAG_UNAME);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
selectedUser = "";
}
});
This code does not work allthough it looks the same like the other code I wrote. selectedCat is also globally declared. The thing is the value is set in the onItemSelected method but as soon as it leaves the method selectedCat is an empty string.
spCat.setAdapter(new MyAdapter(this, R.layout.category_sp_row,tempArray));
spCat.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int index = spCat.getSelectedItemPosition();
selectedCat = categoryList.get(index).get(Constants.TAG_UPID);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
selectedCat = "";
}
});

I don't know why are using int index = spUsers.getSelectedItemPosition(); to get the index when you can use the position integer provided in onItemSelected() method.

I've got this working by indeed doing everything that needs to be done in the setOnItemSelectedListener().
Ty DrkStr

Related

How to pass value from onItemSelected to another spinner

I have got 3 spinners in a activity which are populated from webservices with 3 methods as follows using loopj. I want to pass the value of "ida" from onItemSelected of spinner1 to spinner3. So how can I pass a value from one method to another.
protected void onCreate(Bundle savedInstanceState) {
getSpinner1();
}
private void getSpinner1() {
RestClient1.getForSpinner1(
.
.
public void onItemSelected(AdapterView<?> parent, View view, int position, long ida) {
getSpinner2(ida);
}
private void getSpinner2(Long ida) {
RestClient2.getForSpinner2(
.
.
public void onItemSelected(AdapterView<?> parent, View view, int position, long idb) {
getSpinner3(ida,idb);
}
.
.
private void getSpinner3(Long ida,Long idb) {
RestClient3.getForSpinner3(
.
.
public void onItemSelected(AdapterView<?> parent, View view, int position, long idc) {
}
Try to use OnItemSelectedListener. There is a bried description on how to found here at StackOverFlow - how-to-pass-a-selected-spinner-item-between-spinners
I have used this before and it worked a charm.
EDIT: To summarise #Skizo-ozᴉʞS solution, the following -
Then create a globalVariable to get the String to your first Spinner as follows :
String FirstValue = "";
Then you'll need to call this :
spinnerLengthInput.setOnItemSelectedListener(this);
spinnerLengthOutput.setOnItemSelectedListener(this);
Of course you'll need to implements OnItemSelectedListener
Then inside you can do the same that you were doing.
#Override
public void onItemSelected(AdapterView<?> spinner, View view, int position,long id)
{
FirstValue = spinner.getItemAtPosition(position).toString();
checkIfConvertingFromMeter(itemSelectedInSpinnerLengthInput);
}
Then in your other Spinner use the FirstValue value.

how to manage two spinner setOnItemSelectedListener android

I used two spinners in same fragment I want when the first spinner will complete its task then only the setOnItemSelectedListener will call for the second spinner.
Issue: But the issue is setOnItemSelectedListener is called on same time for both the spinners.How can I manage that. :(
What I want to do: I want to draw a graph on page load spinner 1 will darw a different graph and spinner 2 will draw a different graphon page load.
Any help will be Appreciated.
Why do you have same setOnItemSelectedListener for both the spinners.
Have structure like this:
spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
func1();
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText(topThis, "herf", Toast.LENGTH_LONG).show();
}
});
spinner2.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
func2();
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText(topThis, "herf", Toast.LENGTH_LONG).show();
}
});
private void func1()
{
//do task of spinner1
}
private void func2()
{
//your task for second spinner
}
spinnerLeft = (Spinner) getActivity().findViewById(R.id.spinner_left);
dataAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, arrayList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerLeft.setAdapter(dataAdapter);
spinerRight = (Spinner) getActivity().findViewById(R.id.spinner_right);
rightSpinnerAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, arrayList);
rightSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinerRight.setAdapter(rightSpinnerAdapter);
That is my two spinner that I calle d on onActivityCreated.
spinerRight.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long arg3) {
// here I called a method to download a chart and showing below 1st spinner
AppGlobals.getInstance().checkSpinner = 1;
}
private void addListenerOnSpinnerLeftItemSelection() {
spinnerLeft.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long arg3) {
//here I m called the same method to download and show chart below 2nd spinner
AppGlobals.getInstance().checkSpinner = 1;
}
But the before completing the first spinner functionality the second spinner called. I have but the int value so that when both the spinner's called the int value will tell the difference.
if (AppGlobals.getInstance().checkSpinner == 1) {
chartArea = (LinearLayout) getActivity().findViewById(R.id.chart);
} else if (AppGlobals.getInstance().checkSpinner == 0) {
chartArea = (LinearLayout) getActivity().findViewById(R.id.pie_chart);
}

Odd Android Spinner behavior

This is the code to populate my spinner.
The code:
String[] rcs = new String[review_cycles.length];
for (int i = 0; i < review_cycles.length; i++)
rcs[i] = review_cycles[i].ReviewCycleName;
ArrayAdapter<String> rc_spinnerAdapter = new ArrayAdapter<String>(
ActivityManagementReview.this,
R.layout.simple_spinner_item,
rcs);
sp_review_cycle.setAdapter(rc_spinnerAdapter);
sp_review_cycle.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
DtoMrReviewCycleVersion selected_review_cycle_version = review_cycles[position];
if (selected_review_cycle_version != latest_review_cycle_version) {
latest_review_cycle_version = selected_review_cycle_version;
int mr_version_id = latest_review_cycle_version.MrdVersionId;
_URL_version = _url_base + "MrVersion/" + Integer.toString(mr_version_id);
new GetMrVersionInfoAsyncTask().execute();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
return;
}
});
When I select a value from the spinner, the code is executed twice. Once with the selection I made and then right afterward, the first item in the list is executed again bringing me back to where I started.
How can I prevent this from happening?
Thanks.
When I select a value from the spinner, the code is executed twice.
As I reminded you in the comments, Spinners call onItemSelected() when they load the default value. This feature is useful when you know about it, but since it is not what the average developer expects it is problematic as well.
The Spinner will also call onItemSelected() when the user re-selects the current value... When I want to avoid both of these false alarms I use something like this:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
int previous = -1;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(previous != position && previous < -1) {
Log.v("Example", "Selected: " + position);
// Do something
}
previous = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
});

Android Spinner only selects top value

I've tried this a few different ways and all the code does is print out the top value of the spinner.
final String [] equipment=new String[]{//items
}
ArrayAdapter<?> ad=new ArrayAdapter<Object>(this,android.R.layout.simple_spinner_item,equipment);
ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spin=(Spinner)findViewById(R.id.spinneritem);
spin.setAdapter(ad);
int position = spin.getSelectedItemPosition();
final String equipmentitem = equipment[position].toString();
From what I can tell that should be able to take the value of the array that the user has selected, but no matter what I select in the list, it only select the first item, and ignores the actual selection.
You probably need to add a listener to the spinner.
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
equipmentitem = equipment[position].toString();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});

Spinner item gets automatically selected upon entering activity. How do I avoid this?

I have a spinner in my Android app, and its onItemSelected() event automatically gets triggered upon entering the activity.
How do I avoid this?
We can use a flag, and just enable it when the spinner is really touched.
private boolean isSpinnerTouched = false;
spinner.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
isSpinnerTouched = true;
return false;
}
});
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View arg1,
int arg2, long arg3) {
if (!isSpinnerTouched) return;
// do what you want
}
});
To add on Jerry Abraham, You should clear selection before enabling setOnItemSelectedListener
Spinner mSpinner=(Spinner)findViewById(R.id.mySpinner);
int initialSelectedPosition=mSpinner.getSelectedItemPosition();
mSpinner.setSelection(initialSelectedPosition, false); //clear selection
mSpinner.setOnItemSelectedListener(this); //set listener after clearing section
I have solved this issue,
You can avoid this issue by not setting any default values to the spinner
int initialposition=spinner.getSelectedItemPosition();
spinner.setSelection(initialposition, false);
This will avoid entering into onItemSelected()
There are no any way to avoid this.
You may add some flag, indicating readiness of your application and use it in your onItemSelected() method to decide, what to do in each case.
Well, you can add a dummy selection to the initial adapter, and ignore position number in the setOnItemSelectedListener. It's not pretty but it works. See this code for setting up the items for an array adapter.
List<String> names = new ArrayList<String>();
names.add("");
names.addAll(realValues);
Then in your setOnItemSelectedListener you can do this:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
if (position > 0)
{
String name = names.get(position - 1);
}
else
{
Log.d(TAG, "selected nothing or perhaps the dummy value");
}
}
I have found a solution for this problem and posted it here (with code sample):
Spinner onItemSelected() executes when it is not suppose to
Simple and easy is this...
validate with a boolean to see if is first time...
Spinner mySpinner = (Spinner)findViewById(R.id.spinner_xml_pro);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(isSpinnerInitial){ // globar var boolean isSpinnerInitial = false;
//do something
}else
isSpinnerInitial=true;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Check this with spinner.post(new Runnable()...)
or this other my source
I think that you can use spinner position which is a better approach in my opinion.
Create a global variable where you store the spinner position, in onItemSelected method the position is provided you can compare them, if they are the same do not make an action.
private int spinnerPosition; \\ Global variable
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
if(spinnerPosition != position){
// Do whatever you like
// Do not forget to save the new position
spinnerPosition = position;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
You can avoid it by ignoring the first click by,
private boolean isSpinnerInitial = true; //As global variable
public void onItemSelected(xxx xxx, xxx xxx, xxx xxx, xxx xxx) {
if(isSpinnerInitial) {
isSpinnerInitial = false;
return;
}
// Write your code here
}

Categories

Resources