Set text of selected item in Spinner for an Edittext

Asked

Viewed 449 times

0

First of all forgive the lack of knowledge and technical errors, I’m starting in the area.

I need to send the information of a spinner to a database and the solution I proposed was to set the text of the selected item to an Edittext and that Edittext to be sent to the database.

This Edittext sits on a Alertdialog in Adapterhistorico.java outside my Fragmentohistorico fragment.java.

Here is the code of Alertdialog:

 private void editTaskDialog(final DataHistorico pedidos){



    LayoutInflater inflater = LayoutInflater.from(context);
    View subView = inflater.inflate(R.layout.layout_edt_pedido, null);

    spinner1 = (Spinner) subView.findViewById(R.id.spinner);
    spinner1.setOnItemSelectedListener(new ItemSelectedListener());



    final EditText campoId = (EditText)subView.findViewById(R.id.etPedido_Id);
    final EditText campoCliente = (EditText)subView.findViewById(R.id.etPedido_Cliente);
    final EditText campoStatus = (EditText)subView.findViewById(R.id.etPedido_Status);
    final EditText campoEndereco = (EditText)subView.findViewById(R.id.etPedido_Endereco);
    final EditText campoTotal = (EditText)subView.findViewById(R.id.etPedido_Total);

    if(pedidos != null){
        campoId.setText(pedidos.getId());
        campoCliente.setText(pedidos.getCliente());
        campoStatus.setText(String.valueOf(pedidos.getStatus()));
        campoEndereco.setText(String.valueOf(pedidos.getEndereco()));
        campoTotal.setText(String.valueOf(pedidos.getTotal()));
    }


    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("Editar pedido");
    builder.setView(subView);
    builder.create();

    builder.setPositiveButton("SALVAR", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            final String id = campoId.getText().toString();
            final String cliente = campoCliente.getText().toString();
            final String status = campoStatus.getText().toString();
            final String endereco = campoEndereco.getText().toString();
            final String total = campoTotal.getText().toString();

            if(TextUtils.isEmpty(cliente) || TextUtils.isEmpty(status) || TextUtils.isEmpty(endereco) || TextUtils.isEmpty(total)){
                Toast.makeText(context, "Algo está errado. Cheque os dados digitados.", Toast.LENGTH_LONG).show();
            }
            else{

                new ServiceLogin().execute(id, cliente, endereco, status, total);
            }
        }
    });



    builder.setNegativeButton("CANCELAR", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {


           //DynamicToast.make(context, "Operação cancelada.", AppCompatResources.getDrawable(context, R.drawable.ic_pedido_em_andamento), Color.parseColor("#FFFFFF"), Color.parseColor("#000000"), Toast.LENGTH_LONG).show();
            Toast.makeText(context, "Operação cancelada", Toast.LENGTH_LONG).show();

        }
    });
    builder.show();
}

And just below the class Itemselectedlistener:

public class ItemSelectedListener implements AdapterView.OnItemSelectedListener {


    final EditText campoStatus = (EditText) ((Activity)context).findViewById(R.id.etStatusAux);

    //get strings of first item
    String firstItem = String.valueOf(spinner1.getSelectedItem());

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



        if (firstItem.equals(String.valueOf(spinner1.getSelectedItem()))) {
            //campoStatus.setText("");
        } else {
            campoStatus.setText(parent.getItemAtPosition(pos).toString());


        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg) {

    }

}

Any way I try doesn’t work or the app closes when onItemSelected is activated as is the case with this line that I made passing the context of Adapterhistorico:

final EditText campoStatus = (EditText) ((Activity)context).findViewById(R.id.etPedido_Status);

EDIT:

Error log:

java.lang.Nullpointerexception: Attempt to invoke virtual method 'void android.widget.Textview.setText(java.lang.Charsequence)' on a null Object Reference at com.beliasdev.cadjobel.adapter.Adapterhistorico$Itemselectedlistener.onItemSelected(Adapterhistorico.java:227)

I think Spinner is working in a different context than Alertdialog so the error occurs and the app closes after an item is selected.

If someone has a better solution to my problem of sending the information of the spinner with the other Edittexts in Alertdialog to the database feel free to comment.

EDIT 2:

