Example data within a class - Good or bad practise? - java

Is it a good idea to write example data within a class which can be instantiated?
In the following example, i am using some static var's which are used to get direct access to some Contacts via:
Contact.contact101()
...
I am using this example data definition within a test and don't want to write a kind of util class which contains all the example data.
package com.example.webdriver.util.builder.model;
import com.google.gson.annotations.SerializedName;
import com.example.webdriver.util.builder.LocalStorageBuilder;
import com.example.webdriver.util.builder.enumaration.UserStatus;
public class Contact {
#SerializedName("ID")
private Long id;
#SerializedName("puid")
private Long principleUserId;
#SerializedName("cuid")
private Long contactUserId;
#SerializedName("v")
private int visible;
#SerializedName("ustat")
private String userStatus;
#SerializedName("ats")
private Long addedTimeStamp;
private static Contact contact101;
private static Contact contact102;
private static Contact contact305;
private static Contact contact302;
private static Contact contact301;
private static Contact contact382;
public Contact() {
this.id = LocalStorageBuilder.getContactIdCounter();
this.principleUserId = LocalStorageBuilder.principalUserId;
this.contactUserId = 301L;
this.visible = 1;
this.userStatus = String.valueOf(UserStatus.ONLINE.getUserStatus());
this.addedTimeStamp = 1410168552386L;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPrincipleUserId() {
return principleUserId;
}
public void setPrincipleUserId(Long principleUserId) {
this.principleUserId = principleUserId;
}
public int getVisible() {
return visible;
}
public void setVisible(boolean visible) {
if (visible) {
this.visible = 1;
} else {
this.visible = 0;
}
}
public String getUserStatus() {
return userStatus;
}
public void setUserStatus(UserStatus userStatus) {
this.userStatus = String.valueOf(userStatus.getUserStatus());
}
public Long getAddedTimeStamp() {
return addedTimeStamp;
}
public void setAddedTimeStamp(Long addedTimeStamp) {
this.addedTimeStamp = addedTimeStamp;
}
public Long getContactUserId() {
return contactUserId;
}
public void setContactUserId(Long contactUserId) {
this.contactUserId = contactUserId;
}
// Example data
public static Contact contact102() {
if (contact102 == null) {
contact102 = createContact(102L);
}
contact102.setPrincipleUserId(LocalStorageBuilder.principalUserId);
return contact102;
}
public static Contact contact302() {
if (contact302 == null) {
contact302 = createContact(302L);
}
contact302.setPrincipleUserId(LocalStorageBuilder.principalUserId);
return contact302;
}
public static Contact contact305() {
if (contact305 == null) {
contact305 = createContact(305L);
}
contact305.setPrincipleUserId(LocalStorageBuilder.principalUserId);
return contactAVG305;
}
private static Contact createContact(Long contactUserId) {
Contact contact = new Contact();
contact.setContactUserId(contactUserId);
contact.setPrincipleUserId(LocalStorageBuilder.principalUserId);
contact.setUserStatus(UserStatus.ONLINE);
contact.setAddedTimeStamp(1410168552386L);
contact.setVisible(true);
return contact;
}
}

No, use some kind of factory instead.
There are various terms around the internet, ObjectMother is one, although I prefer TestDataFactory.
public class TestDataFactory {
private static Contact createContact(Long contactUserId) {
Contact contact = new Contact();
contact.setContactUserId(contactUserId);
contact.setPrincipleUserId(LocalStorageBuilder.principalUserId);
contact.setUserStatus(UserStatus.ONLINE);
contact.setAddedTimeStamp(1410168552386L);
contact.setVisible(true);
return contact;
}
}
The advantage is that this can live in your test sources, not poluting your domain objects with test code.

This makes re factoring tough and as per class definition, this is not valid here.
The correct place is to create another class named TestDataHelper and create a method named getContacts and return list of Contact objects.
Concerns should always be separated. This is how Java works !

Related

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.

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).

How to sort object array in Java [duplicate]

