How to pass spinner data from one activity to anot

2020-07-15 18:36发布

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);
    }
});

3条回答
【Aperson】
2楼-- · 2020-07-15 18:52

try this

int positionitem = spinner.getSelectedItemPosition();
查看更多
我只想做你的唯一
3楼-- · 2020-07-15 18:56

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");
查看更多
叛逆
4楼-- · 2020-07-15 19:06
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);
                  }
           });
    }
}
查看更多
登录 后发表回答