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

时间:2019-05-23 13:29:03

标签: android okhttp3

我正在制作一个我使用OkHttp3作为网络库的android应用程序。我正在回收视图中从服务器中获取数据。我正在尝试缓存数据,以便如果用户第二次打开应用程序时应用程序不应触发任何网络请求并显示缓存中的旧数据,直到服务器上添加了一些新数据。 我不知道该如何开始。

这是我的下面的代码:

Home.java

public class Home extends Fragment {

String myValue;
RecyclerView recycle;
ArrayList<LoadHomeBooks> list;
HomeBookAdapter adapter;
EditText search;


private static final String URL = "https://www.example.com";

public Home() {
// Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);

recycle = view.findViewById(R.id.recycle);
refresh = view.findViewById(R.id.refresh);
search = view.findViewById(R.id.search);

list = new ArrayList<>();

recycle.setHasFixedSize(true);
recycle.setLayoutManager(new LinearLayoutManager(getActivity()));

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

RequestBody formBody = new FormBody.Builder().add("city", myValue).build();

Request request = new Request.Builder().url(URL).post(formBody).build();

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

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

        if (getActivity() != null) {

            getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {

                    try {

                        JSONArray jsonArray = new JSONArray(response.body().string());


                        for (int i = jsonArray.length() - 1; i > -1; i--) {

                            JSONObject object = jsonArray.getJSONObject(i);

                            String str1 = object.getString("Book_name");


                            LoadHomeBooks model = new LoadHomeBooks(str1);

                            list.add(model);
                        }

                         adapter = new HomeBookAdapter(list, getActivity());

                        recycle.setAdapter(adapter);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }


    }

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

        if (getActivity() != null) {

            getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {

                  TastyToast.makeText(getActivity(), e.getMessage(), TastyToast.LENGTH_LONG, TastyToast.ERROR).show();
                }
            });

        }

    }

}); 

HomeBookAdapter.java

public class HomeBookAdapter extends 
RecyclerView.Adapter<HomeBookAdapter.ViewHolder> {

ArrayList<LoadHomeBooks> list;
Context context;

public HomeBookAdapter(ArrayList<LoadHomeBooks> list,Context context){

this.list = list;
this.context = context;
}

@NonNull
@Override
public HomeBookAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.home_book_layout,viewGroup,false);

return new ViewHolder(v);
}

@Override
public void onBindViewHolder(@NonNull HomeBookAdapter.ViewHolder viewHolder, int i) {

LoadHomeBooks model = list.get(i);

viewHolder.homeBookName.setText(model.getbName());

}

@Override
public int getItemCount() {
return list.size();
}

public class ViewHolder extends RecyclerView.ViewHolder{

TextView homeBookName;

public ViewHolder(@NonNull View itemView) {
    super(itemView);

    homeBookName = itemView.findViewById(R.id.homeBookName);
 }
}

public void setFilter(ArrayList<LoadHomeBooks> filterBooks){

list = new ArrayList<>();
list.addAll(filterBooks);
notifyDataSetChanged();

 } 
}

LoadHomeBooks.java

public class LoadHomeBooks {

String bName;

public LoadHomeBooks(){

}

public LoadHomeBooks(String bName){

this.bName = bName;

}

public String getbName() {
return bName;
}

public void setbName(String bName) {
this.bName = bName;
}

}

请让我知道如何在上述代码中实现缓存。我们将不胜感激。

谢谢

1 个答案:

答案 0 :(得分:0)

您将需要一个本地数据库。尝试RealmRoom都是不错的选择。这将是您的工作流程:

1->检查数据库中是否有数据。如果是,请直接将它们加载到RecyclerView

2->如果不是,请从网络请求数据。成功获取后,将它们保存到数据库中,然后显示它们。如果网络请求失败,则必须显示错误。

或者,您可以使用OkHTTP本身提供的cache

OkHttpClient.Builder builder = new OkHttpClient.Builder() .cache(new Cache(context.getCacheDir(), cacheSize)

查看此link以获得更多信息