Realm Android insertOrUpdate不更新

时间:2016-11-02 04:53:27

标签: android realm

api响应(www.railwayapi.com/api/#trains-between-stations)不包含任何PrimaryKey字段(api不在我的控制之下),所以我创建了另一个类并设置了PK和响应它。 我在StackOverflow上经历了所有类似的问题,并做了相应的工作。数据(使用Retrofit获取)仍然反复插入Realm而不是更新。我该如何解决这个问题?

这就是我将数据保存到Realm的方式:(已编辑)

 private void loadJSON(){

    SearchResultsApiInterface apiService = SearchResultsApiClient.getClient().create(SearchResultsApiInterface.class);
    Call<SearchResultsResponse> call = apiService.getTrainNameResponse(SSC,DSC,DATE,API_KEY);
    call.enqueue(new Callback<SearchResultsResponse>() {
        @Override
        public void onResponse(Call<SearchResultsResponse> call, Response<SearchResultsResponse> response) {

                           final SearchResultsResponse jsonResponse = response.body();
            jsonResponse.setKey(SSC+DSC+DATE);    //EDITED (SSC,DSC,DATE are the EditText valus enter by user)
            final List<Train> data =  jsonResponse.getTrain();
            String from = data.get(0).getFrom().getCode();
            String to = data.get(0).getTo().getCode();
            transaction = realm.executeTransactionAsync(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    realm.insertOrUpdate(jsonResponse);
                }
            }, new Realm.Transaction.OnSuccess() {
                @Override
                public void onSuccess() {
                    Toast.makeText(getApplicationContext(),"Data saved", Toast.LENGTH_LONG).show();}
            }, new Realm.Transaction.OnError() {
                @Override
                public void onError(Throwable error) {
                    Toast.makeText(getApplicationContext(),"Error in saving",Toast.LENGTH_LONG).show();}
            });
            SearchResultsDataAdapter adapter  = new SearchResultsDataAdapter(MainActivity.this,traindata);
            recyclerView.setAdapter(adapter);
            String toolbarTitle = from + " " + "-" + " " + to;
            toolbar.setTitle(toolbarTitle);
        }

        @Override
        public void onFailure(Call<SearchResultsResponse> call, Throwable t) {
            Log.d("Error", "" + t.getMessage());
        }
    });
}

这是回复:(已编辑)

package com.android.vyshnav.indianrailwaysimpledesign.modelSearchTrain;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;

@Generated("org.jsonschema2pojo")
public class SearchResultsResponse extends RealmObject{

@PrimaryKey
private String key;
private int total;
private String error;
private RealmList<Train> train = new RealmList<Train>();
private int response_code;

public String getKey() {
    return key;
}

public void setKey(String key) {
    this.key = key;
}

/**
 *
 * @return
 * The train
 */
public RealmList<Train> getTrain() {
    return train;
}

/**
 *
 * @param train
 * The train
 */
public void setTrain(RealmList<Train> train) {
    this.train = train;
}

/**
 *
 * @return
 * The responseCode
 */
public int getResponseCode() {
    return response_code;
}

/**
 *
 * @param responseCode
 * The response_code
 */
public void setResponseCode(int responseCode) {
    this.response_code = responseCode;
}

/**
 *
 * @return
 * The total
 */
public int getTotal() {
    return total;
}

/**
 *
 * @param total
 * The total
 */
public void setTotal(int total) {
    this.total = total;
}

/**
 *
 * @return
 * The error
 */
public String getError() {
    return error;
}

/**
 *
 * @param error
 * The error
 */
public void setError(String error) {
    this.error = error;
}


}

这是Json的回复:

{
"response_code": 200,
"total": 1,
"train": [
    {
        "no": 1,
        "name": "RAPTI SAGAR EXP",
        "number": "12511",
        "src_departure_time": "06:35",
        "dest_arrival_time": "03:50",
        "travel_time": "21:15",
        "from": {
            "name": "GORAKHPUR JN",
            "code": "GKP"
        },
        "to": {
            "name": "NAGPUR",
            "code": "NGP"
        },
        "classes": [
            {
                "class-code": "FC",
                "available": "N"
            },
            {
                "class-code": "3E",
                "available": "N"
            },
            {
                "class-code": "CC",
                "available": "N"
            },
            {
                "class-code": "SL",
                "available": "Y"
            },
            {
                "class-code": "2S",
                "available": "N"
            },
            {
                "class-code": "2A",
                "available": "Y"
            },
            {
                "class-code": "3A",
                "available": "Y"
            },
            {
                "class-code": "1A",
                "available": "N"
            }
        ],
        "days": [
            {
                "day-code": "MON",
                "runs": "N"
            },
            {
                "day-code": "TUE",
                "runs": "N"
            },
            {
                "day-code": "WED",
                "runs": "N"
            },
            {
                "day-code": "THU",
                "runs": "Y"
            },
            {
                "day-code": "FRI",
                "runs": "Y"
            },
            {
                "day-code": "SAT",
                "runs": "N"
            },
            {
                "day-code": "SUN",
                "runs": "Y"
            }
        ]
    }
]
}

1 个答案:

答案 0 :(得分:0)

您正在获得重复,因为SearchResultsResponse没有主键。

基于您正在使用的API

{
    "response_code": 200,
    "error": "",
    "position": "Train has reached Destination and late by 5 minutes.",
    "train_number": "12046",
    "route": [
        {
            "no": 1,
            "station_": {
                "name": "CHANDIGARH",
                "code": "CDG"
            },
            "has_arrived": false,
            "has_departed": true,
            "day": 0,
            "distance": 0,
            "scharr": "Source",
            "schdep": "12:00",
            "actarr": "00:00",
            "actdep": "12:00",
            "scharr_date": "19 Nov 2015",
            "actarr_date": "19 Nov 2015",
            "latemin": 0
        },
        {
            "no": 2,
            "station_": {
                "name": "AMBALA CANT JN",
                "code": "UMB"
            },
            "has_arrived": true,
            "has_departed": true,
            "day": 0,
            "distance": 67,
            "scharr": "12:40",
            "schdep": "12:42",
            "actarr": "12:40",
            "actdep": "12:42",
            "scharr_date": "19 Nov 2015",
            "actarr_date": "19 Nov 2015",
            "latemin": 0
        },
        {
            "no": 3,
            "station_": {
                "name": "NEW DELHI",
                "code": "NDLS"
            },
            "has_arrived": true,
            "has_departed": false,
            "day": 0,
            "distance": 265,
            "scharr": "15:25",
            "schdep": "Destination",
            "actarr": "15:30",
            "actdep": "00:00",
            "scharr_date": "19 Nov 2015",
            "actarr_date": "19 Nov 2015",
            "latemin": 5
        }
    ]
}

对我而言,您似乎应构建以下RealmObject:

public class TrainRoute extends RealmObject {
    @PrimaryKey
    private String key; // train_number + station_code + scharr_date + scharr

    private long trainNumber;
    private int no;
    private String stationName;
    private String stationCode;
    private boolean hasArrived;
    private boolean hasDeparted;
    private int day;
    private int distance;
    private String scharr;
    private String schdep;
    private String actarr;
    private String actdep;
    private String scharrDateText;
    private String actarrDateText;
    private Date scharrDate;
    private Date actarrDate;
    private int latemin;

    // getter setter
}

之后,您的主键应该具体且相同,并且不应相互覆盖。