public class AdapterHistorico extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements AdapterView.OnItemSelectedListener {


private String cancelado;
private String dateold;
private String datenew;
private String concluido;
private String em_andamento;
private String status;
private Context context;
private LayoutInflater inflater;
List<DataHistorico> data= Collections.emptyList();
DataHistorico current;
int currentPos=0;


// create constructor to innitilize context and data sent from MainActivity
public AdapterHistorico(Context context, List<DataHistorico> data){
    this.context=context;
    inflater= LayoutInflater.from(context);
    this.data=data;
}


// Inflate the layout when viewholder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view=inflater.inflate(R.layout.container_historico, parent,false);

    MyHolder holder=new MyHolder(view);

    return holder;
}

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


    // Aqui você está apto a obter o valor selecionado!
    String item = parent.getItemAtPosition(pos).toString();


}


public void onNothingSelected(AdapterView<?> parent) {

}



// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
   final DataHistorico pedidos = data.get(position);

    // Get current position of item in recyclerview to bind data and assign values from list
    MyHolder myHolder= (MyHolder) holder;
    DataHistorico current = data.get(position);



    /* if (current.pStatus.equals("concluido")) {
        // ToDo when first item is selected
    }

   if(current.pStatus == "") {
        spinner.setSelection(getIndex(spinner, "concluido"));
    }*/

    dateold = current.pData;
    try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yyyy 'ás' HH:mm:ss");
        datenew = df2.format(format.parse(dateold));

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    myHolder.txtPedidoCliente.setText(current.pCliente);

    myHolder.txtPedidoData.setText(datenew);

    myHolder.txtPedidoTotal.setText("R$ " + current.pTotal);

    myHolder.edtPedido.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            editTaskDialog(pedidos);
        }
    });


    // load image into imageview using glide
    concluido = "concluido";
    cancelado = "cancelado";
    em_andamento= "em_andamento";
    status = current.pStatus;
    if (status.equals(concluido)) {
        Glide.with(context).load(R.drawable.ic_pedido_concluido).into(myHolder.imgPedidoStatus);
    } else if (status.equals(cancelado)) {
        Glide.with(context).load(R.drawable.ic_pedido_cancelado).into(myHolder.imgPedidoStatus);
    }else if (status.equals(em_andamento)) {
        Glide.with(context).load(R.drawable.ic_pedido_em_andamento).into(myHolder.imgPedidoStatus);
    }


}



// return total item from List
@Override
public int getItemCount() {
    return data.size();
}



private void editTaskDialog(final DataHistorico pedidos){

    LayoutInflater inflater = LayoutInflater.from(context);
    View subView = inflater.inflate(R.layout.layout_edt_pedido, null);

    Spinner spinner = (Spinner) subView.findViewById(R.id.spinner);
    spinner.setOnItemSelectedListener(this); // Adicionado

    final EditText campoId = (EditText)subView.findViewById(R.id.etPedido_Id);
    final EditText campoCliente = (EditText)subView.findViewById(R.id.etPedido_Cliente);
    final EditText campoStatus = (EditText)subView.findViewById(R.id.etPedido_Status);
    final EditText campoEndereco = (EditText)subView.findViewById(R.id.etPedido_Endereco);
    final EditText campoTotal = (EditText)subView.findViewById(R.id.etPedido_Total);

    if(pedidos != null){
        campoId.setText(pedidos.getId());
        campoCliente.setText(pedidos.getCliente());
        campoStatus.setText(String.valueOf(pedidos.getStatus()));
        campoEndereco.setText(String.valueOf(pedidos.getEndereco()));
        campoTotal.setText(String.valueOf(pedidos.getTotal()));
    }


    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("Editar pedido");
    builder.setView(subView);
    builder.create();

    builder.setPositiveButton("SALVAR", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            final String id = campoId.getText().toString();
            final String cliente = campoCliente.getText().toString();
            final String status = campoStatus.getText().toString();
            final String endereco = campoEndereco.getText().toString();
            final String total = campoTotal.getText().toString();

            if(TextUtils.isEmpty(cliente) || TextUtils.isEmpty(status) || TextUtils.isEmpty(endereco) || TextUtils.isEmpty(total)){
                Toast.makeText(context, "Algo está errado. Cheque os dados digitados.", Toast.LENGTH_LONG).show();
            }
            else{

                new ServiceLogin().execute(id, cliente, endereco, status, total);
            }
        }
    });



    builder.setNegativeButton("CANCELAR", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {


           //DynamicToast.make(context, "Operação cancelada.", AppCompatResources.getDrawable(context, R.drawable.ic_pedido_em_andamento), Color.parseColor("#FFFFFF"), Color.parseColor("#000000"), Toast.LENGTH_LONG).show();
            Toast.makeText(context, "Operação cancelada", Toast.LENGTH_LONG).show();

        }
    });
    builder.show();
}


