pull to refresh返回两次数据

时间:2014-08-09 03:43:32

标签: android json android-layout android-activity pull-to-refresh

我从JSON Feed获取数据。

我能够进行快速刷新并且工作正常,但它不会只带来新数据,它会一遍又一遍地带来所有数据,所以每次我刷新它会带来所有结果,如相同的结果,并在应用程序内重复它们。

我正在使用Volly库。

我的数据JSON看起来像

http://twaa9l.com/ji/feed.json

这是我的代码:

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

import com.android.volley.Cache;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.twaa9l.photosee.feed.FeedItem;
import com.twaa9l.photosee.feed.FeedListAdapter;
import com.twaa9l.photosee.library.AppController;
import com.twaa9l.photosee.library.SessionManagement;
import com.twaa9l.photosee.library.UploadPhoto;

public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private ListView listView;
    private FeedListAdapter listAdapter;
    private List<FeedItem> feedItems;
    protected SwipeRefreshLayout mSwipeRefreshLayout;
    private String URL_FEED = "http://twaa9l.com/ji/feed.json";
    // Session Manager Class
    SessionManagement session;


    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //refresh();
        // Session class instance
        session = new SessionManagement(getApplicationContext());

        /**
         * Call this function whenever you want to check user login
         * This will redirect user to LoginActivity is he is not
         * logged in
         * */
        session.checkLogin();

        // get user data from session
        HashMap<String, String> user = session.getUserDetails();


        mSwipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipeRefreshLayout);
        mSwipeRefreshLayout.setOnRefreshListener(mOnRefreshListener);
        mSwipeRefreshLayout.setColorScheme(
                R.color.swipeRefresh1,
                R.color.swipeRefresh2,
                R.color.swipeRefresh3,
                R.color.swipeRefresh4);

        listView = (ListView) findViewById(R.id.list);

        feedItems = new ArrayList<FeedItem>();

        listAdapter = new FeedListAdapter(this, feedItems);
        listView.setAdapter(listAdapter);

        // These two lines not needed,
        // just to get the look of facebook (changing background color & hiding the icon)
        getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
        getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));

            getNewPosts();

    }


    private void getNewPosts() {

            // making fresh volley request and getting json
            JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                    URL_FEED, null, new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            VolleyLog.d(TAG, "Response: " + response.toString());
                            if (response != null) {
                                parseJsonFeed(response);
                                if(mSwipeRefreshLayout.isRefreshing()){
                                    mSwipeRefreshLayout.setRefreshing(false);
                                }
                            }
                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {
                            VolleyLog.d(TAG, "Error: " + error.getMessage());
                        }
                    });

            // Adding request to volley request queue
            AppController.getInstance().addToRequestQueue(jsonReq);
    }

    /**
     * Parsing json reponse and passing the data to feed view list adapter
     * */
    private void parseJsonFeed(JSONObject response) {
        try {
            JSONArray feedArray = response.getJSONArray("feed");

            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);

                FeedItem item = new FeedItem();
                item.setId(feedObj.getInt("id"));
                item.setName(feedObj.getString("name"));

                // Image might be null sometimes
                String image = feedObj.isNull("image") ? null : feedObj
                        .getString("image");
                item.setImge(image);
                item.setStatus(feedObj.getString("status"));
                item.setProfilePic(feedObj.getString("profilePic"));
                item.setTimeStamp(feedObj.getString("timeStamp"));

                // url might be null sometimes
                String feedUrl = feedObj.isNull("url") ? null : feedObj
                        .getString("url");
                item.setUrl(feedUrl);

                int lastStoredTimeStamp = 0;
                if(i == feedArray.length()){
                     lastStoredTimeStamp = feedObj.getInt("timeStamp");
                }

                if(feedObj.getInt("timeStamp") > lastStoredTimeStamp){
                    feedItems.add(item);
                    }
            }

            // notify data changes to list adapater
            listAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();

        switch (itemId) {
        case R.id.action_settings:
            session.logoutUser();
            break;
        case R.id.addPhoto:
            Intent intent1 = new Intent(this, UploadPhoto.class);
            startActivity(intent1);
            break;
        }

        // TODO Auto-generated method stub
        return super.onOptionsItemSelected(item);
    }


    protected OnRefreshListener mOnRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh() {
            // TODO Auto-generated method stub
            //Toast.makeText(MainActivity.this, "We Are Refreshing", Toast.LENGTH_SHORT).show();
            getNewPosts();  
        }
    };


}

我想要做的是,只提供新结果并将其附加到应用中的现有结果中,

不重复结果。

注意:这个问题不是重复的,因为我在这里找了所有问题来解决问题并且对我没有任何作用

1 个答案:

答案 0 :(得分:0)

理想情况下,从中提取数据的服务器需要根据您传递的时间戳返回数据。

例如,当您查询时,指定您拥有的数据的时间戳“T”,服务器仅在时间戳“T”之后返回数据

如果服务器不支持此机制,那么在客户端,您需要确保将数据项添加到列表视图列表中,其中时间戳为&gt; “T”。

如下所示:

          long lastStoredTimeStamp = 0;//This should be in constructor
/**
 * Parsing json reponse and passing the data to feed view list adapter
 * */
private void parseJsonFeed(JSONObject response) {
    try {
        JSONArray feedArray = response.getJSONArray("feed");

        for (int i = 0; i < feedArray.length(); i++) {
            JSONObject feedObj = (JSONObject) feedArray.get(i);

            FeedItem item = new FeedItem();
            item.setId(feedObj.getInt("id"));
            item.setName(feedObj.getString("name"));

            // Image might be null sometimes
            String image = feedObj.isNull("image") ? null : feedObj
                    .getString("image");
            item.setImge(image);
            item.setStatus(feedObj.getString("status"));
            item.setProfilePic(feedObj.getString("profilePic"));
            item.setTimeStamp(feedObj.getString("timeStamp"));

            // url might be null sometimes
            String feedUrl = feedObj.isNull("url") ? null : feedObj
                    .getString("url");
            item.setUrl(feedUrl);

            if(i == feedArray.length()-1){
                 lastStoredTimeStamp = feedObj.getLong("timeStamp");
            }

            if(feedObj.getLong("timeStamp") > lastStoredTimeStamp){
                feedItems.add(item);
                }
        }

        // notify data changes to list adapater
        listAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}