recyclerview没有更新

时间:2017-03-16 11:44:57

标签: android android-recyclerview

我正在尝试更新我的RecyclerView,因为数据集中的元素数量会发生变化

PlaceHolderFragment

public class PlaceholderFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";
    public static final String HOME_ADAPTER = "HOME";
    public static final String TRENDING_ADAPTER = "TREND";

    public static int P_START = -1;
    public static int P_END = -1;
    public static int T_START = -1;
    public static int T_END = -1;

    List<Posts> mNewsFeeds = new ArrayList<>();
    List<Posts> mTrending = new ArrayList<>();
    List<ChatList> mChatList = new ArrayList<>();
    List<Online> mOnline = new ArrayList<>();
    HomeAdapter homeAdapter;
    HomeAdapter TrendAdapter;
    ChatListAdapter chatListAdapter;
    OnlineListAdapter onlineAdapter;

    RecyclerView recyclerViewT1;
    RecyclerView recyclerViewT2;
    RecyclerView recyclerViewT3;
    RecyclerView recyclerViewT4;
    private SwipeRefreshLayout swipeRefreshLayoutT1;
    private SwipeRefreshLayout swipeRefreshLayoutT2;
    private SwipeRefreshLayout swipeRefreshLayoutT3;
    private SwipeRefreshLayout swipeRefreshLayoutT4;

    private int visibleThreshold = 2;
    private int PlastVisibleItem, PtotalItemCount;
    private boolean Ploading;

    private int TlastVisibleItem, TtotalItemCount;
    private boolean Tloading;


    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }


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

        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        Bundle args = new Bundle(getArguments());
        int TabID = args.getInt(ARG_SECTION_NUMBER);

        if (TabID == 1) {

            recyclerViewT1 = (RecyclerView) rootView.findViewById(R.id.rv_numbers);
            swipeRefreshLayoutT1 = (SwipeRefreshLayout) rootView.findViewById(R.id.refresh);
             final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
            recyclerViewT1.setLayoutManager(layoutManager);
            recyclerViewT1.setHasFixedSize(false);

            try {
                OnlineltPosts();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            recyclerViewT1.addOnScrollListener(new RecyclerView.OnScrollListener() {

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);

                    PtotalItemCount = layoutManager.getItemCount();
                    PlastVisibleItem = layoutManager.findLastVisibleItemPosition();
                    if (!Ploading && PtotalItemCount <= (PlastVisibleItem + visibleThreshold)) {
                        Ploading = true;
                        OnlineltPosts();
                        Log.e("coool","yeeeeeeeeeeeeee");
                    }
                }

        });


        } else if (TabID == 2) {



        } else if (TabID == 3) {


        } else {


        }
        return rootView;
    }

 .........

Onlineltpost

