Realm query result always null - java

i've got a Realm DB containing some Item. I've populated the DB getting info from my online DB but when i try to execute a query on DB it gives always null data.
Im sure that data from DB is not null.
I've populated the DB as official site shows.
Here where i use my query's result:
public void onBindViewHolder(ViewHolder holder, int position) {
Item result = ItemHandler.getItem(mDataset.get(position));
Picasso.get().load(result.getImg()).resize(100,100).onlyScaleDown().centerCrop().into(holder.itemImage);
holder.itemName.setText(result.getName());
holder.itemValue.setText(result.getSell_value());
//TODO when clicked open a dialog
}
Query method:
public static Item getItem(int id){
Realm realm = Realm.getDefaultInstance();
return realm.where(Item.class).equalTo("id", id).findFirst();
}
Item class:
public class Item extends RealmObject {
private int id;
private String name;
private String description;
private int img;
private int buff_health;
private int buff_damage;
private int buff_armor;
private int buy_value;
private int sell_value;
public int getBuy_value() {
return buy_value;
}
public void setBuy_value(int buy_value) {
this.buy_value = buy_value;
}
public int getSell_value() {
return sell_value;
}
public void setSell_value(int sell_value) {
this.sell_value = sell_value;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getImg() {
return img;
}
public void setImg(int img) {
this.img = img;
}
public int getBuff_health() {
return buff_health;
}
public void setBuff_health(int buff_health) {
this.buff_health = buff_health;
}
public int getBuff_damage() {
return buff_damage;
}
public void setBuff_damage(int buff_damage) {
this.buff_damage = buff_damage;
}
public int getBuff_armor() {
return buff_armor;
}
public void setBuff_armor(int buff_armor) {
this.buff_armor = buff_armor;
}
}
EDIT: here is where i store my data:
public static void addToDB(List<ItemMaster> itemMasterList, Resources resource){
Realm myRealm = Realm.getDefaultInstance();
for(int i = 0; i < itemMasterList.size(); i++){
myRealm.beginTransaction();
Item item = myRealm.createObject(Item.class);
item.setId(itemMasterList.get(i).getId());
item.setName(itemMasterList.get(i).getName());
item.setDescription(itemMasterList.get(i).getDescription());
item.setBuff_armor(itemMasterList.get(i).getBuff_armor());
item.setBuff_damage(itemMasterList.get(i).getBuff_damage());
item.setBuff_health(itemMasterList.get(i).getBuff_health());
item.setBuy_value(itemMasterList.get(i).getBuy_value());
item.setSell_value(itemMasterList.get(i).getSell_value());
item.setImg(resource.getIdentifier("item_" + itemMasterList.get(i).getId(), "drawable", null));
myRealm.commitTransaction();
}
myRealm.close();
//TODO check this, last watch, not saving
}

Related

update query not working?

I have the following Dao class:
#Dao
public interface AchievementDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertIntoDatabase(AchievementModel... achievementModel);
#Query("SELECT * FROM achievements WHERE game = :game")
AchievementModel[] getAchievementDataForGame(String game);
#Query("UPDATE achievements SET pointsAchieved = pointsAchieved + :points WHERE achievementKey = :achievementKey")
void updatePointsForKey(double points, String achievementKey);
#Query("SELECT * FROM achievements WHERE achievementKey LIKE :achievementKey")
AchievementModel getAchievementForKey(String achievementKey);
}
and the following model class:
#Entity(tableName = "achievements", indices = {#Index(value = {"achievementKey"}, unique = true)})
public class AchievementModel {
#PrimaryKey #NonNull
private String achievementKey;
private String title;
private String description;
private double pointsAchieved;
private int imageId;
private int viewType;
private String game;
public AchievementModel(#NonNull String achievementKey, String title, String description,
double pointsAchieved, int imageId, int viewType, String game) {
this.achievementKey = achievementKey;
this.title = title;
this.description = description;
this.pointsAchieved = pointsAchieved;
this.imageId = imageId;
this.viewType = viewType;
this.game = game;
}
#NonNull
public String getAchievementKey() {
return achievementKey;
}
public void setAchievementKey(#NonNull String achievementKey) {
this.achievementKey = achievementKey;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPointsAchieved() {
return pointsAchieved;
}
public void setPointsAchieved(double pointsAchieved) {
this.pointsAchieved = pointsAchieved;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public int getViewType() {
return viewType;
}
public void setViewType(int viewType) {
this.viewType = viewType;
}
public String getGame() {
return game;
}
public void setGame(String game) {
this.game = game;
}
}
The first 2 queries in the DAO class are working absolutely fine whereas the last 2 queries updatePointsForKey and getAchievementForKey are not working. They are being called correctly from a background thread. Please help. Do tell me if more information is required about the question.
The update query maybe returns an int instead of void ... What do you think ?

Custom TiledDataSource with paging library

I tried to implement custom TiledDataSource for using with paging library. When I used LivePagedListProvider like returns type for my Dao method it worked fine (after table items updating - ui updated automatically).
#Query("SELECT * FROM " + Table.States.PLAY_STATE + ", "+Table.Chart.ARTIST+ " ORDER BY position ASC")
LivePagedListProvider<Artist> loadArtists();
But when I try implement custom TiledDataSource for LivePagerListProvider table updates not triggered my observers.
Abstract generic class:
public abstract class PagedNetworkBoundResource<ResultType, RequestType> extends TiledDataSource<ResultType> {
#Override
public int countItems() {
return DataSource.COUNT_UNDEFINED;
}
#Override
public List<ResultType> loadRange(int startPosition, int count) {
fetchFromNetwork(startPosition, count);
return loadFromDb(startPosition, count);
}
#WorkerThread
private void fetchFromNetwork(int startPosition, int count) {
if (createCall(startPosition, count) != null)
try {
Response<RequestType> response = createCall(startPosition, count).execute();
if (response.isSuccessful() && response.code() == 200) {
saveCallResult(response.body());
}
} catch (IOException e) {
e.printStackTrace();
}
}
#WorkerThread
protected abstract void saveCallResult(#NonNull RequestType item);
#WorkerThread
protected abstract List<ResultType> loadFromDb(int startPosition, int count);
#WorkerThread
protected abstract Call<RequestType> createCall(int startPosition, int count);
public LiveData<PagedList<ResultType>> getAsLiveData() {
return new LivePagedListProvider<Integer, ResultType>() {
#Override
protected DataSource<Integer, ResultType> createDataSource() {
return PagedNetworkBoundResource.this;
}
}.create(0, new PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(20)
.setInitialLoadSizeHint(20)
.build());
}
}
My dao method for this case:
#Query("SELECT * FROM " + Table.States.PLAY_STATE + ", "+Table.Chart.ARTIST+ " ORDER BY position ASC LIMIT (:limit) OFFSET (:offset)")
List<Artist> loadArtists(int offset, int limit);
I update Table.States.PLAY_STATE.
public void updatePlayerState(PlayerStateEntity state){
new Thread(() -> {
dao.deleteState();
dao.insertState(state);
}).run();
}
#Dao
public interface PlayStateDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertState(PlayerStateEntity playEntity);
#Query("DELETE FROM " + Table.States.PLAY_STATE)
void deleteState();
#Query("SELECT * FROM "+Table.States.PLAY_STATE)
PlayerStateEntity getPlayerState();
}
#Entity(tableName = Table.States.PLAY_STATE)
public class PlayerStateEntity extends IdEntity {
#ColumnInfo(name = "album_played_id")
private Long albumPlayedId = -1L;
#ColumnInfo(name = "track_played_id")
private Long trackPlayedId = -1L;
#ColumnInfo(name = "artist_played_id")
private Long artistPlayedId = -1L;
#ColumnInfo(name = "state")
private PlayingState state;
#ColumnInfo(name = "playing_type")
private PlayingType playingType;
public Long getAlbumPlayedId() {
return albumPlayedId;
}
public void setAlbumPlayedId(Long albumPlayedId) {
this.albumPlayedId = albumPlayedId;
}
public Long getTrackPlayedId() {
return trackPlayedId;
}
public void setTrackPlayedId(Long trackPlayedId) {
this.trackPlayedId = trackPlayedId;
}
public Long getArtistPlayedId() {
return artistPlayedId;
}
public void setArtistPlayedId(Long artistPlayedId) {
this.artistPlayedId = artistPlayedId;
}
public PlayingState getState() {
return state;
}
public void setState(PlayingState state) {
this.state = state;
}
public PlayingType getPlayingType() {
return playingType;
}
public void setPlayingType(PlayingType playingType) {
this.playingType = playingType;
}
}
class Artist extends PlayEntity{
private String name;
private String link;
private String picture;
#ColumnInfo(name = "picture_small")
private String pictureSmall;
#ColumnInfo(name = "picture_medium")
private String pictureMedium;
#ColumnInfo(name = "picture_big")
private String pictureBig;
#ColumnInfo(name = "picture_xl")
private String pictureXl;
private Boolean radio;
private String tracklist;
private Integer position;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getPictureSmall() {
return pictureSmall;
}
public void setPictureSmall(String pictureSmall) {
this.pictureSmall = pictureSmall;
}
public String getPictureMedium() {
return pictureMedium;
}
public void setPictureMedium(String pictureMedium) {
this.pictureMedium = pictureMedium;
}
public String getPictureBig() {
return pictureBig;
}
public void setPictureBig(String pictureBig) {
this.pictureBig = pictureBig;
}
public String getPictureXl() {
return pictureXl;
}
public void setPictureXl(String pictureXl) {
this.pictureXl = pictureXl;
}
public Boolean getRadio() {
return radio;
}
public void setRadio(Boolean radio) {
this.radio = radio;
}
public String getTracklist() {
return tracklist;
}
public void setTracklist(String tracklist) {
this.tracklist = tracklist;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
#Override
public boolean isItemPlaying() {
return getId() == getArtistPlayedId().longValue() && getPlayingType() == PlayingType.Artist && getState() == PlayingState.Playing;
}
}
public abstract class PlayEntity extends PlayerStateEntity {
public abstract boolean isItemPlaying();
}
public class ArtistsRepository {
private final ChartArtistDao chartArtistDao;
private final DeezerService deezerService;
#Inject
public ArtistsRepository(ChartArtistDao chartArtistDao, DeezerService deezerService) {
this.chartArtistDao = chartArtistDao;
this.deezerService = deezerService;
}
public LiveData<PagedList<ChartArtistDao.Artist>> getArtist() {
return new PagedNetworkBoundResource<ChartArtistDao.Artist, ModelList<ChartArtistEntity>>() {
#Override
protected void saveCallResult(#NonNull ModelList<ChartArtistEntity> item) {
if (item != null) {
chartArtistDao.saveArtists(item.getItems());
}
}
#Override
protected List<ChartArtistDao.Artist> loadFromDb(int startPosition, int count) {
return chartArtistDao.loadArtists(startPosition, count);
}
#Override
protected Call<ModelList<ChartArtistEntity>> createCall(int startPosition, int count) {
return deezerService.getChartArtist(startPosition, count);
}
}.getAsLiveData();
}
}
For each Artist items I add fields from PlayerStateEntity (not good solution but this easy way to represent state of ui items). After PlayerStateEntity table updates Room should notify about data changes, but doesn't do it.
I understand that Room doesn't know about query what I used, and can't updates my RecyclerView which provide by paging library. But maybe some one knows how to notify Room about tables which I used inside mine DataSource for future triggering ui updates?
The problem was related with custom DataSource realization. When data has changed, LivePagedListProvider should create a new DataSource instance for right ui updating. I used the same instance, so my previous solution is not right.

How to sort the arraylist with two different model class in android?

I'm creating the grid view with array list of category and un categorized product model class. Now I want to sort the list by date or name. See below my code.
Here this is my adapter.
public class CommonAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater inflator = null;
private List<Object> list;
public CommonAdapter(Context mContext, List<Object> list) {
super();
this.mContext = mContext;
this.list = list;
inflator = LayoutInflater.from(mContext);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflator.inflate(R.layout.row_categories, null);
holder = new ViewHolder();
holder.layout_bg = (RelativeLayout) convertView.findViewById(R.id.grid_bg);
holder.titleTextView = (TextView) convertView.findViewById(R.id.grid_item_title);
holder.txt_price = (TextView) convertView.findViewById(R.id.txt_price);
holder.img_notifier = (ImageView) convertView.findViewById(R.id.img_notifier);
holder.titleTextView.setTextColor(Color.WHITE);
holder.titleTextView.setTextSize(27);
holder.titleTextView.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
holder.titleTextView.setLayoutParams(new RelativeLayout.LayoutParams(200, 200));
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (list.get(position) instanceof Product) {
holder.titleTextView.setText(((Product) list.get(position)).getShortCode());
holder.img_notifier.setVisibility(ImageView.GONE);
holder.txt_price.setVisibility(TextView.VISIBLE);
NumberFormat format = NumberFormat.getCurrencyInstance();
double amount = Double.parseDouble(((Product) list.get(position)).getPrice()toString());
String formatAmount = NumberFormat.getCurrencyInstance().format(amount / 100);
holder.txt_price.setText(formatAmount);
}
if (list.get(position) instanceof Category) {
holder.titleTextView.setText(((CategoryWithProduct) list.get(position)).getShortCode());
holder.img_notifier.setVisibility(ImageView.VISIBLE);
holder.txt_price.setVisibility(TextView.GONE);
if (((Category) list.get(position)).getColor() != null) {
holder.layout_bg.setBackgroundColor(Color.parseColor(((Category) list.get(position)).getColor()));
} else {
}
}
return convertView;
}
static class ViewHolder {
RelativeLayout layout_bg;
TextView titleTextView, txt_price;
ImageView img_notifier;
}
This is product model classes
public class Product {
String id;
String name;
String price;
String createAt;
public Product(String id, String name, String price, String createAt) {
this.id = id;
this.name = name;
this.price = price;
this.createAt = createAt;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getCreateAt() {
return createAt;
}
public void setCreateAt(String createAt) {
this.createAt = createAt;
}
}
This is Category Model
public class Category {
String id;
String name;
String createAt;
public Category(String id, String name, String createAt) {
this.id = id;
this.name = name;
this.createAt = createAt;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCreateAt() {
return createAt;
}
public void setCreateAt(String createAt) {
this.createAt = createAt;
}
}
In MainActivity.java
CommonAdapter commonAdapter = new CommonAdapter(getActivity(), commonArrayList);
grid_common.setAdapter(commonAdapter);
Here I tried with comparator, it's comes with object only!
Collections.sort(commonArrayList, new Comparator<Object>() {
#Override
public int compare(Object o1, Object o2) {
return 0;
}
});
See here both models have createAt and name fields, So I want to sort by createAt or by name in this ArrayList.
Create another object model class and add all method and variable there is in two separate class...
and set data manually then... using for loop and any other ..that suitable for you...
and you this third created object model for sorting your data...
Edited
Eg:
first class
class first{
String f_name,l_name;
public String getF_name() {
return f_name;
}
public void setF_name(String f_name) {
this.f_name = f_name;
}
public String getL_name() {
return l_name;
}
public void setL_name(String l_name) {
this.l_name = l_name;
}
}
Second class
public class second {
String f_name,l_name,m_name;
public String getF_name() {
return f_name;
}
public void setF_name(String f_name) {
this.f_name = f_name;
}
public String getL_name() {
return l_name;
}
public void setL_name(String l_name) {
this.l_name = l_name;
}
public String getM_name() {
return m_name;
}
public void setM_name(String m_name) {
this.m_name = m_name;
}
}
third class
public class third{
String f_name,l_name,m_name;
public String getF_name() {
return f_name;
}
public void setF_name(String f_name) {
this.f_name = f_name;
}
public String getL_name() {
return l_name;
}
public void setL_name(String l_name) {
this.l_name = l_name;
}
public String getM_name() {
return m_name;
}
public void setM_name(String m_name) {
this.m_name = m_name;
}
}
set all value of first and second into third...
and use third class for setup data and sorting data
Here is my advice:
public class Category {
String id;
String name;
String createAt;
...
}
public class Product extends Category{
String price;
....
}
Collections.sort(commonArrayList, new Comparator<Category>() {
#Override
public int compare(Category o1, Category o2) {
if(o1.getCreateAt()>o2.getCreateAt()){
return 1;
}else{
...
}
return 0;
}
});
Create an abstract class, put fields common in Product and Category and compare that class.
public abstract class BaseClass {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Your Public class:
public class Product extends BaseClass {
...
public Product(String id, String name, String price, String createAt) {
setId(id);
setName(name);
this.price = price;
this.createAt = createAt;
}
}
Category class:
public class Category extends BaseClass {
...
public Category(String id, String name, String createAt) {
setId(id);
setName(name);
this.createAt = createAt;
}
}
And compare like this:
Collections.sort("ArrayList<BaseClass>()", new Comparator<BaseClass>() {
#Override
public int compare(BaseClass baseClass, BaseClass t1) {
return baseClass.getName().compareTo(t1.getName());
}
});
If you wanna sort by date put date field to BaseClass.
Thanks for your advice. I found the answer. I just make class casting on the object inside the comparator.
See the code below,
Collections.sort(commonArrayList, new Comparator<Object>() {
#Override
public int compare(Object o1, Object o2) {
int res = 0;
if (o1 instanceof Category && o2 instanceof Category) {
res = (((Category) o1).getName().compareTo(((Category) o2).getName()));
} else if (o1 instanceof Product && o2 instanceof Product) {
res = (((Product) o1).getName().compareTo(((Product) o2).getName()));
} else if (o1 instanceof Category && o2 instanceof Product) {
res = (((Category) o1).getName().compareTo(((Product) o2).getName()));
} else if (o1 instanceof Product && o2 instanceof Category) {
res = (((Product) o1).getName().compareTo(((Category) o2).getName()));
}
return res;
}
});
If you have any simplified ideas, kindly post here..
Hope this sample solution in java may help :
Create an interface let say Data as follows
public interface Data {
}
Create the model classes as follows :
Product
public class Product implements Data{
String id;
String name;
String price;
String createAt;
public Product(String id, String name, String price, String createAt) {
this.id = id;
this.name = name;
this.price = price;
this.createAt = createAt;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getCreateAt() {
return createAt;
}
public void setCreateAt(String createAt) {
this.createAt = createAt;
}
}
Category
public class Category implements Data{
String id;
String name;
String createAt;
public Category(String id, String name, String createAt) {
this.id = id;
this.name = name;
this.createAt = createAt;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCreateAt() {
return createAt;
}
public void setCreateAt(String createAt) {
this.createAt = createAt;
}
}
Now in main class of the project
public class TestSorting {
public static void main(String args[]) {
ArrayList<Data> categories = new ArrayList<>();
ArrayList<Data> products = new ArrayList<Data>();
// For Product
for (int i = 0; i < 10; i++) {
Product product = new Product("Prod" + i, "Product " + i, "" + i, System.currentTimeMillis() + "");
products.add(product);
}
// For category
for (int i = 10; i >=0; i--) {
Category category = new Category("Cat" + i, "Category " + i, System.currentTimeMillis() + "");
categories.add(category);
}
Collections.sort(categories, new Comparator<Data>() {
#Override
public int compare(Data data, Data data2) {
if(data instanceof Category)
{
int result=(((Category) data).getId().compareTo((((Category) data2).getId())));
return result;
}else if(data instanceof Product)
{
int result= (((Product) data).getId().compareTo(((Product) data2).getId()));
return result;
}else {
return 0;
}
}
});
System.out.println("******PRODUCT****************");
// For Product
for (int i = 0; i < products.size(); i++) {
Product product=((Product)products.get(i));
System.out.println(product.id+ " "+product.name);
}
System.out.println("\n\n"+"******Caterogy****************");
// For category
for (int i = 0; i < categories.size(); i++) {
Category category=((Category)categories.get(i));
System.out.println(category.id+ " "+category.name);
}
}
}

Realm object not fully persisted

I'm having trouble trying to understand how realm.io persist/save objects.
I have 3 Objects (Inventory, InventoryItem and Product);
When I create a Inventory containing InventoryItems it works fine until i close the app. When i re-open the app all InventoryItems loses the reference to Product and start to show "null" instead.
Strange thing is all other attributes like Inventory reference to InventoryItem is persisted fine. Just problem with Products.
this is how i'm trying to do:
Model
Product
public class Product extends RealmObject {
#PrimaryKey
private String id;
#Required
private String description;
private int qtdUnityType1;
private int qtdUnityType2;
private int qtdUnityType3;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getQtdUnityType1() {
return qtdUnityType1;
}
public void setQtdUnityType1(int qtdUnityType1) {
this.qtdUnityType1 = qtdUnityType1;
}
public int getQtdUnityType2() {
return qtdUnityType2;
}
public void setQtdUnityType2(int qtdUnityType2) {
this.qtdUnityType2 = qtdUnityType2;
}
public int getQtdUnityType3() {
return qtdUnityType3;
}
public void setQtdUnityType3(int qtdUnityType3) {
this.qtdUnityType3 = qtdUnityType3;
}
}
Inventory
public class Inventory extends RealmObject {
#PrimaryKey
private String id;
#Required
private String type;
#Required
private Date createdAt;
#Required
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
private RealmList<InventoryItem> listItems;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public RealmList<InventoryItem> getListItems() {
return listItems;
}
public void setListItems(RealmList<InventoryItem> listItems) {
this.listItems = listItems;
}
}
InventoryItem
public class InventoryItem extends RealmObject {
#PrimaryKey
private String idItem;
private Inventory inventory;
private Product product;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
private Date expirationDate;
private int qtdUnityType1;
private int qtdUnityType2;
private int qtdUnityType3;
private int qtdDiscard;
public String getIdItem() {
return idItem;
}
public void setIdItem(String idItem) {
this.idItem = idItem;
}
public Inventory getInventory() {
return inventory;
}
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
public Date getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public int getQtdUnityType1() {
return qtdUnityType1;
}
public void setQtdUnityType1(int qtdUnityType1) {
this.qtdUnityType1 = qtdUnityType1;
}
public int getQtdUnityType2() {
return qtdUnityType2;
}
public void setQtdUnityType2(int qtdUnityType2) {
this.qtdUnityType2 = qtdUnityType2;
}
public int getQtdUnityType3() {
return qtdUnityType3;
}
public void setQtdUnityType3(int qtdUnityType3) {
this.qtdUnityType3 = qtdUnityType3;
}
public int getQtdDiscard() {
return qtdDiscard;
}
public void setQtdDiscard(int qtdDiscard) {
this.qtdDiscard = qtdDiscard;
}
}
and finally one of the millions ways i tried to persist
realm.beginTransaction();
Inventory inventory = realm.createObject(Inventory.class);
inventory.setId(id);
inventory.setCreatedAt(new DateTime().toDate());
if (radioGroup.getCheckedRadioButtonId() == R.id.rbInventario) {
inventory.setType("Inventário");
} else {
inventory.setType("Validade");
}
inventory.setStatus("Aberto");
RealmList<InventoryItem> inventoryItems = new RealmList<>();
RealmResults<Product> productsRealmResults = realm.allObjects(Product.class);
for (int i = 1; i <= productsRealmResults.size(); i++) {
InventoryItem item = realm.createObject(InventoryItem.class);
item.setIdProduct(productsRealmResults.get(i - 1).getId() + " - " + productsRealmResults.get(i - 1).getDescription());
item.setProduct(productsRealmResults.get(i - 1));
item.setIdItem(i + "-" + id);
item.setInventory(inventory);
item = realm.copyToRealmOrUpdate(item);
item = realm.copyToRealmOrUpdate(item);
inventoryItems.add(item);
}
inventory.setListItems(inventoryItems);
realm.copyToRealmOrUpdate(inventory);
realm.commitTransaction();
I already looked trough some answers here like this one:
stack answer
and the Java-examples (person, dog, cat)
provided with the API
but I can't understand how to properly insert this.
The problem is that you are setting a list of InventoryItem elements which are not added to the Realm database.
Change InventoryItem item = new InventoryItem(); to InventoryItem item = realm.createObject(InventoryItem.class);
Also, the inventoryItems themselves aren't stored in Realm db. Add realm.copyToRealmOrUpdate(inventoryItems) after the loop.

JSON to Java Mapping Help - Nested Collection

I'm trying to figure out a way to transform this JSON String into a Java object graph but I'm unable to do so. Below, I've inserted my JSON String, and my two classes. I've verified that its a valid json structure. I've been trying googles api (http://sites.google.com/site/gson/gson-user-guide) but it doesn't map the nested Photo Collection. Any ideas or alternate libraries?
{"photos":{"page":1,"pages":73514,"perpage":50,"total":"3675674","photo":[{"id":"5516612975","owner":"23723942#N07","secret":"b8fb1fda57","server":"5213","farm":6,"title":"P3100006.JPG","ispublic":1,"isfriend":0,"isfamily":0},{"id":"5516449299","owner":"81031835#N00","secret":"67b56722da","server":"5171","farm":6,"title":"Kaiser Boys Volleyball","ispublic":1,"isfriend":0,"isfamily":0}]},"stat":"ok"}
Photos.java
public class Photos {
private int pages;
private int perpage;
private String total;
private List<Photo> photo;
private String stat;
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public int getPerpage() {
return perpage;
}
public void setPerpage(int perpage) {
this.perpage = perpage;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public List<Photo> getPhoto() {
return photo;
}
public void setPhoto(List<Photo> photo) {
this.photo = photo;
}
public String getStat() {
return stat;
}
public void setStat(String stat) {
this.stat = stat;
}
}
Photo.java:
public class Photo {
private String id;
private String owner;
private String secret;
private String server;
private String farm;
private String title;
private int isPublic;
private int isFriend;
private int isFamily;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public String getFarm() {
return farm;
}
public void setFarm(String farm) {
this.farm = farm;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getIsPublic() {
return isPublic;
}
public void setIsPublic(int isPublic) {
this.isPublic = isPublic;
}
public int getIsFriend() {
return isFriend;
}
public void setIsFriend(int isFriend) {
this.isFriend = isFriend;
}
public int getIsFamily() {
return isFamily;
}
public void setIsFamily(int isFamily) {
this.isFamily = isFamily;
}
}
Use Jackson. It'll take care of converting to and from JSON. It provides multiple ways of approaching conversion, and is well-integrated with frameworks like Spring. Definitely one to know.

Categories

Resources