This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 6 years ago.
I have an object List with the name of cars and in this list I have some vehicle object. all objects values are different to each other. In all object here is custom field with the name of unit and in unit is another field with the name of unitType ... which is "T20" , "VT11" or any other ..
I want to sort this cars List according to unitType like:
if cars(0).getUnit().getUnitType().equals("T20") sort all the value first then other "VT11" and then all other...
How can I do this?? Is any suitable method in java?
my Unit class:
package com.vehicletracking.vtss.classes.bean;
import java.io.*;
public class Unit implements Serializable{
private int code;
private int unitId;
private String unitType; //X8, X1, X1+, VT10, VT200, SPT100
private Sim sim;
private String commType; //CSD, SMS, GPRS, AUTO
private int modemCode;
private long IMEI;
private String serialNo;
private InputReportProfile inputReportProfile;
private String firmware;
private String packageName;
private String password;
public Unit() {
}
public Unit(int unitId) {
this.unitId = unitId;
}
public Unit(int unitId, String unitType) {
this.unitId = unitId;
this.unitType = unitType;
}
public Unit(int unitId, String unitType, Sim sim) {
this.unitId = unitId;
this.unitType = unitType;
this.sim = sim;
}
public void setUnitId(int unitId) {
this.unitId = unitId;
}
public int getUnitId() {
return this.unitId;
}
public void setUnitType(String unitType) {
this.unitType = unitType;
}
public String getUnitType() {
return this.unitType;
}
public void setSim(Sim sim) {
this.sim = sim;
}
public void setCommType(String commType) {
this.commType = commType;
}
public void setModemCode(int modemCode) {
this.modemCode = modemCode;
}
public void setSerialNo(String serialNo) {
this.serialNo = serialNo;
}
public void setCode(int code) {
this.code = code;
}
public void setInputReportProfile(InputReportProfile inputReportProfile) {
this.inputReportProfile = inputReportProfile;
}
public void setPassword(String password) {
this.password = password;
}
public void setIMEI(long IMEI) {
this.IMEI = IMEI;
}
public Sim getSim() {
return this.sim;
}
public String getCommType() {
return commType;
}
public int getModemCode() {
return modemCode;
}
public String getSerialNo() {
return serialNo;
}
public int getCode() {
return code;
}
public InputReportProfile getInputReportProfile() {
return inputReportProfile;
}
public String getPassword() {
return password;
}
public long getIMEI() {
return IMEI;
}
public int hashCode() {
return unitId;
}
public boolean equals(Object obj) {
if (obj instanceof Unit) {
return this.unitId == ((Unit) obj).getUnitId();
}
return false;
}
public String toString() {
return this.unitId + "/" + this.unitType;
}
public String getFirmware() {
return firmware;
}
public void setFirmware(String firmware) {
this.firmware= firmware;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
}
Car List:
List cars;
From Java 8 Documentation for Comparable:
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.
Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.
According to above, you just have to implement Comparable, and provide an implementation for compareTo for your object. Collections.sort takes care of the rest.

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 write a static class that has an id with a string in it

I want to write a static class customer ID that begins with C1000, and for each new customer object created it will add +1, C1001, C1002, C1003, and so on. How is it done if there is a string?
public class Customer
{
private static int customerID = 1000;
public Customer()
{
customerID++;
}
public static int getcutomerID()
{
return customerID;
}
}
public class Customer {
private static int NextCustomerId = 1000;
private final int myCustomerId;
public Customer() {
myCustomerId = NextCustomerId++;
...
}
public String getCustomerId() {
return "C" + myCustomerId;
}
}
Note that this probably isn't threadsafe. If you need it to be, look at java.util.concurrent.atomic.AtomicInteger and use one of those for NextCustomerId.
public class Customer {
private static int customerID = 1000;
// wth would you do this?! static state is evil!
public Customer() { customerID++; }
public String getCurrentCustomerID() { return "C" + customerID; }
}
Static state is very bad for testing. It amounts to global variables. Perhaps a better design is:
public class Customer {
private final int id;
public Customer(final int id) { this.id = id; }
public int getId() { return id; }
}
public class CustomerDatabase {
private int nextId;
public CustomerDatabase() { this(0); }
public CustomerDatabase(int nextId) { this.nextId = nextId; }
public synchronized int nextId() { return nextId++; }
// define useful operations for a CustomerDatabase
}
// maybe you could use the database and customer classes as follows
public class CustomerApplication {
public static void main(String[] args) {
// first argument is highest customer id
CustomerDatabase db = new CustomerDatabase(Integer.parseInt(args[0]));
Customer c = new Customer(db.nextId());
db.add(c);
System.out.println(db.getCustomers());
db.save("customers.txt");
Customer x = db.findById(13);
if(x.isBroke()) db.delete(x);
System.out.println("K thx, bai");
}
}
Don't do that. Use an int with String.format().

Categories

Resources