Digvijay
Digvijay

Reputation: 3271

How to cache data using OkHttp3 networking library in android

I am making an android app in which I am using OkHttp3 as a networking library.I am fetching data from server in recycler view.I am trying to cache data so that if user open app second time app should fire no network request and shows old data from cache until there is some new data added on server. I don't know how to get started .

This is my code below:

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

}

Someone please let me know how can I implement cache in above code.Any help would be appreciated.

THANKS

Upvotes: 0

Views: 158

Answers (1)

apksherlock
apksherlock

Reputation: 8371

You will need a local database. Try Realm or Room they both are great. This will be your workflow:

1-> Check if there are data to database. If yes, load them to the RecyclerView directly.

2-> If not, request the data from the network. After a successful fetch, save them to the database and then display them. If the network request will be unsuccessful, you must show an error.

Alternatively you can use a cache provided by the OkHTTP itself:

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

Check out this link for more information

Upvotes: 1

Related Questions