Custom TiledDataSource with paging library - java

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.

Related

Realm Migration is not working in Android?

I am at present working on a android chat application like whatsapp but I stuck at a situation in where Realm Migration is issue. I am not knowing so much about realm but testing it for a successful offline chat application. I am not able to use more than one model in realm because it is saying about the migrator. I tried all the ways but my migrator is not working and I also not having idea that what statements I have to use after this (schema.) statement for migrate my model according to my situations.
Here is the Code for my Realm ChatList Model:-
public class RealmChatListModel extends RealmObject {
#Index
private String userID;
private String Username;
private String Descryption;
private String phoneNo;
private String lastMessage;
private String Date;
private String ImageURI;
private long lastMessageTime;
public RealmChatListModel() {
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getUsername() {
return Username;
}
public void setUsername(String username) {
Username = username;
}
public String getDescryption() {
return Descryption;
}
public void setDescryption(String descryption) {
Descryption = descryption;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getLastMessage() {
return lastMessage;
}
public void setLastMessage(String lastMessage) {
this.lastMessage = lastMessage;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
public String getImageURI() {
return ImageURI;
}
public void setImageURI(String imageURI) {
ImageURI = imageURI;
}
public long getLastMessageTime() {
return lastMessageTime;
}
public void setLastMessageTime(long lastMessageTime) {
this.lastMessageTime = lastMessageTime;
}
}
And here is my code for realm Chat Model :-
public class RealmChat extends RealmObject {
#PrimaryKey
#Index
private String messageKey;
private String time;
private String date;
private String textMessage;
private String type;
private String sender;
private String receiver;
private String uri;
private boolean isSeen;
private String duration;
private String receivername;
private String fileSize;
private boolean isNextDay;
private boolean isDeleted;
private Date extactdate;
private String repMesKey;
private String repMesUri;
private String repMesText;
private String repMesType;
private String repMesSender;
private long timestamp;
private String repMesSendPhone;
private boolean isReplied;
private String phoneNo;
private boolean isForwarded;
public String getMessageKey() {
return messageKey;
}
public void setMessageKey(String messageKey) {
this.messageKey = messageKey;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTextMessage() {
return textMessage;
}
public void setTextMessage(String textMessage) {
this.textMessage = textMessage;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public boolean isSeen() {
return isSeen;
}
public void setSeen(boolean seen) {
isSeen = seen;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getReceivername() {
return receivername;
}
public void setReceivername(String receivername) {
this.receivername = receivername;
}
public String getFileSize() {
return fileSize;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
public boolean isNextDay() {
return isNextDay;
}
public void setNextDay(boolean nextDay) {
isNextDay = nextDay;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean deleted) {
isDeleted = deleted;
}
public Date getExtactdate() {
return extactdate;
}
public void setExtactdate(Date extactdate) {
this.extactdate = extactdate;
}
public String getRepMesKey() {
return repMesKey;
}
public void setRepMesKey(String repMesKey) {
this.repMesKey = repMesKey;
}
public String getRepMesUri() {
return repMesUri;
}
public void setRepMesUri(String repMesUri) {
this.repMesUri = repMesUri;
}
public String getRepMesText() {
return repMesText;
}
public void setRepMesText(String repMesText) {
this.repMesText = repMesText;
}
public String getRepMesType() {
return repMesType;
}
public void setRepMesType(String repMesType) {
this.repMesType = repMesType;
}
public String getRepMesSender() {
return repMesSender;
}
public void setRepMesSender(String repMesSender) {
this.repMesSender = repMesSender;
}
public String getRepMesSendPhone() {
return repMesSendPhone;
}
public void setRepMesSendPhone(String repMesSendPhone) {
this.repMesSendPhone = repMesSendPhone;
}
public boolean isReplied() {
return isReplied;
}
public void setReplied(boolean replied) {
isReplied = replied;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public boolean isForwarded() {
return isForwarded;
}
public void setForwarded(boolean forwarded) {
isForwarded = forwarded;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
And Here is my code for my migrator :-
public class RealmMigration implements io.realm.RealmMigration {
#Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
RealmSchema schema = realm.getSchema();
// Migrate from version 0 to version 1
if (oldVersion == 0) {
schema.get("RealmChatListModel")
.addField("Username", String.class)
.addRealmListField("lastMessageTime", long.class);
oldVersion++;
}
if (oldVersion == 1) {
schema.get("RealmChat")
.addField("extactdate", Date.class)
.addRealmListField("timestamp",long.class);
}
}
public static RealmConfiguration getDefaultConfig() {
return new RealmConfiguration.Builder()
.schemaVersion(2)
.migration(new RealmMigration())
.build();
}
#Override
public int hashCode() { return RealmMigration.class.hashCode(); }
#Override
public boolean equals(Object object) { return object != null && object instanceof RealmMigration; }
}
Please Help me...................................................................................
<<<<<<<<<<<<<<<<------------------(~~~~~~~~~~~~~~~~~~~)------------------->>>>>>>>>>>>>>>>>>>>>
Yes I got it my migration is working only by a single change :-
#Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
RealmSchema schema = realm.getSchema();
// Migrate from version 0 to version 1
if (oldVersion == 0) {
schema.get("RealmChatListModel")
.addField("userID", String.class, FieldAttribute.REQUIRED);
oldVersion++;
}
}
Here I removed Realm Chat from migrating the old version because it is the last model and added in realmChatListSchema that userID field is required.Noting else reqired. I am happy 🥰 🥰 🥰 .

Realm query result always null

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
}

unique constraint Exception (SQLIntegrityConstraintViolationException)

I am trying to insert data in oracle DB using spring JPA repositories
I have a hash map which contains all the values which needs to be populated into DB,I am Iterating each value and setting into my Entity class
Basically I have a table which has a composite primary key(NotifiedToId).when I am setting the values ints throwing constraint violation exception.In my logs it is printing all correct values but its not getting inserted,
My Entity class:
#Embeddable
public class TbBamiNotifUserLogPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#Column(name="NOTIF_REF_NO")
private String notifRefNo;
#Column(name="NOTIFIED_TO_ID")
private String notifiedToId;
public TbBamiNotifUserLogPK() {
}
public String getNotifRefNo() {
return this.notifRefNo;
}
public void setNotifRefNo(String notifRefNo) {
this.notifRefNo = notifRefNo;
}
public String getNotifiedToId() {
return this.notifiedToId;
}
public void setNotifiedToId(String notifiedToId) {
this.notifiedToId = notifiedToId;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof TbBamiNotifUserLogPK)) {
return false;
}
TbBamiNotifUserLogPK castOther = (TbBamiNotifUserLogPK)other;
return
this.notifRefNo.equals(castOther.notifRefNo)
&& this.notifiedToId.equals(castOther.notifiedToId);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.notifRefNo.hashCode();
hash = hash * prime + this.notifiedToId.hashCode();
return hash;
}
}
import java.io.Serializable;
import javax.persistence.*;
#Entity
#Table(name="TB_BAMI_NOTIF_USER_LOG")
#NamedQuery(name="TbBamiNotifUserLog.findAll", query="SELECT t FROM TbBamiNotifUserLog t")
public class TbBamiNotifUserLog implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private TbBamiNotifUserLogPK id;
#Column(name="NOTIF_CAT")
private String notifCat;
#Column(name="NOTIFIED_TO_NAME")
private String notifiedToName;
#Column(name="NOTIFIED_TO_ROLE")
private String notifiedToRole;
public TbBamiNotifUserLog() {
}
public TbBamiNotifUserLogPK getId() {
return this.id;
}
public void setId(TbBamiNotifUserLogPK id) {
this.id = id;
}
public String getNotifCat() {
return this.notifCat;
}
public void setNotifCat(String notifCat) {
this.notifCat = notifCat;
}
public String getNotifiedToName() {
return this.notifiedToName;
}
public void setNotifiedToName(String notifiedToName) {
this.notifiedToName = notifiedToName;
}
public String getNotifiedToRole() {
return this.notifiedToRole;
}
public void setNotifiedToRole(String notifiedToRole) {
this.notifiedToRole = notifiedToRole;
}
}
#Entity
#Table(name="TB_BAMI_NOTIFICATION_LOG")
#NamedQuery(name="TbBamiNotificationLog.findAll", query="SELECT t FROM TbBamiNotificationLog t")
public class TbBamiNotificationLog implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="NOTIF_REF_NO")
private String notifRefNo;
#Column(name="\"ACTION\"")
private String action;
#Column(name="NOTIF_CONTENT")
private String notifContent;
#Column(name="NOTIF_TYPE")
private String notifType;
#Column(name="NOTIFIED_DATE_TIME")
private Timestamp notifiedDateTime;
private String refno;
#Column(name="\"VERSION\"")
private BigDecimal version;
public TbBamiNotificationLog() {
}
public String getNotifRefNo() {
return this.notifRefNo;
}
public void setNotifRefNo(String notifRefNo) {
this.notifRefNo = notifRefNo;
}
public String getAction() {
return this.action;
}
public void setAction(String action) {
this.action = action;
}
public String getNotifContent() {
return this.notifContent;
}
public void setNotifContent(String notifContent) {
this.notifContent = notifContent;
}
public String getNotifType() {
return this.notifType;
}
public void setNotifType(String notifType) {
this.notifType = notifType;
}
public Timestamp getNotifiedDateTime() {
return this.notifiedDateTime;
}
public void setNotifiedDateTime(Timestamp notifiedDateTime) {
this.notifiedDateTime = notifiedDateTime;
}
public String getRefno() {
return this.refno;
}
public void setRefno(String refno) {
this.refno = refno;
}
public BigDecimal getVersion() {
return this.version;
}
public void setVersion(BigDecimal version) {
this.version = version;
}
}
Business Logic:
for (Entry<String, PushNotificationDetails> entry : finalTemplate.entrySet()){
try{
notificationlog.setNotifRefNo("121323");
notificationlog.setRefno(refNum);
notificationlog.setVersion(new BigDecimal(1));
notificationlog.setAction(action);
LOGGER.debug("TEMPLATE TYPE"+entry.getValue().getTemplate_type());
LOGGER.debug("TEMPLATE"+entry.getValue().getTemplate());
notificationlog.setNotifType(entry.getValue().getTemplate_type());
notificationlog.setNotifContent(entry.getValue().getTemplate());
notificationlog.setNotifiedDateTime(notifiedDateTime);
tbBamiNotifyLogRepository.save(notificationlog);
LOGGER.debug("inside if block ::: ");
LOGGER.debug("USERID is: "+entry.getValue().getUserID());
LOGGER.debug("NOTIFCAT is: "+entry.getValue().getNotif_cat());
LOGGER.debug("NOTIFUSER is: "+entry.getValue().getUserName());
LOGGER.debug("NOTIFROLE is: "+entry.getKey());
tbBamiNotifUserLogPK.setNotifiedToId(entry.getValue().getUserID());
tbBamiNotifUserLogPK.setNotifRefNo("121323");
tbBamiNotifUserLog.setId(tbBamiNotifUserLogPK);
LOGGER.debug("GET is: "+tbBamiNotifUserLog.getId().getNotifiedToId());
tbBamiNotifUserLog.setNotifCat(entry.getValue().getNotif_cat());
tbBamiNotifUserLog.setNotifiedToName(entry.getValue().getUserName());
tbBamiNotifUserLog.setNotifiedToRole(entry.getKey());
tbBamiNotifyUserLogRepository.save(tbBamiNotifUserLog);
}
Try to add notificationlog = new TbBamiNotificationLog() in the beginning of your saving for. It could be possible when you try to save the second row but the instance is the same (with id provided during the first save).

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.

How to pass array of string in insert query in ibatis?

How to pass array of string in insert query statement in ibatis. On passing string array as parameter it is giving me this exception of ibatis -
Can't infer the SQL type to use for an instance of [Ljava.lang.String;. Use setObject() with an explicit Types value to specify the type to use.
How to solve this error ?
My method is -
public void insertCampaignData(String campaignData, ObjectMapper jsonObjMapper) {
Campaign campaign = null;
SqlSession session = null;
IfrmCreateCampaign createCampaign = null;
try {
campaign = jsonObjMapper.readValue(campaignData,Campaign.class);
session = DBConnectionFactory.getNewSession();
createCampaign = session.getMapper(IfrmCreateCampaign.class);
createCampaign.insertCampaignData(campaign);
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
My entity class is -
import java.io.File;
import java.util.Date;
public class Campaign {
private long campaignId;
private String campaignName;
private long keywordId;
private String brandName;
private String clientName;
private String mobileNum;
private Date startTime;
private Date endTime;
private double campaignBudget;
private double allocatedFund;
private double campaignRate;
private boolean basicTgt;
private boolean customTgt;
private boolean advTgt;
private boolean chechme;
private boolean couponSend;
private String couponFrom;
private String couponTo;
private String couponFilePath;
private File[] couponFile;
private String[] couponFileFileName;
private String[] couponFileContent;
private String callbackUrl;
private String status;
private int campaignTypeId;
private long roAmount;
// edit
private int roType;
public int getRoType() {
return roType;
}
public void setRoType(int roType) {
this.roType = roType;
}
// edit
private String strStartTime;
private String strEndTime;
private String keyword;
private String keywordNum;
private int goal;
private double spentAmount;
private int goalAchievePercent;
private int dial;
private int uniqueDial;
private long userId;
private double campaignTotalAmount;
private double operatorShare;
private long responseCount;
private String strRoPdfFileName;
private File[] roPdf;
private String[] roPdfFileName;
private String[] roPdfContent;
public long getCampaignId() {
return campaignId;
}
public void setCampaignId(long campaignId) {
this.campaignId = campaignId;
}
public String getCampaignName() {
return campaignName;
}
public void setCampaignName(String campaignName) {
this.campaignName = campaignName;
}
public long getKeywordId() {
return keywordId;
}
public void setKeywordId(long keywordId) {
this.keywordId = keywordId;
}
public String getKeywordNum() {
return keywordNum;
}
public void setKeywordNum(String keywordNum) {
this.keywordNum = keywordNum;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getMobileNum() {
return mobileNum;
}
public void setMobileNum(String mobileNum) {
this.mobileNum = mobileNum;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public double getCampaignBudget() {
return campaignBudget;
}
public void setCampaignBudget(double campaignBudget) {
this.campaignBudget = campaignBudget;
}
public double getAllocatedFund() {
return allocatedFund;
}
public void setAllocatedFund(double allocatedFund) {
this.allocatedFund = allocatedFund;
}
public double getCampaignRate() {
return campaignRate;
}
public void setCampaignRate(double campaignRate) {
this.campaignRate = campaignRate;
}
public boolean isBasicTgt() {
return basicTgt;
}
public void setBasicTgt(boolean basicTgt) {
this.basicTgt = basicTgt;
}
public boolean isCustomTgt() {
return customTgt;
}
public void setCustomTgt(boolean customTgt) {
this.customTgt = customTgt;
}
public boolean isAdvTgt() {
return advTgt;
}
public void setAdvTgt(boolean advTgt) {
this.advTgt = advTgt;
}
public boolean isChechme() {
return chechme;
}
public void setChechme(boolean chechme) {
this.chechme = chechme;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getStrStartTime() {
return strStartTime;
}
public void setStrStartTime(String strStartTime) {
this.strStartTime = strStartTime;
}
public String getStrEndTime() {
return strEndTime;
}
public void setStrEndTime(String strEndTime) {
this.strEndTime = strEndTime;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public int getGoal() {
return goal;
}
public void setGoal(int goal) {
this.goal = goal;
}
public double getSpentAmount() {
return spentAmount;
}
public void setSpentAmount(double spentAmount) {
this.spentAmount = spentAmount;
}
public int getGoalAchievePercent() {
return goalAchievePercent;
}
public void setGoalAchievePercent(int goalAchievePercent) {
this.goalAchievePercent = goalAchievePercent;
}
public int getDial() {
return dial;
}
public void setDial(int dial) {
this.dial = dial;
}
public int getUniqueDial() {
return uniqueDial;
}
public void setUniqueDial(int uniqueDial) {
this.uniqueDial = uniqueDial;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public boolean isCouponSend() {
return couponSend;
}
public void setCouponSend(boolean couponSend) {
this.couponSend = couponSend;
}
public String getCouponFrom() {
return couponFrom;
}
public void setCouponFrom(String couponFrom) {
this.couponFrom = couponFrom;
}
public String getCouponTo() {
return couponTo;
}
public void setCouponTo(String couponTo) {
this.couponTo = couponTo;
}
public String getCouponFilePath() {
return couponFilePath;
}
public void setCouponFilePath(String couponFilePath) {
this.couponFilePath = couponFilePath;
}
public File[] getCouponFile() {
return couponFile;
}
public void setCouponFile(File[] couponFile) {
this.couponFile = couponFile;
}
public String[] getCouponFileFileName() {
return couponFileFileName;
}
public void setCouponFileFileName(String[] couponFileFileName) {
this.couponFileFileName = couponFileFileName;
}
public String[] getCouponFileContent() {
return couponFileContent;
}
public void setCouponFileContent(String[] couponFileContent) {
this.couponFileContent = couponFileContent;
}
public String getCallbackUrl() {
return callbackUrl;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
public int getCampaignTypeId() {
return campaignTypeId;
}
public void setCampaignTypeId(int campaignTypeId) {
this.campaignTypeId = campaignTypeId;
}
public long getRoAmount() {
return roAmount;
}
public void setRoAmount(long roAmount) {
this.roAmount = roAmount;
}
public double getOperatorShare() {
return operatorShare;
}
public void setOperatorShare(double operatorShare) {
this.operatorShare = operatorShare;
}
public long getResponseCount() {
return responseCount;
}
public void setResponseCount(long responseCount) {
this.responseCount = responseCount;
}
public double getCampaignTotalAmount() {
return campaignTotalAmount;
}
public void setCampaignTotalAmount(double campaignTotalAmount) {
this.campaignTotalAmount = campaignTotalAmount;
}
public String getStrRoPdfFileName() {
return strRoPdfFileName;
}
public void setStrRoPdfFileName(String strRoPdfFileName) {
this.strRoPdfFileName = strRoPdfFileName;
}
public File[] getRoPdf() {
return roPdf;
}
public void setRoPdf(File[] roPdf) {
this.roPdf = roPdf;
}
public String[] getRoPdfFileName() {
return roPdfFileName;
}
public void setRoPdfFileName(String[] roPdfFileName) {
this.roPdfFileName = roPdfFileName;
}
public String[] getRoPdfContent() {
return roPdfContent;
}
public void setRoPdfContent(String[] roPdfContent) {
this.roPdfContent = roPdfContent;
}
}
My xml mapping file is -
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mogae.starStarWebServices.db.dao.IfrmCreateCampaign">
<insert id="insertCampaignData" statementType="PREPARED" >
insert into campaign(campaign_id,campaign_name,keyword_id,brand_name,client_name,mobile_num,start_time,end_time,campaign_type_id,ro_amount,ro_type,ro_pdf_file_name,campaign_budget,allocated_fund,campaign_rate,is_basic_tgt,is_custom_tgt,is_adv_tgt,is_checkme,is_coupon_send,coupon_from,coupon_to,coupon_file,callback_url,status) values (#{campaignId},#{campaignName},#{keywordId},#{brandName},#{clientName},#{mobileNum},#{startTime},#{endTime},#{campaignTypeId},#{roAmount},#{roType},
#{strRoPdfFileName},#{campaignBudget},#{allocatedFund},#{campaignRate},#{basicTgt},#{customTgt},#{advTgt},#{chechme},#{couponSend},#{couponFrom},#{couponTo},#{couponFileFileName},#{callbackUrl},#{status});
</insert>
<insert id="insertKeywordData" statementType="PREPARED" >
insert into keywords(keyword_id,keyword,keyword_num,booked_by,purchased_on,expires_on,status) values (#{keywordId},#{keyword},#{keywordNum},#{bookedBy},#{purchasedOn},#{expiresOn},#{status})
</insert>
</mapper>

Categories

Resources