/
DatabaseController.java
117 lines (95 loc) · 3.25 KB
/
DatabaseController.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package hani.weather.utils;
import android.app.Activity;
import android.app.Application;
import android.support.v4.app.Fragment;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import hani.weather.BuildConfig;
import hani.weather.models.Weather;
import hani.weather.models.api.weather.WeatherApiResponse;
import hani.weather.models.City;
import io.realm.Realm;
import io.realm.RealmResults;
/**
* Created by hani.momanii on 9/2/16.
*/
public class DatabaseController {
private static DatabaseController instance;
private final Realm realm;
public DatabaseController(Application application) {
realm = Realm.getDefaultInstance();
}
public static DatabaseController with(Application application) {
if (instance == null) {
instance = new DatabaseController(application);
}
return instance;
}
public Realm getRealm() {
return realm;
}
public void addCity(final City city) throws Exception {
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(city);
}
});
}
public void addCityList(final List<City> cities) throws Exception {
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(cities);
}
});
}
public void addWeather(final Weather weather) {
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
try {
realm.copyToRealmOrUpdate(weather);
} catch (Exception e) {
Log.e(Constants.TAG, "" + e.getMessage());
realm.cancelTransaction();
}
}
});
}
public void clearWeather(final City city) {
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
try {
RealmResults<Weather> result = realm.where(Weather.class).equalTo("city.id", city.getId()).findAll();
result.deleteAllFromRealm();
} catch (Exception e) {
Log.e(Constants.TAG, "" + e.getMessage());
realm.cancelTransaction();
}
}
});
}
public void deleteCity(final City city) throws Exception {
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
RealmResults<City> result = realm.where(City.class).equalTo("id", city.getId()).findAll();
result.deleteAllFromRealm();
}
});
}
public List<City> getCities() {
List<City> cities = realm.where(City.class).findAll();
for (City city : cities) {
Utility.log(city.getCityName());
}
return cities;
}
public List<Weather> getWeather(final City city) {
List<Weather> weathers = realm.where(Weather.class).equalTo("city.id", city.getId()).findAll();
return weathers;
}
}