androidlistviewandroid-fragmentsgetview

getView() not called even when getCount() has results


Sorry for my english, not my first language. Im creating an app in Android and I have a issue:

I have a TabBar with 2 fragments (1 - ProductFragment and 2 - CartFragment), in second Fragment (CartFragment) I have a ListView and that ListView is initial null.

CartFragment Layout:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:app="http://schemas.android.com/apk/res-auto"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:padding="15dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

               <ListView
                   android:layout_width="match_parent"
                   android:layout_height="match_parent"
                   android:id="@+id/lancarvenda_carrinho_lvwresultado"
                   android:orientation="vertical" />

    </LinearLayout>
</FrameLayout>

In ProductFragment I have a button with onclick, that onclick Intents another activity and in that activity I add values in my public Custom List:

public static List<PesquisarProdutoResponse> Carrinho = new ArrayList<>();

When I done with adding values that I need, I close that activity and return to TabBar and expects that ListView has been populated.

The method that populate my public list:

private void PesquisarProduto()
{
    RequestQueue sQueue = Volley.newRequestQueue(getActivity());
    String sEnderecoBase = "http://www.my-url";

    StringRequest sRequest = new StringRequest(Request.Method.POST, sEnderecoBase, new Response.Listener<String>() {
        @Override
        public void onResponse(String response)
        {
            PesquisarProdutoResponse sResultado = new Gson().fromJson((String) response, PesquisarProdutoResponse.class);
            if (sResultado.getCodigoRetorno() != 0)
            {
                //lastText = "Produto não encontrado";
                //barcodeView.setStatusText("Produto não encontrado");
            }
            else
            {

                Variaveis.Carrinho.add(sResultado);

                try {
                    List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar = new ArrayList<>();

                    for (int i = 0; i < Variaveis.Carrinho.size(); i++) {
                        PesquisarProdutoObjetoRetorno sItem = Variaveis.Carrinho.get(i).getDadosProduto();
                        sCarrinhoAuxiliar.add(sItem);
                    }

                    LancarVendaCarrinhoListViewAdapter sAdaptador = new LancarVendaCarrinhoListViewAdapter(getActivity(),
                            sCarrinhoAuxiliar);
                    fCarrinhoResultado.setAdapter(sAdaptador);
                    sAdaptador.notifyDataSetChanged();

                    Object oi = fCarrinhoResultado.getCount();
                    oi.toString();

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }, new Response.ErrorListener()
    {
        @Override
        public void onErrorResponse(VolleyError error)
        {
            byte[] sBytesResposta = error.networkResponse.data;
            String sTexto = new String(sBytesResposta);
            Mensagem.ExibirAlert(getActivity(), String.valueOf(error.networkResponse.statusCode));
        }
    })
    {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError
        {
            Map<String, String> sHeaders = new HashMap<>();
            sHeaders.put("Authorization", "Bearer " + Variaveis.ApiToken);
            return sHeaders;
        }

        @Override
        public byte[] getBody() throws AuthFailureError
        {
            return new Gson().toJson(sCorpoBusca).getBytes();
        }

        @Override
        public String getBodyContentType()
        {
            return "application/json";
        }
    };

    sQueue.add(sRequest);
}

ListView Adapter:

public class LancarVendaCarrinhoListViewAdapter extends BaseAdapter
{

private Context mContext;
//private LayoutInflater mInflater;
private List<PesquisarProdutoObjetoRetorno> mDataSource;

public LancarVendaCarrinhoListViewAdapter(Context context, List<PesquisarProdutoObjetoRetorno> items)
{
    mContext = context;
    mDataSource = items;
}

@Override
public int getCount() {
    return mDataSource.size();
}

@Override
public Object getItem(int position) {
    return mDataSource.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    try
    {
        LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View sView = mInflater.inflate(R.layout.activity_lancarvenda_carrinho_list_view_item, parent, false);

        PesquisarProdutoObjetoRetorno sItem = (PesquisarProdutoObjetoRetorno) getItem(position);

        TextView descricao = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txtdescricao);
        descricao.setText(sItem.getDescricao());

        TextView preco = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txvpreco);
        preco.setText(String.valueOf(sItem.getPreco()));

        EditText quantidade = (EditText)sView.findViewById(R.id.lancarvenda_carrinho_item_etquantidade);
        quantidade.setText("1");

        return sView;
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }
}
}

My layout of row:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/lancarvenda_carrinho_item_imvFoto"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center_horizontal"
            android:background="@drawable/circulo_foto2"
            app:border_color="#898989"
            app:border_width="2dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_marginLeft="10dp">

            <TextView
                android:id="@+id/lancarvenda_carrinho_item_txtdescricao"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:text="Relogio"
                android:textSize="20dp"
                android:textStyle="bold"
                android:layout_marginRight="8dp"
                android:lines="2"
                android:minLines="2"
                android:singleLine="false"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

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

                    <TextView
                        android:id="@+id/lancarvenda_carrinho_item_txvpreco"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="8dp"
                        android:text="R$ 399,89"
                        android:textColor="#1ba39c"
                        android:textSize="20dp"
                        android:layout_marginRight="70dp"/>

                    <EditText
                        android:id="@+id/lancarvenda_carrinho_item_etquantidade"
                        android:layout_width="50dp"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:backgroundTint="#9a9b9c"
                        android:hint="0"
                        android:textColor="#2a2d2e"
                        android:layout_marginRight="8dp"/>

                </RelativeLayout>

            </LinearLayout>
        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

In debug mode, when code pass in getCount in Adapter, I have size more than 1 and my list still not show! Even if I close TabBar and reopen and set adapter (with values) on onCreate method. What can I do to my ListView show?

EDIT I inflate listview on onCreate:

    super.onCreate(savedInstanceState);

    LayoutInflater sInflater = getActivity().getLayoutInflater();
    View sView = sInflater.inflate(R.layout.fragment_lancarvenda_carrinho, null);

    fCarrinhoResultado = (ListView) sView.findViewById(R.id.lancarvenda_carrinho_lvwresultado);

Solution

  • I got help from another forum and I was able to solve my problem:

    I override two methods: OnCreate (inflate and receive view) and OnCreateView (find the product and put on listview), I eliminate method OnCreate and put everything on OnCreateView!

    That solve my problem! Thanks to everybody!