在recyclerview中更新数据

时间:2016-04-17 06:32:35

标签: android android-recyclerview

在我的项目中,从我通过JSON响应创建的CMS中读取数据。我的问题是当我点击刷新按钮时,数据被读取两次!这是我的片段代码。

public class FootballNews extends Fragment {

public static final String TAG = "ManuApp";
private static final String IMAGE_URL = "http://xxx//manucms/football_news_images/" ;
private List<FootballNewsObject> listItemsList;

private RecyclerView mRecyclerView;
private FootballNewsAdapter adapter;

public FootballNews() {
    // Required empty public constructor
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    setRetainInstance(true);
    View v = inflater.inflate(R.layout.fragment_football_news, container, false);
    // Inflate the layout for this fragment
    listItemsList = new ArrayList<FootballNewsObject>();
    mRecyclerView = (RecyclerView)v.findViewById(R.id.recycler_view);
    //mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(Color.BLACK).build());
    final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(linearLayoutManager);


    return v;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    updateList();


}
public void updateList() {




    //declare the adapter and attach it to the recyclerview
    adapter = new FootballNewsAdapter(getActivity(), listItemsList);
    mRecyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();
    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(getActivity());

    // Clear the adapter because new data is being added from a new subreddit
    //adapter.clearAdapter();

    //showPD();

    // Request a string response from the provided URL.
    JsonArrayRequest jsObjRequest = new JsonArrayRequest(Request.Method.GET, Config.URL_FOOTBALL_NEWS, new Response.Listener<JSONArray>() {

        @Override
        public void onResponse(JSONArray response) {

            Log.d(TAG, response.toString());
            //hidePD();

            // Parse json data.
            // Declare the json objects that we need and then for loop through the children array.
            // Do the json parse in a try catch block to catch the exceptions
            try {



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

                    JSONObject post = response.getJSONObject(i);
                    FootballNewsObject item = new FootballNewsObject();
                    item.setTitle(post.getString("title"));
                    item.setImage(IMAGE_URL + post.getString("news_image"));
                    item.setArticle(post.getString("article"));



                    listItemsList.add(item);

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

            // Update list by notifying the adapter of changes
            adapter.notifyDataSetChanged();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            //hidePD();
        }
    });
    jsObjRequest.setRetryPolicy(new RetryPolicy() {
        @Override
        public int getCurrentTimeout() {
            return 50000;
        }

        @Override
        public int getCurrentRetryCount() {
            return 50000;
        }

        @Override
        public void retry(VolleyError error) throws VolleyError {

        }
    });
    queue.add(jsObjRequest);

}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    getActivity().getMenuInflater().inflate(R.menu.main, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if(id == R.id.refresh){
        if(isOnline()) {
            updateList();
        }else{
            Toast.makeText(getActivity(),"There is no internet connection",Toast.LENGTH_SHORT).show();
        }
    }



    return super.onOptionsItemSelected(item);
}
protected boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    } else {
        return false;
    }
}
}

基本上我运行 updateList 方法两次。一旦进入 onActivityCreated(...)方法,其次进入 onOptionsItemSelected(...)

最后这是我的适配器

public class FootballNewsAdapter extends RecyclerView.Adapter<FootballNewsRowHolder>{
private List<FootballNewsObject> footballNewsObjectList;
private Context mContext;
private ImageLoader mImageLoader;
private int focused = 0;

public FootballNewsAdapter(Activity activity, List<FootballNewsObject> footballNewsObjectList){
    this.footballNewsObjectList = footballNewsObjectList;
    this.mContext = activity;
}


@Override
public FootballNewsRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.football_news_row,null);
    final FootballNewsRowHolder holder = new FootballNewsRowHolder(v);


    return holder;
}

@Override
public void onBindViewHolder(FootballNewsRowHolder holder, int position) {
    final FootballNewsObject listItems = footballNewsObjectList.get(position);
    holder.itemView.setSelected(focused==position);

    holder.getLayoutPosition();

    mImageLoader = AppController.getInstance().getImageLoader();
    holder.thumbnail.setImageUrl(listItems.getImage(),mImageLoader);
    holder.thumbnail.setDefaultImageResId(R.drawable.reddit_placeholder);

    holder.name.setText(Html.fromHtml(listItems.getTitle()));
    holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String title = listItems.getTitle();
            String article = listItems.getArticle();
            String image = listItems.getImage();
            Intent i = new Intent(mContext, Extras.class);
            i.putExtra("title",title);
            i.putExtra("article",article);
            i.putExtra("image",image);
            mContext.startActivity(i);
            //Toast.makeText(mContext,"You clicked",Toast.LENGTH_SHORT).show();
            //Intent intent = new Intent(mContext,WebActivity.class);
            //intent.putExtra("url",postUrl);
            // mContext.startActivity(intent);
        }
    });
}

@Override
public int getItemCount() {
    return (null != footballNewsObjectList?footballNewsObjectList.size() :0    );
}

}

有什么想法吗?

由于

1 个答案:

答案 0 :(得分:1)

您正在刷新方法中添加到列表中,而不是更新。添加

listItemsList.clear();

在刷新函数(updateList)的开头。