Passing Value from Spinner setonItemSelectedListener - android

I am trying to get the position of a spinner item and pass it into another method. To achieve this I have declared a spinner in MainActivity and set onItemSelectedListener method(to get the position based on user click). Now I want to pass the value from the onItemselectedListener method to another method getItem(). But the value recieved at getItem() is always null. I have attached my code for further reference.
public class MainActivity extends AppCompatActivity {
Spinner spinner;
String[]array={"I","Me","Myself"};
String abc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner= (Spinner) findViewById(R.id.spinner);
spinnerAdapter adapter=new spinnerAdapter(MainActivity.this,android.R.layout.simple_spinner_dropdown_item);
adapter.addAll(array);
adapter.add("Select Here");
spinner.setAdapter(adapter);
spinner.setSelection(adapter.getCount());
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
abc= String.valueOf(spinner.getSelectedItemPosition()+1);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
getitem();
}
public void getitem()
{
Log.e("MSG",abc);
}
}

From Android dev website:
Responding to User Selections
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
...
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
From parent.getItemAtPosition(pos) you can then get the string value and pass it to another activity if you wish.

Related

Spinner listener OnItemSelectedListener function without click on spinner

I have an activity Advanced Research, with a spinner that contains all category from my db. When i create the activity, this spinner call onSetItemListener in loop. Why?
I try to use onTouchListener but not working, maybe i fail something.
if(risultato.getCategoria().getSottocategorie().toArray() != null && risultato.getCategoria().getSottocategorie().toArray().length != 0){
adapterSpinnerCategoria = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, risultato.getCategoria().getSottocategorie().toArray());
}else{
adapterSpinnerCategoria = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, categoriaVuota);
}
spinnerCategoria.setAdapter(adapterSpinnerCategoria);
public void spinnerChange(AdapterView<?> parent){
if(!parent.getSelectedItem().toString().equals("Sottocategorie vuote")) {
ricercaAvanzata.setCategoria((Categoria) parent.getSelectedItem());
setArticoli();
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinnerChange(parent);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
return;
}
public void setListener() {
spinnerCategoria.setOnItemSelectedListener(this);
}
public class ActivityRicercaAvanzata extends AppCompatActivity implements AdapterView.OnItemSelectedListener { .... }
I expect that when i click on spinner call onItemSelected not before
i am using Spinner for Country Selection for User Registration.
please vote my answer.
Spinner spcountry;
String country;
//in onCreare
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
spcountry = (Spinner) findViewById(R.id.country);
final String[] countryNames = getResources().getStringArray(R.array.countries_array);
ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item, countryNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spcountry.setAdapter(aa);
spcountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.v("item", (String) parent.getItemAtPosition(position));
if (position == 0) {
return;
} else
country = countryNames[position];
//Toast.makeText(getBaseContext(),country,Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
From what I can see, you are extending AdapterView.OnItemSelectedListener.
You cannot extend it since OnItemSelectedListener is an interface, not a class.
What you actually should be doing is, implementing it instead, like so:
MyActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
}
Then you can set the OnItemSelectedListener on the Spinner,
spinnerCategoria.setOnItemSelectedListener(this);
And the final step would be to write the implementation for the overridden methods,
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Your implementation here
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
//Your implementation here
}
Ok, mark as solved thx. I create a new List and i convert my set into list. After this operation i add a null element at first position, and when i'm call onItemSelected, i do
if(position != 0)then
//do something
Activity start always at position 0 then must wait my click and my choice. Thx all for help me.

Cannot get current spinner position with setOnItemSelectedListener

I am trying to retrieve the spinner's selected position. The values inside the spinner are of type String and I am using setOnItemSelectedListener to change a class String variable to the one that has been selected and use it later on:
spinner = (MaterialBetterSpinner) myToolbar.findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,socialMediaOptions);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
socialMedia = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
private void sendPost(){
Log.v(TAG, socialMedia);
}
The problem is that the variable does not change when an item is selected, it seems like onItemSelected is not being called when there is a change in the spinner selection
See this thread:
https://github.com/Lesilva/BetterSpinner/issues/42
There said that BetterSpinner extends EditText, that's why onItemSelectedListener is not being called. You should use TextChangedListener instead.
Hope your socialMediaOptions are string array like this
socialMediaOptions={"FB","TWIT","IN"}
then
// Specify the layout to use when the list of choices appears
add this line
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
socialMedia = socialMediaOptions[position];
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

How to display value of two Spinner(present in one activity) in a TextView: Android

