简体   繁体   English

如何使用swipeRefreshLayout更新片段中的新json数据

[英]How can I updating only new json data in fragment with swipeRefreshLayout

In this fragment I send a jsonRequest with volley to the server . 在这个片段中,我向服务器发送了一个带有volley的jsonRequest and I'm setting the swipeRefreshLayout to this fragment , I want to load only new json data but when I use sendJsonRequest() method on the onRefresh() all of the json data is enabled to the recyclerView : 和我设置swipeRefreshLayout这个片段,我想要只载入新的JSON数据,但是当我使用sendJsonRequest()方法的onRefresh()所有的JSON数据使能到recyclerView

This is my fragment code: 这是我的片段代码:

package ghandak.ghandshekan.com.ghandak.fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import ghandak.ghandshekan.com.ghandak.R;
import ghandak.ghandshekan.com.ghandak.adapters.PostRecyclerAdapter;
import ghandak.ghandshekan.com.ghandak.app.AppController;
import ghandak.ghandshekan.com.ghandak.models.PostData;

/**
 * Created by imajid on 12/19/2015.
 */
public class TabFragment3 extends Fragment implements OnRefreshListener{
    private RecyclerView allContentRecyclerView;
    private String url  = "http://kakdo.herokuapp.com/api/news/?format=json";
    private List<PostData> postDataList = new ArrayList<PostData>();
    private SwipeRefreshLayout swipeRefreshLayout;

    //====================================================================================== onCreateView
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab_fragment_3 , container , false);
        allContentRecyclerView = (RecyclerView)view.findViewById(R.id.xmlRecyclerViewtabFragment3);
        allContentRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        swipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.xml_swipe_refresh_layout_tab_fragment_3);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        //swipeRefreshLayout.setColorSchemeColors();



        return view;
    }

    //====================================================================================== onCreate


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

    //====================================================================================== sendjsonRequest
    private void sendJsonRequest() {

        JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                parseJsonResponse(response);
                //==========setting adapter to the recyclerview  <==
                allContentRecyclerView.setAdapter(new PostRecyclerAdapter(getActivity() ,postDataList));
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        AppController.getInstance().addToRequestQueue(request);

    }

    //====================================================================================== parsjsonResponse()
    private void parseJsonResponse(JSONArray response) {
        if(response == null){
            Toast.makeText(getActivity(), "ریسپانس خالی هستش", Toast.LENGTH_SHORT).show();
            return;
        }else {
            Log.d("parsejsonresponse", "response khali nist");
            for (int i = 0 ; i < response.length()  ; i++ ){

                try {

                    //Toast.makeText(getActivity(), "ریسپانس میگیرم ", Toast.LENGTH_SHORT).show();
                    JSONObject currentPost = response.getJSONObject(i);
                    //Log.d("currentPost", "currentPost ro gereftam");

                    PostData postData = new PostData();
                    postData.setTitle(currentPost.getString("title"));
                    //Toast.makeText(getActivity() , currentPost.getString("title") , Toast.LENGTH_SHORT).show();
                    postData.setCreate(currentPost.getString("create"));

                    postDataList.add(postData);

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

            }
        }

    }

    @Override
    public void onRefresh() {
        sendJsonRequest();
        swipeRefreshLayout.setRefreshing(false);

    }
}

Now my question is in the OnRefresh method , what can I write to load only new json data, not all of the exists json. 现在我的问题是在OnRefresh方法中,我可以写什么来仅加载新的json数据,而不是全部存在的json。

Add this line in your code 在代码中添加此行

  postDataList.clear(); in your code given in bellow.

Updated: 更新:

           @Override
    public void onResponse(JSONArray response) {
        if(response == null )
            return;
        postDataList.clear();
        parseJsonResponse(response);
        //==========setting adapter to the recyclerview  <==
        allContentRecyclerView.setAdapter(new PostRecyclerAdapter(getActivity() ,postDataList));
    }

Note: when ever you create any kind of list max create adapter instance once in your code, After change list data you just need to call 'adapterInstance.notifyDataSetChange();' 注意:无论何时在代码中一次创建任何类型的列表max create适配器实例,更改列表数据后,您只需调用“ adapterInstance.notifyDataSetChange();”即可。 This is the best practice instead of creating list every time it's better to refresh list items, Further info check here 这是最佳做法,而不是每次都最好刷新列表项时创建列表,更多信息请点击此处

add this code , 添加此代码,

private SwipeRefreshLayout mSwipeRefreshLayout;


mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        mSwipeRefreshLayout.setRefreshing(true);
                    }
                }, SPLASH_DISPLAY_LENGTH);
            }
        });

when you want to refresh it call, 当您想刷新通话时,

mSwipeRefreshLayout.setRefreshing(true);
    swipeContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeContainer);
            swipeContainer.setOnRefreshListener(new OnRefreshListener()
            {

                @Override
                public void onRefresh()
                {
                    //clear your old data
                    callForData();
                    //swipeContainer.setRefreshing(false); use this while get data and set in you ui
                }
            });

            // Configure the refreshing colors
            swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM