Fill Spinner and Listview - Fragment

Asked

Viewed 248 times

1

I am developing an application with Fragment. I have two Fragments, where in one there is a Listview and in the other a Spinner.

Listview and Spinner are populated with data coming from the database.

During the debugging I realized that when it arrives in the setAdapter method: listview.setAdapter(Adapter) or spinner.setAdapter(Adapter) an error is generated and enters the Catch(Exception) block).

The mistake is this:

Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

I already followed the debugging, the data is coming from the database, everything is correct more for this line of catch(Execption).

In both cases (Spinner and Listview filling) the error is same.

Follow the Oncreateview code:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View mae = inflater.inflate(R.layout.fragment_usar_produto, container, false);
    spProduto = (Spinner)mae.findViewById(R.id.spProduto);
    npQuantidade = (NumberPicker)mae.findViewById(R.id.npQuantidade);

    npQuantidade.setMinValue(0);
    npQuantidade.setMaxValue(1000);
    npQuantidade.setValue(30);
    npQuantidade.setWrapSelectorWheel(false);

    preencherSpinner();


    btAtualizar = (Button)mae.findViewById(R.id.btAtualizar);
    btAtualizar.setOnClickListener(atualizar);


    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_usar_produto, container, false);
}

Now the Spinner method code

   public void preencherSpinner()
{
    StringBuilder sql = new StringBuilder();
    sql.append("SELECT * FROM validade ORDER BY produto");

    Validade val = new Validade();

    cursorProdutos = val.listarProduto(getActivity().getBaseContext());

    ArrayList<String> listaProdutos = new ArrayList<String>();

    if (cursorProdutos.moveToFirst()) {
        do {
            listaProdutos.add(cursorProdutos.getString(1));
        } while (cursorProdutos.moveToNext());
    }

    try
    {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_list_item_1,listaProdutos);

        spProduto.setAdapter(adapter);
    }
    catch (Exception ex)
    {
        Log.d("exceção", ex.getMessage());
    }


}
  • I emphasize that the same code above is working normally when implementing directly in an Activity. The error happens when you are inside a Fragment.

  • 1

    R.id.spProduto is a spinner? Exists in the layout fragment_usar_product? Note also that the method onCreateView() must return mae and not inflater.inflate(R.layout.fragment_usar_produto, container, false);

  • The Error was this, it should return mother instead of Inflater.inflate....

No answers

Browser other questions tagged

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