1. 程式人生 > >幾種快取方案的實現

幾種快取方案的實現

package example.com.huancuntest;

import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.LruCache;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.JsonArray;

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

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

import example.com.huancuntest.Util.ACache;
import example.com.huancuntest.Util.NetUtil;
import example.com.huancuntest.Util.SPUtil;
import example.com.huancuntest.Util.SpUtils;
import example.com.huancuntest.entity.DataEntity;
import example.com.huancuntest.entity.MessageEntity;
import example.com.huancuntest.entity.TotalEntity;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private RecyclerViewAdapter adapter;
    private List<TotalEntity> mList;

    private TotalEntity total;
    private Gson gson;

    private SPUtil spUtil;

    private ACache aCache;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }


    private void initView() {

        recyclerView = (RecyclerView)this.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        initData();
        adapter = new RecyclerViewAdapter(this,mList);
        recyclerView.setAdapter(adapter);

    }

    private void initData() {

        mList = new ArrayList<TotalEntity>();
        gson = new Gson();
        spUtil = SPUtil.getInstance();
        aCache = ACache.get(MainActivity.this);

        String company = "shentong";
        String num = "227873745185";
        if (NetUtil.isNetwork(this)){
             RequestQueue queue = Volley.newRequestQueue(this);
            GsonRequest<MessageEntity> request = new GsonRequest<MessageEntity>(
                    "http://www.kuaidi100.com/query?type="+company+"&postid="+num,
                    MessageEntity.class, new Response.Listener<MessageEntity>() {
                @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                @Override
                public void onResponse(MessageEntity response) {
                    for (int i = 0; i < response.getData().size(); i++){
                        total = new TotalEntity();
                        DataEntity entity = response.getData().get(i);
                        total.setContext(entity.getContext());
                        total.setTime(entity.getTime());
                        mList.add(total);
                    }
//                       JSONArray jsonArray = new JSONArray(gson.toJson(response.getData()));
//                       Log.d("tag", "jsonArray test == " + jsonArray);
//                       aCache.put("test",jsonArray);
                        spUtil.putJsonArray(MainActivity.this,"test",gson.toJson(response.getData()));
                    Toast.makeText(MainActivity.this, "has network", Toast.LENGTH_SHORT).show();

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("Tag", error.getMessage(),error);
                }
            });
            queue.add(request);
        }else{
//            JSONArray jsonArray = aCache.getAsJSONArray("test");
//            for (int i = 0; i < jsonArray.length(); i++) {
//                try {
//                    total = gson.fromJson(jsonArray.get(i).toString(), TotalEntity.class);
//                    Log.d("tag","json array-----" + jsonArray.get(i).toString());
//                    Log.d("Tag","getContect----" + total.getContext());
//                    Log.d("Tag","getTime----" + total.getTime());
//                    mList.add(total);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }

//            }
            String test = spUtil.getJsonArray(MainActivity.this,"test","");
            JSONArray jsonArray = null;
            try {
                jsonArray = new JSONArray(test);
                for (int i = 0; i < jsonArray.length(); i++){
                    total = gson.fromJson(jsonArray.get(i).toString(),TotalEntity.class);
                    mList.add(total);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Toast.makeText(this, "no network", Toast.LENGTH_SHORT).show();
        }
    }
}
initData()方法中,將網路返回的資料(response)通過sharedPreferances快取至記憶體中,沒有網路的情況下直接從記憶體中讀取,沒網路情況下,首先例項化一個Json陣列,將此json陣列序列化為TotalEntity物件(通過gson.fromJosn()方法實現)最後將資料新增進List中。

SpUtil.java如下: