En el proceso de registro, cuando el usuario selecciona el título de la ruleta, sus valores de índice de matriz deben seleccionarse automáticamente y enviarse al asynctask. Quiero enviar el valor del índice de la matriz (posición) también en el código que se muestra a continuación.

new RegisterAsyncTask(getApplicationContext()).execute(TitleName,CountryName);

El valor original de la posición está dentro de onItemSelected(), quiero saber cómo pasarlo a onclick()

Este es mi código java

public class RegisterActivity extends Activity {
private String[] states, states1;
private Spinner countrySP, titleSP;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_register);

        Spinner spinner = (Spinner) findViewById(R.id.registerTitle);
        spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

        states = getResources().getStringArray(R.array.title_array);
        states1 = getResources().getStringArray(R.array.country_array);

        titleSP = (Spinner) findViewById(R.id.registerTitle);

        final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, states);
        dataAdapter
        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        titleSP.setAdapter(dataAdapter);

        countrySP = (Spinner) findViewById(R.id.registerCountry);
        ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, states1);
        dataAdapter1
        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        countrySP.setAdapter(dataAdapter1);

        final Button button = (Button) findViewById(R.id.btnRegister);
        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                try {


                    String TitleName = titleSP.getSelectedItem().toString();
                    String CountryName = countrySP.getSelectedItem().toString();
                    String position = String.valueOf(titleSP.getSelectedItemPosition());
                String position = String.valueOf(countrySP.getSelectedItemPosition()); //Duplicate local variable position

                                    new RegisterAsyncTask(
                                            getApplicationContext()).execute(
                                                    TitleName,
                                                    CountryName, position);

                                    Toast.makeText(getApplicationContext(),
                                            "Asynctask started",
                                            Toast.LENGTH_SHORT).show();

                } catch (Exception ex) {

                }

            }
        });


    public class MyOnItemSelectedListener implements OnItemSelectedListener {

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
        long id) {

    //check which spinner triggered the listener
    switch (parent.getId()) {
    //country spinner
    case R.id.registerTitle:
        //make sure the country was already selected during the onCreate
        String[] titles = getResources().getStringArray(R.array.title_array);
        String selectedTitle = titles[position];  
        System.out.println("title = " + position );

    case R.id.registerCountry:
        //make sure the country was already selected during the onCreate
        String[] countries = getResources().getStringArray(R.array.country_array);
        String selectedCountry = countries[position];  
        System.out.println("country = " + position );
    }

}




    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // TODO Auto-generated method stub

    }
    }

}

Mi título.xml dentro de la carpeta de valores

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title_prompt">Choose the title</string>
    <string-array name="title_array">
        <item>Mr</item>
        <item>Mrs</item>
        <item>Miss</item>
        <item>Dr</item>
        <item>Rev</item>
        <item>Ms</item>
    </string-array>
</resources>
0
John David 2 feb. 2015 a las 10:16

2 respuestas

La mejor respuesta

Utilice getSelectedItemPosition para obtener la posición del elemento seleccionado de Spinner en el botón haga clic como:

public void onClick(View v) {
       String TitleName = titleSP.getSelectedItem().toString();
       String CountryName = countrySP.getSelectedItem().toString();
       String position=String.valueOf(titleSP.getSelectedItemPosition());
       // pass position to RegisterAsyncTask
       new RegisterAsyncTask(
         getApplicationContext()).execute(TitleName,CountryName,position);

  }
2
ρяσѕρєя K 2 feb. 2015 a las 07:31

Sí, ahora lo entiendo, necesitas hacer algo como esto

public void onClick(View v) {

try {


String TitleName = titleSP.getSelectedItem().toString();
String CountryName = countrySP.getSelectedItem().toString();
String selectedPos=Integer.toString(titleSP.getSelectedItemPosition()); // or countrySP if u need it to


                new RegisterAsyncTask(
                        getApplicationContext()).execute(
                                TitleName,
                                CountryName, selectedPos);
:
:

Ahora tienes que modificar RegisterAsyncTask doInBackground ():

... doInBackground(String... params){
//params[0] is TitleName
//params[1] is CountryName
//params[2] is selectedPos
:
:
}
1
Yazan 2 feb. 2015 a las 07:35