java - Class relationship, NullPointerException error -
i have 2 classes of authors , books:
public class authors extends realmobject { @primarykey private string url_base; private realmlist<books> books; ... getters & setters... public realmlist<books> getbooks() { return books; } public void setbooks(realmlist<books> books) { this.books = books; } } public class books extends realmobject { @primarykey private string url_base; private authors author; ... getters & setters... public authors getauthor() { return author; } public void setauthor(authors author) { this.author = author; } }
perform inserts:
authors author = new authors(); author.seturl_base("url_base") books book = new books(); book.seturl_base("lala"); book.setauthor(author); author.getbooks().add(book); // error comes here realm.begintransaction(); realm.copytorealmorupdate(author); realm.committransaction();
and program gives java.lang.nullpointerexception.
error line : author.getbooks().add (book);
what wrong? ask help.
you haven't set books
member author object (as books
not initialized null
) getbooks()
return null
.
make sure books
initialized before using :
public class authors extends realmobject { @primarykey private string url_base; private realmlist<books> books = new realmlist<books>(); // empty unmanaged books list. ... getters & setters...
or use setter method (though initializing on construction more correct in case):
authors author = new authors(); author.seturl_base("url_base") author.setbooks(new realmlist<book>());
update:
as @andreyatapin correctly noted in solution above list unmanaged. if want managed list pass required arguments specified in realmlist
api whatever choose books list must initialized before start manipulating it
Comments
Post a Comment