How to pass spinner data from one activity to another ?

天大地大妈咪最大 提交于 2020-01-01 10:16:13

问题


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

回答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");



回答2:


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



回答3:


try this

int positionitem = spinner.getSelectedItemPosition();


来源:https://stackoverflow.com/questions/21928747/how-to-pass-spinner-data-from-one-activity-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!