Step 1. Add the JitPack repository to your build file
Add it in your root settings.gradle at the end of repositories:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}
}
Add it in your settings.gradle.kts at the end of repositories:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
maven { url = uri("https://jitpack.io") }
}
}
Add to pom.xml
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Add it in your build.sbt at the end of resolvers:
resolvers += "jitpack" at "https://jitpack.io"
Add it in your project.clj at the end of repositories:
:repositories [["jitpack" "https://jitpack.io"]]
Step 2. Add the dependency
dependencies {
implementation 'com.github.javierchavez:android-cache:v2.4'
}
dependencies {
implementation("com.github.javierchavez:android-cache:v2.4")
}
<dependency>
<groupId>com.github.javierchavez</groupId>
<artifactId>android-cache</artifactId>
<version>v2.4</version>
</dependency>
libraryDependencies += "com.github.javierchavez" % "android-cache" % "v2.4"
:dependencies [[com.github.javierchavez/android-cache "v2.4"]]
This is a wrapper that eases the use of Google's HttpResponseCache
.
enum
that implements Cachable
.This is where you want to convert server response into real java objects. This is an example where the server is returning JSON array of user objects.
public class UsersSerializer implements Serializer
{
private ArrayList users;
@Override
public <T> T getData ()
{
return (T) users;
}
@Override
public void decode (byte[] data)
{
users = new ArrayList<>();
JSONTokener decoder = new JSONTokener(new String(data));
try
{
JSONArray array = (JSONArray) decoder.nextValue();
for (int i = 0; i < array.length(); i++)
{
User user = new User();
JSONObject obj = (JSONObject) array.get(i);
user.setName(obj.getString("name"));
user.setEmail(obj.getString("email"));
users.add(user);
}
}
catch(JSONException e)
{
}
}
}
This is an example of how you can define your endpoints in a organized fashion.
public enum EndPoints implements Cachable
{
USERS("http://example.com/users")
{
@Override
public long expiration ()
{
return Cachable.ALWAYS;
}
@Override
public Serializer getSerializer ()
{
return new UserSerializer();
}
};
public URL url ()
{
try
{
return new URL(url);
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
return null;
}
private final String url;
public Dataset url (String s)
{
this.url = s;
return this;
}
}
First initialize, by installing a cache. This should really only be called once.
Cache.init(getApplicationContext());
Now you're ready to use it! The return of getData() is generic
EndPoints mCachableData = EndPoints.Users;
List<User> data = Cache.getInstance().getData(mCachableData);
Name: Javier C
Email: javier@javierc.io