如何使用OkHttp3缓存数据

时间:2018-11-03 11:36:07

标签: android android-studio

我正在使用OkHttp3作为网络库,并使用Node-Mongo作为后端服务。我正在列表视图中从服务器中获取数据。每当我的应用程序第一次启动时,它将从服务器中加载我要缓存的数据数据,以便在应用再次启动时无需花费时间在应用中显示数据。 我不知道如何实现缓存功能。 这是我的代码:

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(MainActivity.this);
prg.setMessage("Loading...");
prg.show();

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

OkHttpClient client = new OkHttpClient();

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();
                }
            }
        });
    }

  });

  }
} 

PlacesAdapter.java

public class PlacesAdapter extends ArrayAdapter<Data> {

private List<Data>  places;
private Context ctx;

public PlacesAdapter( List<Data> places, Context ctx) {
super(ctx,R.layout.places_row,places);
this.places = places;
this.ctx = ctx;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

LayoutInflater inflater = LayoutInflater.from(ctx);

View listView = inflater.inflate(R.layout.places_row,null,true);

TextView txt = listView.findViewById(R.id.txt);

Data data = places.get(position);

txt.setText(data.getPlace());

return listView;

 }
}

请让我知道如何实现这一目标。

谢谢

0 个答案:

没有答案