如何在Android中使用OkHttp3缓存数据

时间:2019-05-10 14:41:13

标签: android okhttp3

每次活动打开时,我都从listview的节点服务器中获取数据,它将请求发送到服务器并再次获取数据。我想缓存数据并显示它,直到将一些新数据添加到服务器中为止。

MainActivity.java

public class Activity2 extends AppCompatActivity {

ListView listView;
List<Data> places;

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

listView  = findViewById(R.id.listView);
places = new ArrayList<>();

final ProgressDialog prg = new ProgressDialog(Activity2.this);
prg.setMessage("Loading...");
prg.show();

Log.d("OnCreate","Oncreate started");

OkHttpClient client = new OkHttpClient.Builder()
                          .connectTimeout(22, TimeUnit.SECONDS)
                          .readTimeout(22,TimeUnit.SECONDS)
                          .writeTimeout(22,TimeUnit.SECONDS)
                          .build();

Request request = new Request.Builder().url("https://tiffino.herokuapp.com/test").build();

client.newCall(request).enqueue(new Callback() {

    @Override
    public void onFailure(Call call, final IOException e) {

        prg.dismiss();

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(),""+e.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onResponse(Call call, final Response response) throws IOException {

        prg.dismiss();

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                try {
                    JSONArray arr = new JSONArray(response.body().string());

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

                        JSONObject obj = arr.getJSONObject(i);

                        String str1 = obj.getString("Name");

                        Data data = new Data(str1);

                        places.add(data);

                    }

                    PlacesAdapter adapter=  new PlacesAdapter(places,getApplicationContext());
                    listView.setAdapter(adapter);

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

  });

  }
} 

请让我知道如何缓存数据。 任何帮助将不胜感激。

谢谢

0 个答案:

没有答案