I am unable to display the value of selected spinner in the TextView.
None of the spinner value is being displayed.
Is there any way to display values of both the spinners?
here is the code
public class Calculator extends Activity implements OnItemSelectedListener {
Spinner temp1,temp2;
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
t1=(TextView)findViewById(R.id.t1);
temp1=(Spinner)findViewById(R.id.temp);
ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this,R.array.temperature,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
temp1.setAdapter(adapter);
temp2=(Spinner)findViewById(R.id.temp2);
ArrayAdapter<CharSequence> adapter2=ArrayAdapter.createFromResource(this,R.array.temperature,android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
temp2.setAdapter(adapter2);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Spinner temp1=(Spinner)parent;
Spinner temp2=(Spinner)parent;
if (temp1.getId()==R.id.temp) {
String item = parent.getItemAtPosition(position).toString();
t1.setText(item);
}
if (temp2.getId()==R.id.temp2) {
String item = parent.getItemAtPosition(position).toString();
t1.setText(item);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
You did not added listener to your spinners.
Use:
temp1.setOnItemSelectedListener(this);
temp2.setOnItemSelectedListener(this);

Set Text based on list item click

I am having a layout consisting of ListView and a label. Look at the image below.
I implemented listview using base adapter in a seperate .java file.
Could anyone suggest me how can i set text to the label on click of list item?
EDITED :
The text of the label should be number of list items clicked.
Suppose i clicked a button in a list item, the label should be set to 1.
Similarly in the next attempt if i clicked another list item's button it should be set to 2 and so.. on..
Sir,
What you are saying is this, you have your adapter in one class and the activity in another file. Well you could do this, to update the textview.
pass the context to the activity, and if its in the adapter you are maintaining the count then once the count has been updated,
then, assume you have this method in the activity
public void updateTextView(int count) {
// enter your code here to set the count in the textview
}
and from the baseAdapter call the above method like this:
if(mContext != null) {
((YourActivity)mContext).updateTextView(mCount);
}
and the textview in the activity will be updated!
I hope it helps.
In your OnItemClickListener call adapter.getItem(int position) to retrieve the object from the collection backing your BaseAdapter. From there, you should be able to retrieve any fields you need.
Edit:
Your edit clears up the question. Updated answer:
private int mCounter = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ListView listView = getYourListView();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mCounter++;
updateTextView();
}
});
if(savedInstanceState != null) {
mCounter = savedInstanceState.getInt("counter", 0);
}
updateTextView();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("counter", mCounter);
}
private void updateTextView() {
// TextView textView = getYourTextView();
textView.setText(String.valueOf(mCounter));
}
Just OnItemClickListener in your ListView then in the onClick you will get a value arg2 which is the position of the item which is clicked.
Just get that value from the ArrayList from which you are displaying the ListView and show it...
Hope this is what you need if I have not misunderstood your question.
try this code
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String itemText=(String) arg0.getItemAtPosition(arg2);
yourLable.setText(itemText);
}
});
In onListItemClick call list.getItemAtPosition(position) to retrieve item text
then set this text to textview1.setText(listText).
First Implement your onItemClickListener, where you will get int arg2 parameter, which is position, so get that position and do your stuff whatever you want like below.
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
LABLE.setText(""+arg2);
}
});
Check this code
public class ListA extends ListActivity {
private TextView selection;
private static final String[] items={"Item 1", "Item 2", "Item 3"};
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_list);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
items));
selection=(TextView)findViewById(R.id.selection);
}
#Override
public void onListItemClick(ListView parent, View v, int position,
long id) {
selection.setText(position);
}
}

How to maintain spinner selected state in android

I just wanna maintain spinner selected state in android.I've an activity A which retrieves data from webservice & popped into spinner.After select any one item from that and goes to another activity B.Once back to activity A.,i need to show selected item on spinner without go to web call again.
My Code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
spinner = (Spinner) findViewById(R.id.spinner);
if(spinnerFlag=1){
spinner.setSelection(index);
}
else{
//Web call for spinner data
}
...
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View view, int arg2, long arg3) {
String seletcedProductName = parent.getSelectedItem()
.toString();
spinnerFlag=0;
index=arg2;
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Thanks.
Just save the index in SharedPreferences on activity stop, retrieve it when you return to that activity.
Shared Preferences at Android Developer
You can save selected index of spinner in static variable, initialized with -1, and onResume check the value of that variable, if it's not -1, then set the selected index of spinner with it.
static int position=-1;
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View view, int arg2, long arg3) {
String seletcedProductName = parent.getSelectedItem()
.toString();
spinnerFlag=0;
index=arg2;
position=arg2;
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
#Override
protected void onResume() {
super.onResume();
if(position!=-){
spinner.setSelection(index);
}
}

Categories

Resources