RecyclerView没有显示项目

时间:2018-12-27 07:36:40

标签: android android-recyclerview android-asynctask

我创建了一个应用程序,该应用程序在放置在Fragment中的RecyclerView中显示食物订单。使用AsyncTask检索食品订单详细信息。但是以某种方式在片段中什么也没有显示。它保持空白。我一定会忘记或忽略某些东西。

这是订单片段:

public class OrdersFragment extends Fragment {
RecyclerView recyclerView;
private OrdersAdapter adapter;
RecyclerView.LayoutManager layoutManager;
private static List<Orders> orderslist;



 public static final MediaType JSON = MediaType.parse("application/json; 
charset=utf-8");

SharedPreferences sharedPreferences;
View view;

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

    sharedPreferences = getActivity().getSharedPreferences("UserInfo",0);
    view = inflater.inflate(R.layout.fragment_orders, container, false);

    recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
    orderslist = new ArrayList<>();

    new load_orders().execute();


    return view;
}




   public class load_orders extends AsyncTask<String, Void, Void>  {
        @Override
        protected Void doInBackground(String... strings) {
            try{
                OkHttpClient client = new OkHttpClient();
                JSONObject json = new JSONObject();
                JSONObject datajson = new JSONObject();
                datajson.put("command","ecoexpress_orders");
                datajson.put("username", 
sharedPreferences.getString("Username",null));
                json.put("data",datajson);

                RequestBody body = RequestBody.create(JSON, 
json.toString());

                Request request = new Request.Builder()
                        .url("https://api.watext.com/hook/insert_pagetoken")
                        .post(body)
                        .addHeader("content-type", "application/json")
                        .addHeader("cache-control", "no-cache")
                        .addHeader("postman-token", "55747e8a-0a9a-1fd5-77b0-8af0027be1f1")
                        .build();
                Response response = client.newCall(request).execute();

                JSONObject responseJSON = new JSONObject(response.body().string());
                JSONArray messageArray = responseJSON.getJSONArray("message");



                for (int i = 0; i < messageArray.length(); i ++ ){


                    JSONObject order_item = messageArray.getJSONObject(i);
                    Orders orders = new Orders(order_item.getString("order_id"),
                            order_item.getString("order_details"));

                    orderslist.add(orders);

                }

            }
            catch (Exception e){


                return null;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            layoutManager = new LinearLayoutManager(getActivity());

            adapter = new OrdersAdapter(getContext(),orderslist);

            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setAdapter(adapter);
        //adapter.notifyDataSetChanged();
        }
    }



}

这是模型Order.class:

public class Orders {


        private String order_id;
        private String order_details;

        public Orders(String order_id, String order_details) {
            this.order_id = order_id;
            this.order_details = order_details;
        }

        public String getOrder_id() {
            return order_id;
        }

        public void setOrder_id(String order_id) {
            this.order_id = order_id;
        }

        public String getOrder_details() {
            return order_details;
        }

        public void setOrder_details(String order_details) {
            this.order_details = order_details;
        }

}

这是OrdersAdapter:

public class OrdersAdapter extends RecyclerView.Adapter<OrdersAdapter.ViewHolder> {

    private Context ctx;
    private List<Orders> list;


    public OrdersAdapter(Context ctx, List<Orders> list) {
        this.ctx = ctx;
        this.list = list;
    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cards_layout, viewGroup, false);

        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int i) {

       viewHolder.id.setText(list.get(i).getOrder_id());
        viewHolder.details.setText(list.get(i).getOrder_details());

    }

    @Override
    public int getItemCount() {

        return list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        public TextView id, details;

        public ViewHolder( View itemView) {
            super(itemView);

            id = (TextView)itemView.findViewById(R.id.orderID_textview);
            details = (TextView)itemView.findViewById(R.id.orderDetails_textview);

        }
    }
}

这是OrdersFragment的布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">


       <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="vertical"

            />



</RelativeLayout>

CardView的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
   >

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        card_view:cardBackgroundColor="@color/colorPrimary"
        card_view:cardCornerRadius="10dp"
        card_view:cardElevation="5dp"
        card_view:cardUseCompatPadding="true">

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



            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="12dp"
                android:layout_weight="2"
                android:orientation="vertical"
                >

                <TextView
                    android:id="@+id/orderID_textview"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="10dp"
                    android:text="Order ID"
                   />

                <TextView
                    android:id="@+id/orderDetails_textview"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="10dp"

                    android:text="Order Details"
                   />

            </LinearLayout>
        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

谢谢!

4 个答案:

答案 0 :(得分:0)

我注意到您有RecyclerView.LayoutManager作为布局管理器,将其更改为LinearLayout.LayoutManager,它应该可以正常工作。

答案 1 :(得分:0)

我同意答案 @Piyush ,应将列表检查为空,如果确定数据列表不为空,则必须将 match_parent 更改为 wrap_content 并在根布局视图中添加最小高度(在项目布局xml中添加到CardView的LinearLayoutView父对象)

例如:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:minHeight="70dp"
>
....

编辑

根据@Raghavendra的要求,我可以给解释性文章解释为什么我们必须在商品布局中设置最小高度,如果您想有趣的话,请阅读这篇好文章:

RecyclerView 23.2.0 and item height

Android Support Library 23.2

答案 2 :(得分:0)

尝试像这样在您的recyclerview适配器中初始化arraylist:-

List<Orders> list = new Arraylist<>();

答案 3 :(得分:0)

  1. {[ loginError ? ( <Fragment> <input className={classNames( classes.formItem, classes.formError, )} placeholder="write number" name="login" type="text" onChange={this.handleChange} /> <div className={classes.textError}>{loginError}</div> </Fragment> ) : ( <input className={classes.formItem} placeholder="write number" name="login" type="text" onChange={this.handleChange} /> ), ]} 更改为RecyclerView.LayoutManager
  2. 通过LinearLayoutManager初始化LinearLayoutManager

    onCreateView

  3. 在下一行中将layoutManager = new LinearLayoutManager(getActivity());分配给layoutManager,例如:

    recyclerview

  4. 请勿将您的recyclerView.setLayoutManager(layoutManager);设为静态。

还请检查list中的列表大小,并尝试不初始化并在adapter中设置layoutManager