我想从数据库中获取对象列表,并在网络请求更新数据库中的这些对象后。
public class TripTrack extends RealmObject {
private int tripId;
private double latitude;
private double longitude;
private long downtime;
private long timestamp;
private boolean sent;
public int getTripId() {
return tripId;
}
public void setTripId(int tripId) {
this.tripId = tripId;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public long getDowntime() {
return downtime;
}
public void setDowntime(long downtime) {
this.downtime = downtime;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public boolean isSent() {
return sent;
}
public void setSent(boolean sent) {
this.sent = sent;
}
}
从数据库获取:
List<TripTrack> localTrack = new ArrayList<>();
try (Realm realmInstance = Realm.getDefaultInstance()) {
realmInstance.executeTransaction((realm) -> {
List<TripTrack> trackFromDB = realm.where(TripTrack.class).equalTo("sent", false).findAll();
localTrack.addAll(realm.copyFromRealm(trackFromDB));
});
}
updateTrack(localTrack);
发送:
private void updateTrack(List<TripTrack> localTrack) {
JSONObject params = new JSONObject();
try {
JSONArray locations = new JSONArray();
for(TripTrack tripTrack : localTrack) {
JSONObject loc = new JSONObject();
loc.put("trip_id", String.valueOf(tripTrack.getTripId()));
loc.put("latitude", String.valueOf(tripTrack.getLatitude()));
loc.put("longitude", String.valueOf(tripTrack.getLongitude()));
loc.put("downtime", String.valueOf(tripTrack.getDowntime()));
loc.put("timestamp", String.valueOf(tripTrack.getTimestamp()));
locations.put(loc);
}
params.put("locations", locations);
} catch (JSONException e) {
e.printStackTrace();
}
UpdateTripTrackRequest updateTripTrackRequest = new UpdateTripTrackRequest<>(this, params, DefaultResponse.class, new Response.Listener<DefaultResponse>() {
@Override
public void onResponse(DefaultResponse response) {
if(response.getCode() == 0) {
try (Realm realmInstance = Realm.getDefaultInstance()) {
realmInstance.executeTransaction((realm) -> {
for(TripTrack tripTrack : localTrack) {
tripTrack.setSent(true);
realm.copyToRealmOrUpdate(tripTrack);
}
});
}
}
}
}
// . . .
因为copyToRealmOrUpdate
我需要@PrimaryKey
。但是 Realm 不支持 PrimaryKey 的自增。是否可以在没有主键的情况下执行上述操作?我应该按照这里的描述创建主键吗?