Spinner shows no selected item

Asked

Viewed 1,138 times

1

I’m making a private List states = new Arraylist(); I am filling it correctly and displays the values in Spinner more when I select it changes the size as if it had selected but no longer displays the content. Ex: correct would be this

spinner = "SP"

looks like this in my spinner = " "

my spinner in xml

<Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/spinnersexo_usu"
        android:layout_below="@+id/txtsexo"
        android:layout_alignLeft="@+id/edtnome_usu"/>

my code to add values in spinner

ArrayAdapter<String> adp= new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1,estados);
    adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    EstadoUsu.setAdapter(adp);

My class

 public class Cadastro_Usuario extends Activity {

EditText NomeUsu, FotoUsu, NascimentoUsu, SenhaUsu, TelefoneUsu, CelularUsu, EmailUsu, CepUsu, EnderecoUsu, NumeroUsu, ComplementoUsu, BairroUsu, CidadeUsu;
Spinner SexoUsu, EstadoUsu;

private ProgressDialog pDialog;
private List<String> estados = new ArrayList<String>();
private String estado;

private String tag_json_obj = "jobj_req", tag_json_arry = "jarray_req";
private String TAG = Cadastro_Usuario.class.getSimpleName();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cadastro_usuario);

    NomeUsu = (EditText) findViewById(R.id.edtnome_usu);
    SexoUsu = (Spinner) findViewById(R.id.spinnersexo_usu);
    NascimentoUsu = (EditText) findViewById(R.id.edtdata_usu);
    NascimentoUsu.addTextChangedListener(Mask.insert("##/##/####", NascimentoUsu));
    SenhaUsu = (EditText) findViewById(R.id.edtsenha_usu);
    TelefoneUsu = (EditText) findViewById(R.id.edttelefone_usu);
    TelefoneUsu.addTextChangedListener(Mask.insert("(##)####-####", TelefoneUsu));
    CelularUsu = (EditText) findViewById(R.id.edtcelular_usu);
    CelularUsu.addTextChangedListener(Mask.insert("(##)#####-####", CelularUsu));
    EmailUsu = (EditText) findViewById(R.id.edtemail_usu);
    CepUsu = (EditText) findViewById(R.id.edtcep_usu);
    CepUsu.addTextChangedListener(Mask.insert("##.###-####", CepUsu));
    EnderecoUsu = (EditText) findViewById(R.id.edtendereco_usu);
    NumeroUsu = (EditText) findViewById(R.id.edtnumero_usu);
    ComplementoUsu = (EditText) findViewById(R.id.edtcomplemento_usu);
    BairroUsu = (EditText) findViewById(R.id.edtbairro_usu);
    CidadeUsu = (EditText) findViewById(R.id.edtcidade_usu);
    EstadoUsu = (Spinner) findViewById(R.id.spinnerestado_usu);

    pDialog = new ProgressDialog(this);
    pDialog.setMessage("Loading...");
    pDialog.setCancelable(false);

    RetornaJSONEstado();

}

private void RetornaJSONEstado() {
        showProgressDialog();
    JsonArrayRequest req = new JsonArrayRequest(Const.URL_JSON_ARRAY_CAD_USU,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hideProgressDialog();

                    int aJsonint = 0;
                    String aJsonString;

                    // Recupera seu adapter
                    ArrayAdapter<String> adp = (ArrayAdapter<String>) EstadoUsu.getAdapter();

                    // Desabilito a notificao por enquanto, ate terminar de adicionar tudo
                    adp.setNotifyOnChange(false);

                    try {
                        JSONArray jsonarray = response;
                        JSONObject jsonobj;

                        for (int i=0; i<jsonarray.length(); i++){
                            jsonobj = jsonarray.getJSONObject(i);

                            aJsonString = jsonobj.getString("sigla");
                            aJsonint = jsonobj.getInt("id");
                            System.out.println("ID " + aJsonint + " sigla  " + aJsonString);
                            // Voce pode adicionar aqui, mas nao eh recomendado
                            //estados.add(aJsonString);

                            // Adiciono direto no ArrayAdapter
                            adp.add(aJsonString);
                        }

                        // Habilitar novamente a notificacao
                        adp.setNotifyOnChange(true);
                        // Notifica o Spinner de que houve mudanca no modelo
                        adp.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());

                    System.out.println("Deu ERROR PQP");
                    hideProgressDialog();
                    msgerro();
                    finish();
                }
            }
    );

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(req,
                tag_json_arry);

    // Cancelling request
    // ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_arry);


}