private class ServiceLogin extends AsyncTask<String, Void, String> {

    ProgressDialog mProgressDialog;
    private String res;

    @Override
    protected void onPreExecute() {
        mProgressDialog = ProgressDialog.show(context,
                "", "Aguarde...");
    }

    @Override
    protected String doInBackground(String... params) {
        res = null;
        PutUtility put = new PutUtility();

        put.setParam("id", params[0].toString());
        put.setParam("pedido_cliente", params[1].toString());
        put.setParam("pedido_endereco", params[2].toString());
        put.setParam("pedido_status", params[3].toString());
        put.setParam("pedido_total", params[4].toString());

        try {
            res = put.postData("http://10.0.2.2/cadjobel/public/edt-pedido-app.php");
            Log.v("res", res);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;

    }

    protected void onPostExecute(String res) {
        mProgressDialog.dismiss();
        DynamicToast.makeSuccess(context, "Pedido editado com sucesso", Toast.LENGTH_LONG).show();
    }
}


class MyHolder extends RecyclerView.ViewHolder{

    TextView txtPedidoCliente;
    ImageView imgPedidoStatus;
    TextView txtPedidoData;
    TextView txtPedidoTotal;
    ImageView edtPedido;


    // create constructor to get widget reference
    public MyHolder(View itemView) {
        super(itemView);
        txtPedidoCliente= (TextView) itemView.findViewById(R.id.txtPedidoCliente);
        imgPedidoStatus= (ImageView) itemView.findViewById(R.id.imgPedidoStatus);
        txtPedidoData = (TextView) itemView.findViewById(R.id.txtPedidoData);
        txtPedidoTotal = (TextView) itemView.findViewById(R.id.txtPedidoTotal);
        edtPedido = (ImageView) itemView.findViewById(R.id.edtPedido);
    }

}

}

  • Good night, John Victor! To make it easier to find out what’s wrong with your code, edit your question and include some error message that appears in the log.

  • Oh sorry, I forgot to include the error that appears in the log. It has already been edited.

  • That stream to get data in AlertDialog, of asynchronous calls to databases and tals, usually it can be solved using the standard Communicator... I think it applies in your case

  • Specifically speaking, regarding the error, you are trying to instantiate a view that is the EditTextView in a place not at all appropriated and making cast of a null Context reference

  • I’ll try to rearrange your code and solve your problem

1 answer

0


As you request, you need to get the selected item from Spinner. Remove his instantiation from within the method editTaskDialog and put in the onCreate of Activity

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Spinner spinner = (Spinner) findViewById(R.id.id_do_seu_spinner);
}

Now his Activityshall implement the interface with the return methods of selection

public class NomeDaSuaActivity extends Activity implements OnItemSelectedListener {

    /*...*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       Toolbar toolbar = findViewById(R.id.toolbar);
       setSupportActionBar(toolbar);

       Spinner spinner = (Spinner) findViewById(R.id.id_do_seu_spinner);
               spinner.setOnItemSelectedListener(this); // Adicionado
    }

    public void onItemSelected(AdapterView<?> parent, View view,
            int pos, long id) {
        // Aqui você está apto a obter o valor selecionado!
        int item = parent.getItemAtPosition(pos)
    }

    public void onNothingSelected(AdapterView<?> parent) {

    }
}

Finally, ItemSelectedListener makes no more sense to us and, in theory, your problem is solved since it is he who is causing the mess. Remembering that ItemSelectedListener that the Activity implements is not the class you created.

You now have to uncouple the Adapter button as follows: create an interface

public interface Communicator<T> {
   void onEvent(T data);
}

It will be useful to communicate the Adapter click event to Activity. Implement this interface on Activity, change the method editTaskDialog to her and pass a reference to your Adapter

public class NomeDaSuaActivity extends Activity implements OnItemSelectedListener, Communicator<seu_tipo_de_objeto> {
        private SeuAdapter mAdapter;
        /*...*/

