【问题标题】:Fetching same data again and again from server using android volley?使用 android volley 从服务器一次又一次地获取相同的数据?
【发布时间】:2016-02-04 06:19:46
【问题描述】:

嗨,伙计们,前一天我是 android 开发的新手,只有我开始使用 volley form 从服务器获取数据。现在我的问题是从服务器获取 json 响应并将其设置到回收器适配器中并将其保存在 sharedpreferences 中。我已经在 oncreateview 方法中编写了 volley call 我的疑问是在我重新访问该片段时再次在活动之间切换之后,它从服务器获取相同的数据并将其保存在 sharedpreferences 中,就像我每次访问该片段时明智的数据都会加倍在这里让我发布我的代码:

这是我的片段代码:

public class Task extends Fragment {
    private static final String MY_PREFERENCE_KEY = "yogan";
    private List<Model_Task_List> model_task_lists;

    //Creating Views
    Context context;
    SharedPreferences.Editor editor;
    private RecyclerView recyclerView;
    Task_List_Adapter taskadapter;
    private RecyclerView.LayoutManager layoutManager;
    SharedPreferences sharedPreferences;
    private RecyclerView.Adapter adapter;
    RequestQueue yog;
    Task_DB taskobj = new Task_DB(getContext());
    String yogan;
    AppController app;
    RequestQueue queue;
    String Url;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_task, container, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        recyclerView.setLayoutManager(layoutManager);
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
        Gson gsong = new Gson();


        String jsons = sharedPreferences.getString(MY_PREFERENCE_KEY, "");
        Type type = new TypeToken<ArrayList<Model_Task_List>>() {
        }.getType();
        model_task_lists = gsong.fromJson(jsons, type);
        if (model_task_lists == null) {
            model_task_lists = new ArrayList<Model_Task_List>();
        }


        //Showing a progress dialog


        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(LoginActivity.login, 0);
        yogan = sharedPreferences.getString("user_id", null);
       queue= AppController.getInstance(getActivity().getApplicationContext()).getRequestQueue();
         Url = "http://xxx.xx.x.xxx/xxxx/xxx.svc/getlist/GetTask/" + yogan;
        //Creating a json array request

        JsonObjectRequest jsonArrayRequest = new JsonObjectRequest(Request.Method.GET, Url, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        String server_response = response.toString();
                        try {
                            JSONObject json_object = new JSONObject(server_response);
                            JSONArray json_array = new JSONArray(json_object.getString("GetTaskResult"));
                            for (int i = 0; i < json_array.length(); i++) {
                                Model_Task_List modelobj = new Model_Task_List();

                                JSONObject json_arrayJSONObject = json_array.getJSONObject(i);
                                modelobj.setSubject(json_arrayJSONObject.getString("Subject"));
                                modelobj.setUserName(json_arrayJSONObject.getString("UserName"));
                                modelobj.setTaskStatus(json_arrayJSONObject.getString("TaskStatus"));

                                model_task_lists.add(modelobj);
                                taskadapter = new Task_List_Adapter(model_task_lists, getContext());
                                recyclerView.setAdapter(taskadapter);
                                taskadapter.notifyDataSetChanged();


                                //


                            }


                            //Finally initializing our adapter


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

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
                        Log.e("yog", error.toString());
                    }
                });

        //Creating request queue
queue.start();
        queue.add(jsonArrayRequest);



        return view;
    }


    @Override
    public void onResume() {

        super.onResume();
    }


    @Override
    public void onStop() {
     queue.stop();
        SharedPreferences sharedpref = PreferenceManager.getDefaultSharedPreferences(getContext());
        editor = sharedpref.edit();
        Gson gson = new Gson();
        String god = gson.toJson(model_task_lists);
        editor.putString(MY_PREFERENCE_KEY, god);
        editor.commit();
        super.onStop();
        super.onStop();
    }
}

这是我的 Appcontroller 类:

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;



    public class AppController extends android.app.Application {
        private static AppController mInstance;
        private RequestQueue mRequestQueue;
        private ImageLoader mImageLoader;
        private static Context mCtx;

        private AppController(Context context) {
            mCtx = context;
            mRequestQueue = getRequestQueue();

            mImageLoader = new ImageLoader(mRequestQueue,
                    new ImageLoader.ImageCache() {
                        private final LruCache<String, Bitmap>
                                cache = new LruCache<String, Bitmap>(20);

                        @Override
                        public Bitmap getBitmap(String url) {
                            return cache.get(url);
                        }

                        @Override
                        public void putBitmap(String url, Bitmap bitmap) {
                            cache.put(url, bitmap);
                        }
                    });
        }

        public static synchronized AppController getInstance(Context context) {
            if (mInstance == null) {
                mInstance = new AppController(context);
            }
            return mInstance;
        }

        public RequestQueue getRequestQueue() {
            if (mRequestQueue == null) {
                // getApplicationContext() is key, it keeps you from leaking the
                // Activity or BroadcastReceiver if someone passes one in.
                mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
            }
            return mRequestQueue;
        }

        public <T> void addToRequestQueue(Request<T> req) {
            getRequestQueue().add(req);
        }

        public ImageLoader getImageLoader() {
            return mImageLoader;
        }
    }

我希望你们能理解我面临的问题我会很高兴有人帮助我提前谢谢!

【问题讨论】:

    标签: android android-fragments android-recyclerview android-volley


    【解决方案1】:

    只需在 SharedPreferences 中使用布尔值创建另一个键('First_Time')。在进行服务器调用之前检查此值。如果该值为 false,则进行服务器调用并将该值设置为 true。所以下次重新进入fragment时,该值为true,不会进行服务器调用。

    在你 Fragment 的 onCreate 方法中 -

    SharedPreferences sharedpref = PreferenceManager.getDefaultSharedPreferences(getContext());
    //Check if key exists
    if(!sharedPrefs.contains("First_Time")){
        editor = sharedpref.edit();
        editor.putBoolean("First_Time", true);
    }
    

    现在在进行截击之前检查 -

    if(sharedpref.getBoolean("First_Time")){ //Checking if Fragment launched first time
        //Set this value to false so that it doesn't execute next time.
        editor = sharedpref.edit();
        editor.putBoolean("First_Time", false);
    
       //Now make your volley call for the first and the last time here.
    }
    

    【讨论】:

    • 你能分享一些sn-p吗
    • 那我的凌空码没问题吧?我正在使用 HTTP GET 方法来绑定这个回收器视图
    • 是的,代码看起来不错。但也请确保在您第二次打开片段时初始化您的适配器,因为那时将不会发出 volley 请求。
    • 那么如何从服务器获取新数据
    • 有很多方法可以做到这一点。如果定期发送新数据,那么您每次都下载它。如果您希望定期使用它,那么您可以设置一个服务,该服务将在特定时间间隔唤醒并为您下载数据并保存它或将 sharedpreference 变量设置为 true。另一种方法是使用 GCM,但这需要更多的服务器端代码。
    猜你喜欢
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    • 2018-11-29
    • 1970-01-01
    相关资源
    最近更新 更多