How to pass spinner data from one activity to another ?
18,064
Solution 1
Why you are using onClickListener for Spinner ? You should use OnItemSelectedListener() for Spinner see the below example code,
public class MySpinnerSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selected = parent.getItemAtPosition(pos).toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
Now register listener using following code,
spinner.setOnItemSelectedListener(new MySpinnerSelectedListener());
You can pass it using following code,
// Sending Code
Intent intent = new Intent(getApplicationContext(), DatabaseResult.class);
intent.putextra("getData",USN.toString());
startActivity(intent);
// Receiving code,
String value= getIntent().getStringExtra("getData");
Solution 2
try this
int positionitem = spinner.getSelectedItemPosition();
Solution 3
public class SpinnerExample extends Activity
{
Spinner sp;
String text ="";
Button btnResult;
public void onCreate(Bundle savedInstanceState)
{
sp = (Spinner) findViewById(R.id.spinner1);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View arg1, int arg2, long arg3)
{
this.text = parent.getItemAtPosition(pos).toString();
}
public void onNothingSelected(AdapterView<?> arg0)
{
/ TODO Auto-generated method stub
}
});
btnResult = (Button) findViewById(R.id.buttonId);
btnResult.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent i = new Intent(getApplicationContext(), DatabaseResult.class);
i.putExtra("getData",this.text);
startActivity(i);
}
});
}
}
Author by
Punith K
Quick learner, loves coding, web developer knows, React, Redux and more web related stuff.
Updated on June 09, 2022Comments
-
Punith K almost 2 years
This code is not reading the value from the spinner it's reading only the first value always,
btnResult.setOnClickListener(new View.OnClickListener() { final String USN = spnConversions.getSelectedItem().toString(); @Override public void onClick(View v) { Intent i = new Intent(getApplicationContext(), DatabaseResult.class); i.putExtra("getData",USN.toString()); startActivity(i); } });
-
Punith K about 10 yearsi am using the same thing in my another activity. That is not the problem but whenever i select 10002 from the spinner it's not getting the position value from the spinner. do i need to add any code in first activity.
-
Punith K about 10 yearsThanks, i made a little changes just i called my btn.onClickListener() from spinner.onItemSelectedListener(), it's working.
-
Punith K about 10 yearsThanks for ur valuble time.