How to transfer spinner data from one activity to another?

This code does not read the value from the counter, which always reads only the first value,

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);
    }
});
+4
source share
3 answers

Why are you using onClickListener for Spinner? You must use OnItemSelectedListener () for Spinner, see the code example below,

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 the listener using the following code,

 spinner.setOnItemSelectedListener(new MySpinnerSelectedListener());

You can pass it using the following code,

// Submit code

Intent intent = new Intent(getApplicationContext(), DatabaseResult.class);
intent.putextra("getData",USN.toString());
startActivity(intent);

// Get the code,

String value= getIntent().getStringExtra("getData");
+4
source

try it

int positionitem = spinner.getSelectedItemPosition();
+1
source
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);
                  }
           });
    }
}
+1

Source: https://habr.com/ru/post/1528050/


All Articles