即使getCount()有结果

时间:2017-03-30 19:37:11

标签: android listview android-fragments getview

抱歉我的英语,而不是我的第一语言。 我正在Android中创建一个应用程序,我有一个问题:

我有一个TabBar有2个片段(1 - ProductFragment和2 - CartFragment),在第二个片段(CartFragment)中我有ListView并且ListView是最初null

CartFragment布局:

<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>

ProductFragment我有一个onclick按钮,onclick Intents另一个活动,在该活动中我在公共自定义列表中添加了值:

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

当我添加了我需要的值时,我会关闭该活动并返回TabBar并期望ListView已填充。

填充公开列表的方法:

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适配器:

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;
    }
}
}

我的行布局:

<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>

在调试模式下,当代码在getCount Adapter中传递时,我的大小超过1而我的列表仍未显示!即使我关闭TabBar并重新打开并在onCreate方法上设置适配器(带值)。 我可以对ListView节目做些什么?

修改 我在listview上充气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);

3 个答案:

答案 0 :(得分:0)

尝试使列表成为类的成员而不是本地变量

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>() {

        // Make cart list a private data member so it doesn't loose scope //
        List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar; 

        @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 {
                    sCarrinhoAuxiliar = new ArrayList<>();
                    ...
                }
                ...
             }
             ...
         }
         ...
     }
     ...
}

答案 1 :(得分:0)

将您的列表sCarrinhoAuxiliar和适配器sAdaptador声明为global

更新您的OnCreateView(),如下所示:

// Global
List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar;
LancarVendaCarrinhoListViewAdapter sAdaptador;

.........................

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

    ....................
    ........................

    sCarrinhoAuxiliar = new ArrayList<>();
    sAdaptador = new LancarVendaCarrinhoListViewAdapter(getActivity(), sCarrinhoAuxiliar);
    fCarrinhoResultado.setAdapter(sAdaptador);

    .......................
    ...............
}

更新您的onResponse()方法,如下所示:

@Override
public void onResponse(String response) {

    .....................
    ..........................
    try {
        // Clear old data
        sCarrinhoAuxiliar.clear();

        for (int i = 0; i < Variaveis.Carrinho.size(); i++) {
            PesquisarProdutoObjetoRetorno sItem = Variaveis.Carrinho.get(i).getDadosProduto();
            sCarrinhoAuxiliar.add(sItem);
        }
        // Update list        
        sAdaptador.notifyDataSetChanged();
        .............
        ....................
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

希望这会有所帮助〜

答案 2 :(得分:0)

我从另一个论坛得到了帮助,我能够解决我的问题:

我覆盖了两个方法:OnCreate(inflate和receive view)和OnCreateView(找到产品并放在listview上),我删除OnCreate方法并将所有内容放在OnCreateView上!

解决了我的问题! 谢谢大家!