获得错误'价值'在Android应用程序中实现Realm时,它不是有效的托管对象

时间:2017-09-02 20:14:33

标签: android json realm illegalargumentexception

在我的应用程序中,我必须从rest api获取json数据。我在应用程序中使用Realm作为本地数据库。现在,在创建模型类之后,我有一个控制器类,我在其中执行反序列化并将存储的功能存储到Realm db中。但不幸的是,每当我点击选项查看新闻页面时,应用程序就会崩溃。我在代码中解释过。

NewsRealmModel Class

    public class NewsRealmModel extends RealmObject {
    public static final String ID = "id";

    private String _id;
    private String body;   
    private String title;
    private String updatedDate;
    private RealmList<AppImage> appImages;
    private String updatedAt;
    private TeaserImageSmall teaserImageSmall;

    public NewsRealmModel() {

    }

    public static String getID() {
        return ID;
    }

    public String get_id() {
        return _id;
    }

    public void set_id(String _id) {
        this._id = _id;
    }

    public String getBody() {
        return body;
    }

    public void setUpdatedDate(String updatedDate) {
        this.updatedDate = updatedDate;
    }


    public RealmList<AppImage> getAppImages() {
        return appImages;
    }

    public void setAppImages(RealmList<AppImage> appImages) {
        this.appImages = appImages;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

    public TeaserImageSmall getTeaserImageSmall() {
        return teaserImageSmall;
    }

 //getting error for this.teaserImageSmall = teaserImageSmall;
    public void setTeaserImageSmall(TeaserImageSmall teaserImageSmall) {
        this.teaserImageSmall = teaserImageSmall;
    }
   }

TeaserImageSmall Class

public class TeaserImageSmall extends RealmObject{

private String alt;
private String src;

public String getSrc() {
    return src;
}

public void setSrc(String src) {
    this.src = src;
}

}

现在,AppImage类

    public class AppImage extends RealmObject{

    private String _id;


    private String alt;

    private String src;

    //getter and setter
}

控制器类是

 public class NewsController {
    private static final String TAG = NewsController.class.getSimpleName();
    private UserCallbackListener mListener;
    private NewsRestApiManager mApiManager;
    private AppImage appImages;


    Realm myNews_realm;

    public NewsController(NewsPage listener) {
        mListener = listener;
        mApiManager = new NewsRestApiManager();
    }

    public void startFetching(){
        myNews_realm = Realm.getDefaultInstance();
        mApiManager.getNewsApi().getNews(new Callback<String>() {

            @Override
            public void success(String s, Response response) {
                Log.d(TAG, "JSON :: " + s);

                try {
                    JSONArray array = new JSONArray(s);

                    for(int i = 0; i < array.length(); i++) {
                        JSONObject jsonObject = array.getJSONObject(i);
                        Log.d("-----Start Fetching---", jsonObject.optString( "title" ));
                        myNews_realm.beginTransaction();
                        NewsRealmModel news = myNews_realm.createObject( NewsRealmModel.class );
                        news.setTitle( jsonObject.optString( "title") );
                        news.setBody( jsonObject.optString( "body" ) );
                        news.setUpdatedAt( jsonObject.getString( "updated_at" ) );

                        ArrayList<AppImage> list = new ArrayList();
                        JSONArray imageArray =jsonObject.getJSONArray("appImages");
                        if (imageArray.length() > 1) {
                            for(int j=0; j<imageArray.length();j++){
                                appImages  = new AppImage();
                                try {
                                    appImages.setSrc( new JSONArray( s ).getJSONObject( i ).getJSONArray( "appImages" ).getJSONObject( j ).optString( "src" ) );
                                }catch (JSONException e){
                                    e.printStackTrace();
                                }
                                list.add(appImages);
                            }
                        }
                        news.setAppImages( list ); // I am getting error for this line

                        TeaserImageSmall coverImage=new TeaserImageSmall();
                        coverImage.setSrc( new JSONArray( s ).getJSONObject( i ).getJSONObject( "teaserImageSmall" ).optString( "src" ));

    news.setTeaserImageSmall(myNews_realm.copyToRealmOrUpdate(coverImage));; //error in this line
                        myNews_realm.commitTransaction();



                    }
                } catch (JSONException e) {
                    mListener.onFetchFailed();
                }

                mListener.onFetchComplete();
            }

            @Override
            public void failure(RetrofitError error) {
                Log.d(TAG, "Error :: " + error.getMessage());
                mListener.onFetchComplete();
            }
        });

    }
    public interface UserCallbackListener{
        void onFetchStart();
        void onFetchComplete();
        void onFetchFailed();
    }
}

Logcat显示以下错误

09-02 21:11:43.050 7337-7337/demo.app.com.bluapp_client_and E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: demo.app.com.bluapp_client_and, PID: 7337
                                                                          java.lang.IllegalArgumentException: A RealmObject with no @PrimaryKey cannot be updated: class demo.app.com.bluapp_client_and.RealmModel.TeaserImageSmall
                                                                              at io.realm.Realm.checkHasPrimaryKey(Realm.java:1615)
                                                                              at io.realm.Realm.copyToRealmOrUpdate(Realm.java:1030)
                                                                              at demo.app.com.bluapp_client_and.controller.NewsController$1.success(NewsController.java:134)
                                                                              at demo.app.com.bluapp_client_and.controller.NewsController$1.success(NewsController.java:99)

1 个答案:

答案 0 :(得分:2)

如果替换

,您的代码将不会再出现此错误
news.setTeaserImageSmall(coverImage); //error in this line

使用

news.setTeaserImageSmall(realm.copyToRealm(coverImage));

由于news是托管对象,因此coverImage也必须是托管对象。