qq_34424362
qq_34424362
2019-03-26 12:08
采纳率: 50%
浏览 588

RecycleView代码不更新!

RecycleView代码不更新!更新代码应该怎么写呢,有没有人教一下
网络数据取到了,Recycleview 没显示出来数据

public class FoodFragment extends Fragment {
    public RecyclerView mFoodRecyclerView;//定义RecyclerView
    //定义以goodsentity实体类为对象的数据集合
    private ArrayList<FoodEntity> goodsEntityList = new ArrayList<FoodEntity>();
    //自定义recyclerveiw的适配器
    private FoodRecycleAdapter mRecyclerAdapter;
    private JSONArray array;



    public  FoodFragment() {
    }

    private static ChangeFoodFragment changeFoodFragment;

    public static FoodFragment newInstance(ChangeFoodFragment foodFragment){
        changeFoodFragment = foodFragment;
        Bundle args = new Bundle();

        FoodFragment fragment = new FoodFragment();
        fragment.setArguments(args);
        return fragment;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View  view = inflater.inflate(R.layout.recyclerview_food, container, false);
        //对recycleview进行配置

        return view;
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
        initRecyclerView(view);





    }
    private void initData() {
        new Thread(){
            public void run()
            {
                String url = DocUtil.food_list;
                OkHttpClient okHttpClient = new OkHttpClient();

                String token= CacheUtils.getString(getActivity(), "token", "");
                RequestBody body = new FormBody.Builder()
                        .add("token",token)
                        .build();

                Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();

                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    //System.out.println(response.body().string());
                    try {
                        final String string=response.body().string();
                        final JSONObject object=new JSONObject(string);

                        array=object.getJSONArray("list");
                        System.out.println(array);
                        if(array.length()>0) {

                            try {
                                FoodEntity foodEntity =new FoodEntity();
                                for(int i=0;i<array.length();i++){
                                    JSONObject object1=array.getJSONObject(i);
                                    foodEntity.setFoodtitle(object1.getString("foodtitle"));
                                    foodEntity.setFoodcontent(object1.getString("foodcontent"));
                                    foodEntity.setFoodcontentimg(object1.getString("foodcontentimg"));
                                    System.out.println(object1.getString("foodtitle"));
                                    System.out.println(object1.getString("foodcontent"));
                                    System.out.println(object1.getString("foodcontentimg"));



                                }



                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }else {
                            Toast.makeText(getActivity(), "无数据", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();




//        for (int i=0;i<10;i++){
//            FoodEntity foodEntity =new FoodEntity();
//            foodEntity.setName("模拟数据FOOD"+i);
//            foodEntity.setContent("100"+i);
//            goodsEntityList.add(foodEntity);
//        }
    }
    private void initRecyclerView(View view) {
        //获取RecyclerView
        mFoodRecyclerView=view.findViewById(R.id.food_recyclerView);
        //创建adapter
        mRecyclerAdapter = new FoodRecycleAdapter(getActivity(), goodsEntityList);
        //给RecyclerView设置adapter
        mFoodRecyclerView.setAdapter( mRecyclerAdapter );
        //设置layoutManager,可以设置显示效果,是线性布局、grid布局,还是瀑布流布局
        //参数是:上下文、列表方向(横向还是纵向)、是否倒叙
        mFoodRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        //设置item的分割线
        mFoodRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL));


        //RecyclerView中没有item的监听事件,需要自己在适配器中写一个监听事件的接口。参数根据自定义
        mRecyclerAdapter.setOnItemClickListener(new FoodRecycleAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, FoodEntity data) {
                Toast.makeText(getActivity(),"我是item",Toast.LENGTH_SHORT).show();
                changeToAnotherFragment();
            }
        });

    }
    @SuppressLint("ResourceType")
    private void changeToAnotherFragment() {
        changeFoodFragment.changeFoodFragment();
    }
}

public class FoodRecycleAdapter extends RecyclerView.Adapter<FoodRecycleAdapter.myViewHodler>{

    private Context context;
    private ArrayList<FoodEntity> goodsEntityList;
    private ImageLoaderConfiguration configuration;
    public DisplayImageOptions imageOptions;
    private FoodRecycleAdapter adapter;


    //创建构造函数
    public FoodRecycleAdapter(Context context, ArrayList<FoodEntity> goodsEntityList) {
        //将传递过来的数据,赋值给本地变量
        this.context = context;//上下文
        this.goodsEntityList = goodsEntityList;//实体类数据ArrayList
    }

    /**
     * 创建viewhodler,相当于listview中getview中的创建view和viewhodler
     *
     * @param parent
     * @param viewType
     * @return
     */
    @Override
    public myViewHodler onCreateViewHolder(ViewGroup parent, int viewType) {
        //创建自定义布局

        View itemView = View.inflate(context, R.layout.food_item, null);

        return new myViewHodler(itemView);
    }

    /**
     * 绑定数据,数据与view绑定
     *
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(myViewHodler holder, int position) {
             //根据点击位置绑定数据
        FoodEntity data = goodsEntityList.get(position);
//        holder.mItemGoodsImg;
        configuration = ImageLoaderConfiguration.createDefault(context);
        ImageLoader.getInstance().init(configuration);
        imageOptions = DisplayImageOptions.createSimple();
        holder.mItemGoodsName.setText(data.foodtitle);//获取实体类中的name字段并设置
        holder.mItemContent.setText(data.foodcontent);//获取实体类中的price字段并设置
        adapter=new FoodRecycleAdapter(context, goodsEntityList);

        adapter.notifyItemRangeInserted(position,getItemCount());

//        ImageLoader.getInstance().displayImage(DocUtil.base_url+
//                        data.foodcontentimg, mItemGoodsImg,
//                imageOptions);

    }

    /**
     * 得到总条数
     *
     * @return
     */
    @Override
    public int getItemCount() {
        return goodsEntityList.size();
    }

    //自定义viewhodler
    class myViewHodler extends RecyclerView.ViewHolder {
        private ImageView mItemGoodsImg;
        private TextView mItemGoodsName;
        private TextView mItemContent;

        public myViewHodler(View itemView) {
            super(itemView);
            mItemGoodsImg = itemView.findViewById(R.id.food_img);
            mItemGoodsName =  itemView.findViewById(R.id.food_title);
            mItemContent =  itemView.findViewById(R.id.tx_content);

            //点击事件放在adapter中使用,也可以写个接口在activity中调用
            //方法一:在adapter中设置点击事件
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //可以选择直接在本位置直接写业务处理
                    //Toast.makeText(context,"点击了xxx",Toast.LENGTH_SHORT).show();
                    //此处回传点击监听事件

                    if(onItemClickListener!=null){
                        onItemClickListener.OnItemClick(v, goodsEntityList.get(getLayoutPosition()));
                    }
                }
            });

        }
    }

    /**
     * 设置item的监听事件的接口
     */
    public interface OnItemClickListener {
        /**
         * 接口中的点击每一项的实现方法,参数自己定义
         *
         * @param view 点击的item的视图
         * @param data 点击的item的数据
         */
        public void OnItemClick(View view, FoodEntity data);
    }

    //需要外部访问,所以需要设置set方法,方便调用
    private FoodRecycleAdapter.OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(FoodRecycleAdapter.OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • qq_34424362
    qq_34424362 2019-04-24 18:00
    已采纳

    使用listview就完美解决问题。

    点赞 评论
  • caoweichen520
    caoweichen520 2019-03-26 13:40

    我不知道你说的是什么意思 但是我用sql更新

    点赞 评论
  • menwaiqingshan
    SemiraChen 2019-03-26 17:39

    首先我我看不懂goodsEntity和foodEntity之间是什么关系
    new Adapter的时候传进去的是goodsEntityList
    但是网络请求得到的是foodEntity

    其次网络请求后没有得写更新RV的代码
    一般只要在网络请求后重新改一下数据源(或者可以说是数据集合)
    然后adapter.notifyDataSetChanged();(这句可不写,但是是根据情况来的)

    ————————分割线————————

    public class FoodFragment extends Fragment {
        public RecyclerView mFoodRecyclerView;//定义RecyclerView
        //定义以goodsentity实体类为对象的数据集合
        private ArrayList<FoodEntity> goodsEntityList = new ArrayList<FoodEntity>();
        //自定义recyclerveiw的适配器
        private FoodRecycleAdapter mRecyclerAdapter;
        private JSONArray array;
        private Handler handler;
    
    
        public FoodFragment() {
        }
    
        private static ChangeFoodFragment changeFoodFragment;
    
        public static FoodFragment newInstance(ChangeFoodFragment foodFragment) {
            changeFoodFragment = foodFragment;
            Bundle args = new Bundle();
    
            FoodFragment fragment = new FoodFragment();
            fragment.setArguments(args);
            return fragment;
        }
    
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                                 @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.recyclerview_food, container, false);
            //对recycleview进行配置
    
            return view;
        }
    
        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
    
            final ViewData viewData = new ViewData();
            viewData.setView(view);
            handler = new Handler() {
    
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    System.out.println(msg);
    
                    switch (msg.what) {
                        case 1:
                            // 在这里去刷新UI
                            System.out.println(msg);
                            mRecyclerAdapter.notifyDataSetChanged();
    
                            break;
                    }
                }
    
            };
            //初始化RV
            initRecyclerView(view);
            initData();
        }
    
        private void initData() {
            new Thread() {
                public void run() {
                    String url = DocUtil.food_list;
                    OkHttpClient okHttpClient = new OkHttpClient();
    
                    String token = CacheUtils.getString(getActivity(), "token", "");
                    RequestBody body = new FormBody.Builder()
                            .add("token", token)
                            .build();
    
                    Request request = new Request.Builder()
                            .url(url)
                            .post(body)
                            .build();
    
                    Call call = okHttpClient.newCall(request);
                    try {
                        Response response = call.execute();
                        //System.out.println(response.body().string());
    
    
                        goodsEntityList.clear();
                        FoodEntity mfoodEntity;
                        for (int i = 0; i < 10; i++) {
                            mfoodEntity = new FoodEntity();
                            mfoodEntity.setFoodtitle("1");
                            mfoodEntity.setFoodcontent("2");
                            mfoodEntity.setFoodcontentimg("3");
    
                            goodsEntityList.add(mfoodEntity);
                        }
    
    //                    try {
    //                        final String string=response.body().string();
    //                        final JSONObject object=new JSONObject(string);
    //
    //                        array=object.getJSONArray("list");
    //                        System.out.println(array);
    //
    //                        if(array.length()>0) {
    //
    //                            try {
    //                                FoodEntity foodEntity =new FoodEntity();
    //                                for(int i=0;i<array.length();i++){
    //                                    JSONObject object1=array.getJSONObject(i);
    //                                    foodEntity.setFoodtitle(object1.getString("foodtitle"));
    //                                    foodEntity.setFoodcontent(object1.getString("foodcontent"));
    //                                    foodEntity.setFoodcontentimg(object1.getString("foodcontentimg"));
    //                                    System.out.println(foodEntity.getFoodtitle());
    //                                    System.out.println(foodEntity.getFoodcontent());
    //
    //
    //                                }
    //
    //
    //
    //
    //
    //
    //
    //
    //
    //                            } catch (Exception e) {
    //                                e.printStackTrace();
    //                            }
                                // 获取到数据后,通知handle刷新UI
                                Message message = handler.obtainMessage();
                                message.what = 1;
                                handler.sendMessage(message);
    //                        }else {
    //                            Toast.makeText(getActivity(), "无数据", Toast.LENGTH_SHORT).show();
    //                        }
    //                    } catch (JSONException e) {
    //                        e.printStackTrace();
    //                    }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
    
    
    //        for (int i=0;i<10;i++){
    //            FoodEntity foodEntity =new FoodEntity();
    //            foodEntity.setName("模拟数据FOOD"+i);
    //            foodEntity.setContent("100"+i);
    //            goodsEntityList.add(foodEntity);
    //        }
        }
    
        private void initRecyclerView(View view) {
            //获取RecyclerView
            mFoodRecyclerView = view.findViewById(R.id.food_recyclerView);
            //创建adapter
            mRecyclerAdapter = new FoodRecycleAdapter(getActivity(), goodsEntityList);
            //给RecyclerView设置adapter
            mFoodRecyclerView.setAdapter(mRecyclerAdapter);
            //设置layoutManager,可以设置显示效果,是线性布局、grid布局,还是瀑布流布局
            //参数是:上下文、列表方向(横向还是纵向)、是否倒叙
            mFoodRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
            //设置item的分割线
            mFoodRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
    
    
            //RecyclerView中没有item的监听事件,需要自己在适配器中写一个监听事件的接口。参数根据自定义
            mRecyclerAdapter.setOnItemClickListener(new FoodRecycleAdapter.OnItemClickListener() {
                @Override
                public void OnItemClick(View view, FoodEntity data) {
                    Toast.makeText(getActivity(), "我是item", Toast.LENGTH_SHORT).show();
                    changeToAnotherFragment();
                }
            });
    
        }
    
        @SuppressLint("ResourceType")
        private void changeToAnotherFragment() {
            changeFoodFragment.changeFoodFragment();
        }
    }
    
    点赞 评论
  • haozi_e
    红橡树 2019-03-26 17:46

    你的FoodFragment中我没看到有去初始化goodsEntityList的数据,如果是在这里初始化的那么你可以改下。还有其中的initData();是另起线程去获取的,所以可以这样认为initData()和initRecyclerView(view);几乎都同时执行了,在initData()数据还没获取到时和initRecyclerView(view);已经刷新了UI,解决办法是在数据获取成功后在执行initRecyclerView(view)。另外initRecyclerView(view);只能在UI线程里执行,所以你要换成UI线程,用new Thread()是不行的,改成下面的方式试下

    package com.example.qw.dualnavigation.fragment;

    import android.annotation.SuppressLint;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.v4.app.Fragment;
    import android.support.v7.widget.DividerItemDecoration;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Toast;

    import com.example.qw.dualnavigation.Interface.ChangeFoodFragment;
    import com.example.qw.dualnavigation.R;
    import com.example.qw.dualnavigation.adapter.FoodRecycleAdapter;
    import com.example.qw.dualnavigation.bean.FoodEntity;
    import com.example.qw.dualnavigation.bean.ViewData;

    import org.json.JSONArray;

    import java.util.ArrayList;

    public class FoodFragment extends Fragment {
    public RecyclerView mFoodRecyclerView;//定义RecyclerView
    //定义以goodsentity实体类为对象的数据集合
    private ArrayList goodsEntityList = new ArrayList();
    //自定义recyclerveiw的适配器
    private FoodRecycleAdapter mRecyclerAdapter;
    private JSONArray array;
    private Handler handler;

    public  FoodFragment() {
    }
    
    private static ChangeFoodFragment changeFoodFragment;
    
    public static FoodFragment newInstance(ChangeFoodFragment foodFragment){
        changeFoodFragment = foodFragment;
        Bundle args = new Bundle();
    
        FoodFragment fragment = new FoodFragment();
        fragment.setArguments(args);
        return fragment;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View  view = inflater.inflate(R.layout.recyclerview_food, container, false);
        //对recycleview进行配置
    
        return view;
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    
        final ViewData viewData =new ViewData();
        viewData.setView(view);
        handler = new Handler() {
    
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                System.out.println(msg);
    
                switch (msg.what) {
                    case 1:
                        // 在这里去刷新UI
                        System.out.println(msg);
                        initRecyclerView(viewData.getView());
                        break;
                }
            }
    
        };
    
        initData();
    
    
    }
    private void initData() {
        new Thread(){
            public void run()
            {
                /*String url = DocUtil.food_list;
                OkHttpClient okHttpClient = new OkHttpClient();
    
                String token= CacheUtils.getString(getActivity(), "token", "");
                RequestBody body = new FormBody.Builder()
                        .add("token",token)
                        .build();
    
                Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();
    
                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    //System.out.println(response.body().string());
                    try {
                        final String string=response.body().string();
                        final JSONObject object=new JSONObject(string);
    
                        array=object.getJSONArray("list");
                        System.out.println(array);
                        if(array.length()>0) {
    
                            try {
                                FoodEntity foodEntity =new FoodEntity();
                                for(int i=0;i<array.length();i++){
                                    JSONObject object1=array.getJSONObject(i);
                                    foodEntity.setFoodtitle(object1.getString("foodtitle"));
                                    foodEntity.setFoodcontent(object1.getString("foodcontent"));
                                    foodEntity.setFoodcontentimg(object1.getString("foodcontentimg"));
                                    System.out.println(foodEntity.getFoodtitle());
                                    System.out.println(foodEntity.getFoodcontent());
    
    
                                }
    
    
    
    
    
    
    
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            // 获取到数据后,通知handle刷新UI
                            Message message = handler.obtainMessage();
                            message.what = 1;
                            handler.sendMessage(message);
                        }else {
                            Toast.makeText(getActivity(), "无数据", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }*/
                for (int i=0;i<10;i++){
                    FoodEntity foodEntity =new FoodEntity();
                    foodEntity.setFoodtitle("模拟数据FOOD"+i);
                    foodEntity.setFoodcontent("100"+i);
                    goodsEntityList.add(foodEntity);
                }
                // 获取到数据后,通知handle刷新UI
                Message message = handler.obtainMessage();
                message.what = 1;
                handler.sendMessage(message);
            }
        }.start();
    

    // for (int i=0;i<10;i++){
    // FoodEntity foodEntity =new FoodEntity();
    // foodEntity.setName("模拟数据FOOD"+i);
    // foodEntity.setContent("100"+i);
    // goodsEntityList.add(foodEntity);
    // }
    }
    private void initRecyclerView(View view) {
    //获取RecyclerView
    mFoodRecyclerView=view.findViewById(R.id.food_recyclerView);
    //创建adapter
    mRecyclerAdapter = new FoodRecycleAdapter(getActivity(), goodsEntityList);
    //给RecyclerView设置adapter
    mFoodRecyclerView.setAdapter( mRecyclerAdapter );
    //设置layoutManager,可以设置显示效果,是线性布局、grid布局,还是瀑布流布局
    //参数是:上下文、列表方向(横向还是纵向)、是否倒叙
    mFoodRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
    //设置item的分割线
    mFoodRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL));

        //RecyclerView中没有item的监听事件,需要自己在适配器中写一个监听事件的接口。参数根据自定义
        mRecyclerAdapter.setOnItemClickListener(new FoodRecycleAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, FoodEntity data) {
                Toast.makeText(getActivity(),"我是item",Toast.LENGTH_SHORT).show();
                changeToAnotherFragment();
            }
        });
    
    }
    @SuppressLint("ResourceType")
    private void changeToAnotherFragment() {
        changeFoodFragment.changeFoodFragment();
    }
    

    }

    点赞 评论

相关推荐