private void msgerro(){
    Toast.makeText(this, "Verifique sua conexao com internet e tente novamente", Toast.LENGTH_LONG).show();

}

private void showProgressDialog() {
    if (!pDialog.isShowing())
        pDialog.show();
}

private void hideProgressDialog() {
    if (pDialog.isShowing())
        pDialog.hide();
}
}

My complete layout

<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@drawable/fundoverde2">


<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/scrollView"
    android:layout_centerHorizontal="true"
    android:layout_alignParentTop="true" >
<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="*Nome:"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="15dp"
        android:textColor="#006600"
        android:textSize="15dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="15"
        android:id="@+id/edtnome_usu"
        android:layout_below="@+id/textView"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="*Sexo:"
        android:layout_marginTop="10dp"
        android:id="@+id/txtsexo"
        android:layout_below="@+id/edtnome_usu"
        android:layout_alignLeft="@+id/edtnome_usu"
        android:layout_alignStart="@+id/edtnome_usu"
        android:textColor="#006600"
        android:textSize="15dp" />

    <Spinner
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spinnersexo_usu"
        android:layout_below="@+id/txtsexo"
        android:layout_alignLeft="@+id/edtnome_usu"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="*Nascimento:"
        android:layout_marginTop="10dp"
        android:id="@+id/txtData"
        android:layout_below="@+id/spinnersexo_usu"
        android:layout_alignLeft="@+id/edtnome_usu"
        android:layout_alignStart="@+id/edtnome_usu"
        android:entries="@array/array_sexo"
        android:textColor="#006600"
        android:textSize="15dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/edtdata_usu"
        android:layout_below="@+id/txtData"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Telefone Fixo"
        android:layout_marginTop="10dp"
        android:id="@+id/txttelefone"
        android:layout_below="@+id/edtdata_usu"
        android:layout_alignLeft="@+id/edtnome_usu"
        android:layout_alignStart="@+id/edtnome_usu"
        android:textColor="#006600"
        android:textSize="15dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:ems="10"
        android:id="@+id/edttelefone_usu"
        android:layout_below="@+id/txttelefone"
        android:layout_alignLeft="@+id/edtnome_usu" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Celular:"
        android:layout_marginTop="10dp"
        android:id="@+id/txtcelular"
        android:layout_below="@+id/edttelefone_usu"
        android:layout_alignLeft="@+id/edtnome_usu"
        android:layout_alignStart="@+id/edtnome_usu"
        android:textColor="#006600"
        android:textSize="15dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:ems="10"
        android:id="@+id/edtcelular_usu"
        android:layout_below="@+id/txtcelular"
        android:layout_alignLeft="@+id/edtnome_usu" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="*E-mail:"
        android:layout_marginTop="10dp"
        android:id="@+id/txtemail"
        android:layout_below="@+id/edtcelular_usu"
        android:layout_alignLeft="@+id/edtnome_usu"
        android:layout_alignStart="@+id/edtnome_usu"
        android:textColor="#006600"
        android:textSize="15dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/edtemail_usu"
        android:inputType="textPersonName"
        android:layout_below="@+id/txtemail"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView"
        android:ems="15"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="*Senha:"
        android:layout_marginTop="10dp"
        android:id="@+id/txtsenha"
        android:layout_below="@+id/edtemail_usu"
        android:layout_alignLeft="@+id/edtnome_usu"
        android:layout_alignStart="@+id/edtnome_usu"
        android:textColor="#006600"
        android:textSize="15dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:id="@+id/edtsenha_usu"
        android:layout_below="@+id/txtsenha"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView"
        android:ems="10" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="*Estado:"
        android:layout_marginTop="10dp"
        android:id="@+id/txtestado"
        android:layout_below="@+id/edtsenha_usu"
        android:layout_alignLeft="@+id/edtnome_usu"
        android:layout_alignStart="@+id/edtnome_usu"
        android:textColor="#006600"
        android:textSize="15dp" />

    <Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/spinnerestado_usu"
        android:layout_below="@+id/txtestado"
        android:layout_alignLeft="@+id/edtnome_usu"
        android:layout_alignStart="@+id/edtnome_usu"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="*Cidade:"
        android:layout_marginTop="10dp"
        android:id="@+id/txtcidade"
        android:layout_below="@+id/spinnerestado_usu"
        android:layout_alignLeft="@+id/edtnome_usu"
        android:layout_alignStart="@+id/edtnome_usu"
        android:textColor="#006600"
        android:textSize="15dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:id="@+id/edtcidade_usu"
        android:layout_below="@+id/txtcidade"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView"
        android:ems="10" />


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="*Endereço:"
        android:layout_marginTop="10dp"
        android:id="@+id/txtRua"
        android:layout_below="@+id/edtcidade_usu"
        android:layout_alignLeft="@+id/edtnome_usu"
        android:layout_alignStart="@+id/edtnome_usu"
        android:textColor="#006600"
        android:textSize="15dp" />


    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/edtendereco_usu"
        android:inputType="textPersonName"
        android:layout_below="@+id/txtRua"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginRight="30dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Complemento:"
        android:layout_marginTop="10dp"
        android:id="@+id/txtcomplemento"
        android:layout_below="@+id/edtendereco_usu"
        android:layout_alignLeft="@+id/edtnome_usu"
        android:layout_alignStart="@+id/edtnome_usu"
        android:textColor="#006600"
        android:textSize="15dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/edtcomplemento_usu"
        android:inputType="textPersonName"
        android:layout_below="@+id/txtcomplemento"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginRight="30dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="*Numero:"
        android:layout_marginTop="10dp"
        android:id="@+id/txtnumero"
        android:layout_below="@+id/edtcomplemento_usu"
        android:layout_alignLeft="@+id/edtnome_usu"
        android:layout_alignStart="@+id/edtnome_usu"
        android:textColor="#006600"
        android:textSize="15dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:id="@+id/edtnumero_usu"
        android:layout_below="@+id/txtnumero"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView"
        android:ems="10" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="*Bairro:"
        android:layout_marginTop="10dp"
        android:id="@+id/txtbairro"
        android:layout_below="@+id/edtnumero_usu"
        android:layout_alignLeft="@+id/edtnome_usu"
        android:layout_alignStart="@+id/edtnome_usu"
        android:textColor="#006600"
        android:textSize="15dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/edtbairro_usu"
        android:inputType="textPersonName"
        android:layout_below="@+id/txtbairro"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView"
        android:ems="10" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CEP:"
        android:layout_marginTop="10dp"
        android:id="@+id/txtcep"
        android:layout_below="@+id/edtbairro_usu"
        android:layout_alignLeft="@+id/edtnome_usu"
        android:layout_alignStart="@+id/edtnome_usu"
        android:textColor="#006600"
        android:textSize="15dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/edtcep_usu"
        android:layout_below="@+id/txtcep"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView"
        android:ems="10" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="   Salvar   "
        android:id="@+id/btsalvar_tra"
        android:layout_below="@+id/edtcep_usu"
        android:layout_centerHorizontal="true"
        android:onClick="OnCadastroUsuario"
        android:textColor="#FFF"
        android:textStyle="bold"
        android:background="#009900" />