void OnlineltPosts() {

        String url = ApiUtil.getltPostUrl(P_END);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {


       try {
            JSONArray arr = new JSONArray(response);

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

                mNewsFeeds.add(postHelper(arr, i));
            }
            if (recyclerViewT1.getAdapter() == null) {
                homeAdapter = new HomeAdapter(mNewsFeeds, mNewsFeeds.size() + 1, HOME_ADAPTER);
                recyclerViewT1.setAdapter(homeAdapter);
            }else

                homeAdapter.notifyDataSetChanged();

//                getActivity().runOnUiThread(new Runnable() {
//                    public void run() {
//                        homeAdapter.notifyDataSetChanged();
//                    }
//                });
//            Log.e("coool", String.valueOf(mNewsFeeds.size()));


        } catch (JSONException | MalformedURLException | URISyntaxException e) {
            e.printStackTrace();
        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        RequestManager.getInstance(getContext()).addToRequestQueue(stringRequest);
    }

postHelper

public static Posts postHelper(JSONArray arr, int i) throws JSONException, URISyntaxException, MalformedURLException {

        JSONObject obj = new JSONObject(String.valueOf(arr.get(i)));
        int id = obj.getInt("post_id");

//        SharedPreferences pref = getContext().getSharedPreferences(Preferences.POST, 0);
//        SharedPreferences.Editor editor = pref.edit();
//
//        int start = pref.getInt(Preferences.POST_LATEST_START, -1);
//        int end = pref.getInt(Preferences.POST_LATEST_END, -1);
//
//        if (start == -1 || id > start)
//            editor.putInt(Preferences.POST_LATEST_START, id);
//
//        if (end == -1 || id < end)
//            editor.putInt(Preferences.POST_LATEST_END, id);
//
//        editor.putString(Preferences.POST_PREFEX + id, obj.toString());
//
//        editor.apply();


        if (P_START == -1 || id > P_START)
            P_START = id;

        if (P_END == -1 || id < P_END)
            P_END = id;


        int user_id = obj.getInt("user_id");
        String user_name = (String) obj.get("user_name");

        String pic = (String) obj.get("user_picture");

        URI uri = new URI(pic);
        URL user_picture = uri.toURL();

        String post_text = (String) obj.get("post_text");
        String post_time = (String) obj.get("post_time");
        int likes = (int) obj.get("likes");
        int dislikes = (int) obj.get("dislikes");
        int comments = (int) obj.get("comments");
        int isliked = (int) obj.get("isliked");
        int isdisliked = (int) obj.get("isdisliked");
        int iscommented = (int) obj.get("iscommented");
        int isfollow = (int) obj.get("isfollow");

        JSONObject abc = obj.getJSONArray("post_data").getJSONObject(0);
        String post_image = (String) abc.get("source");
        int type = abc.getInt("type");

        if (type == 4) {

            String youtube = "www.youtube.com/embed/";
            int x = post_image.indexOf(youtube);
            post_image = post_image.substring(x + youtube.length(), post_image.length());
            int x1 = post_image.indexOf("?");
            post_image = post_image.substring(0, x1);
            post_image = "http://img.youtube.com/vi/" + post_image + "/0.jpg";

        }


        List<Like> postLikes = new ArrayList<>();
        List<Comment> postComments = new ArrayList<>();

        JSONArray likeList = obj.getJSONArray("like_all");

        for (int j = 0; j < likeList.length(); j++) {

            JSONObject obj1 = new JSONObject(String.valueOf(likeList.get(j)));

            int Luser_id = obj1.getInt("user_id");
            String Luser_name = obj1.getString("user_name");
            String Lusername = obj1.getString("username");

            String Lpic = obj1.getString("user_picture");

            URI uri1 = new URI(Lpic);
            URL Luser_picture = uri1.toURL();
            Like mlike = new Like(Luser_id, Luser_name, Lusername, Luser_picture);
            postLikes.add(mlike);
        }

        JSONArray CommentList = obj.getJSONArray("post_comment");

        for (int j = 0; j < CommentList.length(); j++) {

            JSONObject obj1 = new JSONObject(String.valueOf(CommentList.get(j)));

            int Lpost_id = obj1.getInt("post_id");
            int Lcomment_id = obj1.getInt("comment_id");


            String Lusername = obj1.getString("username");
            String Lcomment = obj1.getString("comment");
            String Lcomment_time = obj1.getString("comment_time");


            int Luser_id = obj1.getInt("user_id");
            String Luser_name = obj1.getString("user_name");


            String Lpic = obj1.getString("user_picture");

            URI uri1 = new URI(Lpic);
            URL Luser_picture = uri1.toURL();

            Comment mlike = new
                    Comment(Lpost_id, Lcomment_id, Luser_id, Luser_name,
                    Lusername, Lcomment, Lcomment_time, Luser_picture);
            postComments.add(mlike);
        }

        return new Posts(id, user_id, user_name, user_picture,
                post_text, post_time, likes, dislikes, comments,
                isliked, isdisliked, iscommented, isfollow, post_image, type,
                postLikes, postComments);


    }

我尝试过recyclerViewT1.setHasFixedSize(false);,但一切都没有改变。我注意到的是数据集正在成功更改,但recyclerview未显示新项目。

当我尝试:

homeAdapter = new HomeAdapter(mNewsFeeds, mNewsFeeds.size() + 1, HOME_ADAPTER);
 recyclerViewT1.setAdapter(homeAdapter);

而不是:

homeAdapter.notifyDataSetChanged();

它显示正确的项目数,但随后用户被推回到顶部,用户需要再次滚动,这是我不想要的。我只想用新项目更新数据集。

2 个答案:

答案 0 :(得分:2)

您应该始终向HomeAdapter提供新的mNewsFeeds并调用homeAdapter.notifyDataSetChanged();改变数据

try {
    JSONArray arr = new JSONArray(trending);

    for (int i = 0; i < arr.length(); i++) {
        mNewsFeeds.add(postHelper(arr, i));
    }
    if (recyclerViewT1.getAdapter() == null) {
        homeAdapter = new HomeAdapter(mNewsFeeds, mNewsFeeds.size() + 1, HOME_ADAPTER);
        recyclerViewT1.setAdapter(homeAdapter);
    }else {
        homeAdapter.setNewsFeeds(mNewsFeeds)
    }

    homeAdapter.notifyDataSetChanged();

//                getActivity().runOnUiThread(new Runnable() {
//                    public void run() {
//                        homeAdapter.notifyDataSetChanged();
//                    }
//                });
//            Log.e("coool", String.valueOf(mNewsFeeds.size()));


} catch (JSONException | MalformedURLException | URISyntaxException e) {
    e.printStackTrace();
}

答案 1 :(得分:2)

更新getItemCount&amp;设置notifyDataSetChanged

之前的数据

在适配器中:

private int mListSize;

public void setItemCount(int listsize){
mListSize=listsize;
} 

@Override
public int getItemCount() {
    return mListSize;
}

在notifydataset改变之前:

 if (recyclerViewT1.getAdapter() == null) {
                homeAdapter = new HomeAdapter(mNewsFeeds, mNewsFeeds.size() + 1, HOME_ADAPTER);
                recyclerViewT1.setAdapter(homeAdapter);
 }else{
     homeAdapter.setData(mNewsFeeds, mNewsFeeds.size() + 1, HOME_ADAPTER);
     homeAdapter.setItemCount(yourlist.size());
     homeAdapter.notifyDataSetChanged();
}

也可以尝试这个答案

https://stackoverflow.com/a/40220412/3879847