update query not working? - java

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 ?

Related

Room error - "Cannot figure out how to save this field into database. You can consider adding a type converter for it."

I want to store class Reservation that a user makes when going to a cinema to watch a movie and I can't figure out how to convert it so that room can store it in the data base.
Errors appear for members: places and codeQR.
Class Reservation:
#Entity(tableName = "reservations", foreignKeys = #ForeignKey(entity = UtilizatorMADA.class, parentColumns = "id", childColumns = "idUser"))
public class Reservation implements Serializable {
#PrimaryKey(autoGenerate = true)
private long idReservation;
private long idUser;
#Embedded private Film film;
private Time startTime;
private List<Integer> places;
private Bitmap codeQR;
#Ignore
public Reservation(){}
public Reservation(long idReservation, long idUser, Film film, Time startTime, List<Integer> places, Bitmap codeQR) {
this.idReservation = idReservation;
this.idUser = idUser;
this.film = film;
this.startTime = startTime;
this.places = places;
this.codeQR = codeQR;
}
#Ignore
public Reservation(long idUser, Film film, Time startTime, List<Integer> places, Bitmap codeQR) {
this.idUser = idUser;
this.film = film;
this.startTime = startTime;
this.places = places;
this.codeQR = codeQR;
}
#Ignore
public Reservation(Film film, Time startTime, List<Integer> places, Bitmap codeQR) {
this.film = film;
this.startTime = startTime;
this.places = places;
this.codeQR = codeQR;
}
public long getIdReservation() {
return idReservation;
}
public void setIdReservation(long idReservation) {
this.idReservation = idReservation;
}
public long getIdUser() {
return idUser;
}
public void setIdUser(long idUser) {
this.idUser = idUser;
}
public void setPlaces(List<Integer> places) {
this.places = places;
}
public Film getFilm() {
return film;
}
public void setFilm(Film film) {
this.film = film;
}
public Time getStartTime() {
return startTime;
}
public void setStartTime(Time startTime) {
this.startTime = startTime;
}
public Bitmap getCodeQR() {
return codeQR;
}
public void setCodeQR(Bitmap codeQR) {
this.codeQR = codeQR;
}
public List<Integer> getPlaces() { return places; }
#Override
public String toString() {
return "Reservation{" +
"film=" + film +
", startTime=" + startTime +
", codeQR='" + codeQR + '\'' +
'}';
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Reservation that = (Reservation) o;
return Objects.equals(film, that.film) &&
Objects.equals(startTime, that.startTime) &&
Objects.equals(places, that.places);
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public int hashCode() {
return Objects.hash(film, startTime, places);
}
}
Class Film:
#Entity(tableName = "films")
public class Film implements Serializable {
#PrimaryKey(autoGenerate = true)
private int idFilm;
private String title;
private String genre;
private String description;
private double rating;
private int imagePath;
private boolean isFavorite;
public Film(int idFilm, String title, String genre, String description, double rating, int imagePath, boolean isFavorite) {
this.idFilm = idFilm;
this.title = title;
this.genre = genre;
this.description = description;
this.rating = rating;
this.imagePath = imagePath;
this.isFavorite = isFavorite;
}
#Ignore
public Film(String title, String genre, String description, double rating, int imagePath) {
this.title = title;
this.genre = genre;
this.description = description;
this.rating = rating;
this.imagePath = imagePath;
isFavorite = false;
}
#Ignore
public Film(String title) {
this.title = title;
}
public int getIdFilm() {
return idFilm;
}
public void setIdFilm(int idFilm) {
this.idFilm = idFilm;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
public int getImagePath() {
return imagePath;
}
public void setImagePath(int imagePath) {
this.imagePath = imagePath;
}
public boolean isFavorite() {
return isFavorite;
}
public void setFavorite(boolean favorite) {
isFavorite = favorite;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Film film = (Film) o;
return Objects.equals(title, film.title);
}
#Override
public int hashCode() {
return Objects.hash(title);
}
}
I also get the following error by the ReservationOfMoviesDao, which may or may not be related. The queries affected are: getReservationOfMoviesByUserId(long id), getReservationOfMovies() and getReservationOfMoviesByRservationId(long id);
error: The columns returned by the query does not have the fields [idFilm] in com.example.cinemaapp.model.ReservationMovie even though they are annotated as non-null or primitive. Columns returned by the query: [idReservation,idUser,film,startTime,places,codeQR]
Interface ReservationOfMoviesDao:
#Dao
public interface ReservationOfMoviesDao {
#Insert(onConflict = OnConflictStrategy.IGNORE)
void insert(ReservationMovie rm);
#Transaction
#Query("SELECT * FROM reservations where idUser = :id")
List<ReservationMovie> getReservationOfMoviesByUserId(long id);
#Transaction
#Query("SELECT * FROM reservations")
List<ReservationMovie> getReservationOfMovies();
#Transaction
#Query("SELECT * FROM reservations where idReservation = :id")
ReservationMovie getReservationOfMoviesByReservationId(long id);
}
If you could help me out please, I'd appreciate it.
You cant use entities inside other entities (e.g. Film in Reservation). You should either use "relationships between entities" or try "Embedded" annotation.
Reffer to this link for more info.

How to use multiple generic type for a tableview?

I'm making an application with JavaFX for an University Project to manage data in a mysql database and a List. I have to display data into a tableview. But a Table View allow only one POJO Class. How can I make join between two POJO Class? (like SQL Join function)
I tried to make a buffer class, but I don't understand how to do that and how to use it.
Controller class:
public class RevuesController implements Initializable, ChangeListener<Revue> {
---
#FXML private TableView<Revue> revuesTable;
#FXML private TableColumn<Revue, String> titleCol = new TableColumn<>("Titre");
#FXML private TableColumn<Revue, String> descCol = new TableColumn<>("Description");
#FXML private TableColumn<Revue, Double> priceCol = new TableColumn<>("Tarif numéro");
#FXML private TableColumn<Revue, String> visualCol = new TableColumn<>("Visuel");
#FXML private TableColumn<Periodicite, String> periodCol = new TableColumn<>("Périodicité");
#FXML private TableColumn<Integer, String> aboCol = new TableColumn<>("Abonnements en cours");
------
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
ObservableList<Revue> oListRevue = FXCollections.observableArrayList();
try {
oListRevue = FXCollections.observableArrayList(daos.getRevueDAO().getAll());
} catch (Exception e) {
System.out.println("Erreur de récupération des données de revue : " + e.getMessage());
e.printStackTrace();
}
this.titleCol.setCellValueFactory(new PropertyValueFactory<Revue, String>("titre"));
this.descCol.setCellValueFactory(new PropertyValueFactory<Revue, String>("description"));
this.priceCol.setCellValueFactory(new PropertyValueFactory<Revue, Double>("tarif_numero"));
this.visualCol.setCellValueFactory(new PropertyValueFactory<Revue, String>("visuel"));
this.periodCol.setCellValueFactory(new PropertyValueFactory<Periodicite, String>("libelle"));
this.aboCol.setCellValueFactory(new PropertyValueFactory<Integer, Integer>(""));
this.revuesTable.getColumns().setAll(titleCol, descCol, priceCol, visualCol, periodCol, aboCol);
FilteredList<Revue> fListRevue = new FilteredList<>(oListRevue);
this.revuesTable.getItems().addAll(fListRevue);
}
POJO Class Revue:
public class Revue {
private int id_revue;
private String titre;
private String description;
private double tarif_numero;
private String visuel;
private int id_periodicite;
public Revue() {}
public Revue(String titre, String description, double tarif_numero, String visuel, int id_periodicite) {
this.id_revue = -1;
this.titre = titre;
this.description = description;
this.tarif_numero = tarif_numero;
this.visuel = visuel;
this.id_periodicite = id_periodicite;
}
public Revue(int id_revue, String titre, String description, double tarif_numero, String visuel, int id_periodicite) {
this.id_revue = id_revue;
this.titre = titre;
this.description = description;
this.tarif_numero = tarif_numero;
this.visuel = visuel;
this.id_periodicite = id_periodicite;
}
public int getId_revue() {
return id_revue;
}
public void setId_revue(int id_revue) {
this.id_revue = id_revue;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getTarif_numero() {
return tarif_numero;
}
public void setTarif_numero(double tarif_numero) {
this.tarif_numero = tarif_numero;
}
public String getVisuel() {
return visuel;
}
public void setVisuel(String visuel) {
this.visuel = visuel;
}
public int getId_periodicite() {
return id_periodicite;
}
public void setId_periodicite(int id_periodicite) {
this.id_periodicite = id_periodicite;
}
POJO Class Periodicite:
public class Periodicite {
private int id;
private String libelle;
public Periodicite(int id, String libelle) {
this.id = id;
this.libelle = libelle;
}
public Periodicite(String libelle) {
this.id = -1;
this.libelle = libelle;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}

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
}

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