        @Override
        protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
           Toolbar toolbar = findViewById(R.id.toolbar);
           setSupportActionBar(toolbar);

           mAdapter = new SeuAdapter(this); // Passando uma referência para acionar o evento
           Spinner spinner = (Spinner) findViewById(R.id.id_do_seu_spinner);
                   spinner.setOnItemSelectedListener(this); // Adicionado
        }

        public void onItemSelected(AdapterView<?> parent, View view,
                int pos, long id) {
            // Aqui você está apto a obter o valor selecionado!
            int item = parent.getItemAtPosition(pos)
        }

        public void onNothingSelected(AdapterView<?> parent) {

        }

        @override
        public void onEvent(seu_tipo_de_objeto data) {
            /* Finalmente chame editTaskDialog */
           this.editTaskDialog();
        }

        public void editTaskDialog() {
            /*...*/
        } 
    }

Whenever the button is clicked on the Adapter you must trigger the onEvent, as follows

Attach a button-click event in the ViewHolder and add this class to the Adapter class for ease of use listener.onEvent()

protected class SeuViewHolder extends RecyclerView.ViewHolder 
  implements View.OnClickListener{
    public Button seuBotao;

    /*...*/

    public SeuViewHolder(View v) {
         seuBotao = v.findViewById(R.id.id_do_botao);
         seuBotao.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
       if(v.getId() == R.id.id_do_botao) {
         TipoDoSeuObjeto data = seuListaDeObj.get(getAdapterPosition());

         /* Isso aciona o método que vai abrir seu dialog na Activity */
         listener.onEvent(data);
       }
    }
}

And finally, on your Adapter do the following

   private Communicator<seu_tipo_de_objeto> listener;

    // create constructor to innitilize context and data sent from MainActivity
    public AdapterHistorico(Context context, List<DataHistorico> data, Communicator<seu_tipo_de_objeto> listener){
        this.context=context;
        inflater= LayoutInflater.from(context);
        this.data=data;
        this.listener = listener;
    }
    // Inflate the layout when viewholder created
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view=inflater.inflate(R.layout.container_historico, parent,false);

        MyHolder holder=new MyHolder(view);

        return holder;
    }

That way, things that couldn’t be done on the Adapter stay on the Activity. You can adapt the code to a Fragment if you want. Change seu_tipo_de_objeto in the interface for the type of object you want to send. This certainly solves the problem, just adapt it to your code.

  • Sorry to keep you waiting. But if I take the instantiation from within the editTaskDialog method the app gives a crash pq the spinner appears in the same view of editTaskDialog and so needs to be within the same method.

  • And where your method editTaskDialog is?

  • Within the Adapterhistorico class.

  • public class AdapterHistorico extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements AdapterView.OnItemSelectedListener {...&#xA;&#xA;public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {...&#xA;&#xA;public void onItemSelected(...&#xA;...&#xA;private void editTaskDialog(final DataHistorico pedidos){&#xA; &#xA; LayoutInflater inflater = LayoutInflater.from(context);&#xA; View subView = inflater.inflate(R.layout.layout_edt_pedido, null); &#xA;&#xA;Spinner spinner = (Spinner) subView.findViewById(R.id.spinner);&#xA; spinner.setOnItemSelectedListener(this);&#xA;...

  • @Joaovictormenom, edit your question with the code. In the comment not to understand anything

  • I have a fragment and this fragment has a Listview that is in Adapterhistorico.java and in this same class that is contained editTaskDialog

  • Okay, I’ll edit.

  • Why are you using an Adapter to RecyclerView with a ListView? Why don’t you use a RecyclerView

  • "This Edittext sits on a Alertdialog in Adapterhistorico.java outside my Fragmentohistorico fragment.java.", you must create the AlertDialog within the Activity/Fragment and not in the adapter. He should care only about the list.

  • is a Recycleview even, not Listview, confused me.

  • That’s why Recycleview has a button that when it is clicked Alertdialog is shown, and as Recycleview is in Adapter I put Alertdialog there.

  • I understood what your intention was. Each item in the list should have a button that when clicked opens the AlertDialog, that’s it?

  • That, Recycleview items are returned from the database and have an edit button on each of the items.

  • I’ll edit my answer to fit your problem

Show 9 more comments

Browser other questions tagged

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