</RelativeLayout>
</ScrollView>

I made the change you indicated and you made that mistake

09-23 11:59:26.348    2211-2211/spac.com.br.jobbroker W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40a13300)
09-23 11:59:26.398    2211-2211/spac.com.br.jobbroker E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.NullPointerException
    at spac.com.br.jobbroker.Cadastro.Cadastro_Usuario$1.onResponse(Cadastro_Usuario.java:102)
    at spac.com.br.jobbroker.Cadastro.Cadastro_Usuario$1.onResponse(Cadastro_Usuario.java:89)
    at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
    at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
    at android.os.Handler.handleCallback(Handler.java:615)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4745)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    at dalvik.system.NativeStart.main(Native Method)
  • Guilherme, I don’t see much error in this code. Could you include the full Layout? I saw that using the RelativeLayout, has no overlapping problem of View's?

  • I’ll post the full layout, puts so I’m not able to find this error. If there is any way I can improve this layout or know some techniques accepted help, I would have difficulties in this matter.

  • I put your code on my device and saw no error: http://imagecurl.org/images/72620464339968940482.png. Has some code or Listener that interacts with the Spinner?

  • I’ll change the question, show how I’m getting add values in the states, caught by Webservice.

1 answer

2


Ah, I understand the mistake.

Forgot to call the method notifyDatasetChanged in his ArrayAdapter. This is necessary because you are adding the items directly on ArrayList estados.

