/
Cache.java
57 lines (46 loc) · 1.59 KB
/
Cache.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package app.abhijit.iter.data;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Map;
import app.abhijit.iter.models.Student;
/**
* This class handles local storage and retrieval of Student objects.
*/
public class Cache {
private SharedPreferences sharedPreferences;
private Gson gson;
public Cache(Context context) {
this.sharedPreferences = context.getSharedPreferences("students", Context.MODE_PRIVATE);
this.gson = new Gson();
}
@Nullable
public Student getStudent(@Nullable String username) {
try {
return gson.fromJson(this.sharedPreferences.getString(username, null), Student.class);
} catch (Exception e) {
return null;
}
}
@NonNull
public ArrayList<Student> getStudents() {
ArrayList<Student> students = new ArrayList<>();
for (Map.Entry<String, ?> entry : this.sharedPreferences.getAll().entrySet()) {
Student student = getStudent(entry.getKey());
if (student != null) {
students.add(student);
}
}
return students;
}
public void setStudent(@Nullable String username, @Nullable Student student) {
if (student == null) {
this.sharedPreferences.edit().remove(username).apply();
} else {
this.sharedPreferences.edit().putString(username, gson.toJson(student)).apply();
}
}
}