Alternatively you could add directly to ArrayAdapter, but it is recommended to add the entire collection using the addAll (only in version 11+ of Android), because every addition it will call the notifyDataSetChanged. To add individually, you must use setNotifyOnChange(false), add items using the add(String) and then back to normal with setNotifyOnChange(true) and call the notifyDataSetChanged.

For this you either have to save the reference to the created instance, or you can take Spinner and notify.

The notifyDataSetChanged notifies the Spinner that the model has changed. With this it measures again the View which becomes visible (not the DropDown), calling the method onMeasure in the Adapter to perform the measurement.

Soon must:

JsonArrayRequest req = new JsonArrayRequest(Const.URL_JSON_ARRAY_CAD_USU,
    new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            Log.d(TAG, response.toString());
            hideProgressDialog();

            int aJsonint = 0;
            String aJsonString;

            // Recupera seu adapter
            ArrayAdapter<String> adp = (ArrayAdapter<String>) EstadoUsu.getAdapter();

            // Desabilito a notificao por enquanto, ate terminar de adicionar tudo
            adp.setNotifyOnChange(false);

            try {
                JSONArray jsonarray = response;
                JSONObject jsonobj;

                for (int i=0; i<jsonarray.length(); i++){
                    jsonobj = jsonarray.getJSONObject(i);

                    aJsonString = jsonobj.getString("sigla");
                    aJsonint = jsonobj.getInt("id");
                    System.out.println("ID " + aJsonint + " sigla  " + aJsonString);
                    // Voce pode adicionar aqui, mas nao eh recomendado
                    //estados.add(aJsonString);

                    // Adiciono direto no ArrayAdapter
                    adp.add(aJsonString);
                }

                // Habilitar novamente a notificacao
                adp.setNotifyOnChange(true);
                // Notifica o Spinner de que houve mudanca no modelo
                adp.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());

            System.out.println("Deu ERROR PQP");
            hideProgressDialog();
            msgerro();
            finish();
        }
    }
);
  • I understood only that this is giving an error of "FATAL EXCEPTION: main java.lang.Nullpointerexception " in adp.setNotifyOnChange(false); and I did an if to see if != null and started giving error in adp.add(aJsonString);

  • http://187.45.142.241:8080/umamao/stateWs/list the address I’m picking up states want to take a test

  • I need to know where the NullPointerException, include the error message from LogCat complete in your question.

  • I added my class so I could get a glimpse of how she’s doing

  • @William, forgot to add the ArrayAdapter at the EstadoUsu. I thought that first boot code ArrayAdapter was being executed. Place it between the call of the RetornaJSONEstado and the initialisation of EstadoUsu.

  • Puts my fault having taken... Thank you very much now it worked! helped a lot and thank you even for the explanations.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.