Comparing two Lists in java - java

In an application we have a Boarding table having ( boarding_id + invoice_no + item_id ) as key. A Boarding_tmp table with same table structure as Boarding. We are loading Boarding_tmp from a csv file (pipe separator column values)
We have a Boarding java bean with all columns. Let's say we have two list -
1. boardingList with all active records in Boarding table
2. boardingTmpList with all records in Boarding_Tmp table
I need to compare these two list to implement below scenario -
We Need to compare Boarding table with Boarding_tmp table and need to do following (No SQL joins. We have to perform this on object level) -
a. All records which are in Boarding_tmp but not in Boarding table should be inserted in Boarding table (means they are new records)
b. All records which are in Boarding but not in Boarding_tmp table should be mark as deactivated in Boarding table (we have a active column in Boarding table)
Here in Boarding.java -
public class Boarding implements Comparable {
private String bordingId;
private String itemId;
private String invoiceNo;
private String itemName;
private long qty;
private double price;
/**
* #return the bordingId
*/
public String getBordingId() {
return bordingId;
}
/**
* #param bordingId
* the bordingId to set
*/
public void setBordingId(String bordingId) {
this.bordingId = bordingId;
}
/**
* #return the itemId
*/
public String getItemId() {
return itemId;
}
/**
* #param itemId
* the itemId to set
*/
public void setItemId(String itemId) {
this.itemId = itemId;
}
/**
* #return the invoiceNo
*/
public String getInvoiceNo() {
return invoiceNo;
}
/**
* #param invoiceNo
* the invoiceNo to set
*/
public void setInvoiceNo(String invoiceNo) {
this.invoiceNo = invoiceNo;
}
/**
* #return the itemName
*/
public String getItemName() {
return itemName;
}
/**
* #param itemName
* the itemName to set
*/
public void setItemName(String itemName) {
this.itemName = itemName;
}
/**
* #return the qty
*/
public long getQty() {
return qty;
}
/**
* #param qty
* the qty to set
*/
public void setQty(long qty) {
this.qty = qty;
}
/**
* #return the price
*/
public double getPrice() {
return price;
}
/**
* #param price
* the price to set
*/
public void setPrice(double price) {
this.price = price;
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((bordingId == null) ? 0 : bordingId.hashCode());
result = prime * result
+ ((invoiceNo == null) ? 0 : invoiceNo.hashCode());
result = prime * result + ((itemId == null) ? 0 : itemId.hashCode());
return result;
}
#Override
public int compareTo(Object o) {
if (this == o) {
return 0;
}
if (o == null) {
return 1;
}
if (getClass() != o.getClass()) {
return 1;
}
Boarding other = (Boarding) o;
if (bordingId == null) {
if (other.bordingId != null) {
return 1;
}
} else if (!bordingId.equals(other.bordingId)) {
return 1;
}
if (invoiceNo == null) {
if (other.invoiceNo != null) {
return 1;
}
} else if (!invoiceNo.equals(other.invoiceNo)) {
return 1;
}
if (itemId == null) {
if (other.itemId != null) {
return 1;
}
} else if (!itemId.equals(other.itemId)) {
return 1;
}
return 0;
}
}
Please help. Thanks.

You can try Collections Util library. They have very useful methods for the scenario you depicted.

That's easily achivable with use of List#retainAll method.
javadoc is here

You should be able to do the following:
List<Boarding> insertBoarding = new ArrayList(boardingTmpList);
insertBoarding.removeAll(boardingList);
// insert all elements in insertBoarding to the table
List<Boarding> deactivateBoarding = new ArrayList(boardingList);
deactivateBoarding.removeAll(boardingTmpList);
// deactivate all elements in deactivateBoarding in the table
Assuming your equality tests work, this should yield correct results.
NOTE: You will have to override the equals method for this to work properly.

Related

Spring Mongodb pagination of nested collection field

I have a collection of document inside another document. Would like to implement pagination on nested element while fetching the data. Could you please let me know how to do that? In the structure I would like to fetch messages using pagination.
public abstract class CommonDomainAttributes implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
#Id
protected String id;
#JsonIgnore
#CreatedDate
protected Date createDate;
//#JsonIgnore
#LastModifiedDate
//#JsonSerialize(using=JsonDateSerializer.class)
protected Date lastModifiedDate;
#JsonIgnore
#CreatedBy
protected String createdBy;
#JsonIgnore
#LastModifiedBy
protected String lastModifiedBy;
/**
* #return the id
*/
public String getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* #return the createDate
*/
public Date getCreateDate() {
return createDate;
}
/**
* #param createDate the createDate to set
*/
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
/**
* #return the lastModifiedDate
*/
public Date getLastModifiedDate() {
return lastModifiedDate;
}
/**
* #param lastModifiedDate the lastModifiedDate to set
*/
public void setLastModifiedDate(Date lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
/**
* #return the createdBy
*/
public String getCreatedBy() {
return createdBy;
}
/**
* #param createdBy the createdBy to set
*/
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
/**
* #return the lastModifiedBy
*/
public String getLastModifiedBy() {
return lastModifiedBy;
}
/**
* #param lastModifiedBy the lastModifiedBy to set
*/
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
/* (non-Javadoc)
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (id == null ? 0 : id.hashCode());
return result;
}
/* (non-Javadoc)
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
CommonDomainAttributes other = (CommonDomainAttributes) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CommonDomainAttributes [id=").append(id)
.append(", createDate=").append(createDate)
.append(", lastModifiedDate=").append(lastModifiedDate)
.append(", createdBy=").append(createdBy)
.append(", lastModifiedBy=").append(lastModifiedBy)
.append(", toString()=").append(super.toString()).append("]");
return builder.toString();
}
}
public class Message extends CommonDomainAttributes implements Serializable{
private String fromuserId;
private String fromuserName;
private String toUserId;
private String touserName;
private String message;
/**
* #return the fromuserId
*/
public String getFromuserId() {
return fromuserId;
}
/**
* #param fromuserId the fromuserId to set
*/
public void setFromuserId(String fromuserId) {
this.fromuserId = fromuserId;
}
/**
* #return the fromuserName
*/
public String getFromuserName() {
return fromuserName;
}
/**
* #param fromuserName the fromuserName to set
*/
public void setFromuserName(String fromuserName) {
this.fromuserName = fromuserName;
}
/**
* #return the toUserId
*/
public String getToUserId() {
return toUserId;
}
/**
* #param toUserId the toUserId to set
*/
public void setToUserId(String toUserId) {
this.toUserId = toUserId;
}
/**
* #return the touserName
*/
public String getTouserName() {
return touserName;
}
/**
* #param touserName the touserName to set
*/
public void setTouserName(String touserName) {
this.touserName = touserName;
}
/**
* #return the message
*/
public String getMessage() {
return message;
}
/**
* #param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Message [fromuserId=");
builder.append(fromuserId);
builder.append(", fromuserName=");
builder.append(fromuserName);
builder.append(", toUserId=");
builder.append(toUserId);
builder.append(", touserName=");
builder.append(touserName);
builder.append(", message=");
builder.append(message);
builder.append(", toString()=");
builder.append(super.toString());
builder.append("]");
return builder.toString();
}
}
#Document(collection="discussion")
#TypeAlias("discussion")
public class Discussion extends CommonDomainAttributes implements Serializable{
private String discussionTopic;
private List<Message> messages;
/**
* #return the discussionTopic
*/
public String getDiscussionTopic() {
return discussionTopic;
}
/**
* #param discussionTopic the discussionTopic to set
*/
public void setDiscussionTopic(String discussionTopic) {
this.discussionTopic = discussionTopic;
}
/**
* #return the messages
*/
public List<Message> getMessages() {
return messages;
}
/**
* #param messages the messages to set
*/
public void setMessages(List<Message> messages) {
this.messages = messages;
}
/**
* #param messages the messages to set
*/
public void addMessages(Message message) {
if(null == messages){
messages = new LinkedList<>();
}
messages.add(message);
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Discussion [discussionTopic=");
builder.append(discussionTopic);
builder.append(", messages=");
builder.append(messages);
builder.append(", toString()=");
builder.append(super.toString());
builder.append("]");
return builder.toString();
}
}
A bit on Mongo Query Language
In MongoDB, the $slice operator controls the number of items of an array that a query returns. The $slice operator can accept values with following syntax:
[toSkip, toLimit]
Where the first value indicates the number of items in the array to skip and the second value indicates the number of items to return. For example, you can use the following query:
db.discussions.find({}, {messages: {$slice: [20, 10]}})
To return 10 messages, after skipping the first 20 messages of that array.
Bring it to Spring Data World
In order to use $slice operator with Spring Data MongoDB, you should use #Query annotation and its fields attribute. For example, if you have a DiscussionRepository, you could write something like:
public interface DiscussionRepository extends MongoRepository<Discussion, String> {
#Query(value = "{}", fields = "{messages: {$slice: [?0, ?1]}}")
List<Discussion> findDiscussions(int skip, int limit);
}
With this arrangement, following method call:
discussionRepository.findDiscussions(20, 10)
Would generate the same result as:
db.discussions.find({}, {messages: {$slice: [20, 10]}})
With a little bit of work, you can turn the Skip/Limit combination to a pagination functionality.

Android GSON POJO optional field parsing

Ok so heres the thing I am working with an api that for one JSON parameter can return two different types. So I can receive from the server either a JSON Object or a String. I'm pretty new to Android development so if someone could explain to me with maybe a code example how I can handle that problem.
Example json responses {video:"ID OF VIDEO"} or {video:{id:"ID OF VIDEO",...extra data}}. I had a look at custom deserialisers but can't find an example that is easy to follow. There must be a simple way of solving my problem. Currently I receive error "Expected string but found BEGIN OBJECT"
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MyNotification {
#SerializedName("_id")
#Expose
private String Id;
#SerializedName("comment")
#Expose
private String comment;
#SerializedName("createdAt")
#Expose
private String createdAt;
#SerializedName("message")
#Expose
private String message;
#SerializedName("read")
#Expose
private Boolean read;
#SerializedName("recipient")
#Expose
private String recipient;
#SerializedName("sender")
#Expose
private User sender;
#SerializedName("type")
#Expose
private String type;
// #SerializedName("video")
// #Expose
// private String video;
/**
*
* #return
* The Id
*/
public String getId() {
return Id;
}
/**
*
* #param Id
* The _id
*/
public void setId(String Id) {
this.Id = Id;
}
/**
*
* #return
* The comment
*/
public String getComment() {
return comment;
}
/**
*
* #param comment
* The comment
*/
public void setComment(String comment) {
this.comment = comment;
}
/**
*
* #return
* The createdAt
*/
public String getCreatedAt() {
return createdAt;
}
/**
*
* #param createdAt
* The createdAt
*/
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
/**
*
* #return
* The message
*/
public String getMessage() {
return message;
}
/**
*
* #param message
* The message
*/
public void setMessage(String message) {
this.message = message;
}
/**
*
* #return
* The read
*/
public Boolean getRead() {
return read;
}
/**
*
* #param read
* The read
*/
public void setRead(Boolean read) {
this.read = read;
}
/**
*
* #return
* The recipient
*/
public String getRecipient() {
return recipient;
}
/**
*
* #param recipient
* The recipient
*/
public void setRecipient(String recipient) {
this.recipient = recipient;
}
/**
*
* #return
* The sender
*/
public User getSender() {
return sender;
}
/**
*
* #param sender
* The sender
*/
public void setSender(User sender) {
this.sender = sender;
}
/**
*
* #return
* The type
*/
public String getType() {
return type;
}
/**
*
* #param type
* The type
*/
public void setType(String type) {
this.type = type;
}
// /**
// *
// * #return
// * The video
// */
// public String getVideo() {
// return video;
// }
//
// /**
// *
// * #param video
// * The video
// */
// public void setVideo(String video) {
// this.video = video;
// }
}
and the part that craps out
Gson gson = new Gson();
String jsonString = String.valueOf(dataset);
Type listType = new TypeToken<List<MyNotification>>(){}.getType();
notficationsList = (List<MyNotification>) gson.fromJson(jsonString, listType);
Sorry it took so long:
Your best bet is to repair the JSON, if you must map it to an Object.
Try cleaning the JSON with this code:
public static String cleanJson(String json) {
int videoPos = json.indexOf("video");
if(videoPos == -1) {
return json; //return, no video here
}
boolean isObject = false;
int objectBegin = -1;
String cleanedJson = json.replaceAll("\\\"", "\\\\");
for(int i = videoPos; i < cleanedJson.length(); i++) {
if(cleanedJson.charAt(i) == '"') {
System.out.println("string");
return json; // its a string anyway
}
if(cleanedJson.charAt(i) == '{') {
//its an object
// i now is the position beginning the object
objectBegin = i;
}
} //replace " with space
if(objectBegin == -1) {// we did not find any { or " it is a string
return json;
}
boolean inString = false;
int objectEnd = -1;
for(int i = objectBegin; i < cleanedJson.length(); i++) {
//looking for the end of the object;
if(cleanedJson.charAt(i) == '"') inString = !inString;
if(cleanedJson.charAt(i) == '}') {
objectEnd = i;
break;
}
}
if(objectEnd != -1) {
String start = json.substring(0,objectBegin);
String videoPart = json.substring(objectBegin, objectEnd+1);
String end = json.substring(objectEnd+1);
// now we want to get the id
String newVideoPart = "";
int idStart = videoPart.indexOf("id");
int idStringStart = -1;
int idStringEnd = -1;
for(int i = idStart; i < videoPart.length(); i++) {
if(videoPart.charAt(i) == '"') {
if(idStringStart == -1) {
idStringStart = i;
} else {
idStringEnd = i;
break;
}
}
}
if(idStringStart != -1 && idStringEnd != -1) {
newVideoPart = videoPart.substring(idStringStart, idStringEnd+1);
}
return start+newVideoPart+end;
}
return json;
}
Works with these two test jsons:
System.out.println(cleanJson("{video:\"1234\"}"));
System.out.println(cleanJson("{video:{id:\"2345\", name=\"test\"}}"));
Try it like this:
notficationsList = (List<MyNotification>) gson.fromJson(cleanJson(jsonString), listType);
Ok so the solution I went with I wrote my own type adapter that gson allow you to use
public class Helper_StringAdapter extends TypeAdapter<String>{
#Override
public String read(com.google.gson.stream.JsonReader in) throws IOException {
if(in.peek() == JsonToken.NULL){
in.nextNull();
return null;
}else if(in.peek() == JsonToken.BEGIN_OBJECT && in.getPath().contains(".video")){
L.e("VIDEO IS AN OBJECT!");
String userId = readAndReturnVideoId(in);
return userId;
}else{
return in.nextString();
}
}
private String readAndReturnVideoId(com.google.gson.stream.JsonReader reader) throws IOException{
String id = "";
reader.beginObject();
while(reader.hasNext()){
String name = reader.nextName();
if(name.equals("_id")){
id = reader.nextString();
}else{
reader.skipValue();
}
}
reader.endObject();
L.e("READ ID RETURNED"+id);
return id;
}
#Override
public void write(com.google.gson.stream.JsonWriter out, String value) throws IOException {
L.e("TEST "+out);
}
}
Then in my activity data manager (Recyclerview Adapter)
public void updateData (JSONArray dataset) {
GsonBuilder gsonb = new GsonBuilder();
gsonb.registerTypeAdapter(String.class,new Helper_StringAdapter());
Gson gson = gsonb.create();
String jsonString = String.valueOf(dataset);
Type listType = new TypeToken<List<FrameNotification>>(){}.getType();
notficationsList = (List<FrameNotification>) gson.fromJson(jsonString, listType);
}
Seems to do the job

for loop to add certain fields of an object in an arraylist

Sorry if the title wasn't very clear.
anyways, I'm making a monopoly game and im currently working on the income tax space. I have an idea of how to make that, but what I'm stuck on is a method that is supposed to get the total value of all money, properties, etc.
Here's what i have so far:
public int getTotVal()
{
int tot = 0;
for (int i = 0; i < this.properties.size(); i++)
tot += this.properties.get(i).mortgage;
return tot;
}
The for loop is supposed to run through the ArrayList of properties, and for each property, add the mortgage value to the varialble "tot".
I know this isn't right, but how would i do it correctly?
EDIT
Player:
import java.util.ArrayList;
public class Player
{
private String name;
private String token;
public int wallet;
private ArrayList properties;
public Player(String name, String token, int wallet, Property prop)
{
this.name = name;
this.token = token;
this.wallet = wallet;
this.properties.add(prop);
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the token
*/
public String getToken() {
return token;
}
/**
* #param token the token to set
*/
public void setToken(String token) {
this.token = token;
}
/**
* #return the wallet
*/
public int getWallet() {
return wallet;
}
/**
* #param wallet the wallet to set
*/
public void setWallet(int wallet) {
this.wallet = wallet;
}
/**
* #return the properties
*/
public ArrayList getProperties() {
return properties;
}
/**
* #param properties the properties to set
*/
public void setProperties(ArrayList properties) {
this.properties = properties;
}
//add buy()
//add butProp()
//add pay()
//add payRent()
public void pay(int amount)
{
this.wallet -= amount;
}
public int getTotVal()
{
int tot = 0;
for (Property property : this.properties)
{
tot += property.mortgage;
}
return tot;
}
}
Property:
package monopolysrc;
import java.util.Scanner;
public class Property extends Space
{
private int value;
private boolean owned;
private int mortgage;
public Property(String fn,String ln, int val, int mortgage, boolean owned)
{
super(fn,ln);
val = value;
owned = false;
this.mortgage = mortgage;
}
/**
* #return the value
*/
public int getValue() {
return value;
}
/**
* #param value the value to set
*/
public void setValue(int value) {
this.value = value;
}
/**
* #return the owned
*/
public boolean isOwned() {
return owned;
}
/**
* #param owned the owned to set
*/
public void setOwned(boolean owned) {
this.owned = owned;
}
/**
* #return the mortgage
*/
public int getMortgage() {
return mortgage;
}
/**
* #param mortgage the mortgage to set
*/
public void setMortgage(int mortgage) {
this.mortgage = mortgage;
}
}
Try this:
public int getTotVal() {
int tot = 0;
for (int i = 0; i < this.properties.size(); i++)
tot += this.properties.get(i).mortgage;
return tot;
}
There's a neat way to loop over every element of a List:
for (Property property : this.properties) {
tot += property.mortgage;
}

database insert from a model, no such column exception,

firstly i have trouble with creating database,then i want to put my received huge json datas(i converted json to java model by GsonBuilder and i saw all the datas in my entity[] list which made from ReceivedEntityModel class) to database,but i failed at first steps.it never creates my columns,so that after insertion there is 0 rowcount:(, i read all those answers about this topic and they didn't help me at all.I'm stuck.Anyone can help??
public void onCreate(SQLiteDatabase db)
{
String CREATE_M_ENTITY_TABLE = "CREATE TABLE " + TABLE_2_NAME + " ("
+ rId + " INTEGER PRIMARY KEY, "
+ ParentId + " INTEGER, "
+ Code+ " INTEGER, "
+ Label + " TEXT, "
+ LabelFL + " TEXT, "
+ EntityGroupId + " INTEGER, "
+ Property + " TEXT, "
+ ReportCode+ " INTEGER, "
+ Description + " TEXT, "
+ Code1Id + " INTEGER, "
+ Code2Id + " INTEGER, "
+ Code3Id + " INTEGER, "
+ Code4Id+ " INTEGER, "
+ Code5Id + " INTEGER, "
+ DefaultDimension1+ " INTEGER, "
+ DefaultDimension2 + "INTEGER, "
+ DefaultDimension3 + " INTEGER, "
+ CompanyId + " INTEGER, "
+ BranchId + " INTEGER, "
+ ReferenceDate + " TEXT, "
+ ResField1+ " TEXT, "
+ ResField2 + " TEXT, "
+ AreaId + " INTEGER, "
+ ModifiedDateTime + " TEXT, "
+ CreatedDateTime + " TEXT, "
+ RecId + " INTEGER, "
+ IsActive + " BIT,"
+ ModifiedBy + " INTEGER,"
+ CreatedBy + " INTEGER" + ") ";
db.execSQL(CREATE_M_ENTITY_TABLE);
}
i call this function at main activity to bind listview
public Cursor fetchEntities()
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
String myQuery="Select Code, Label from entity";
Cursor mCursor=db.rawQuery(myQuery,null);
int rowCount=mCursor.getCount();
//Cursor mCursor = db.query(TABLE_2_NAME, new String[] {Code, Label }, null,null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//as you see there is paramater like ReceivedEntityModel ,i get the datas from this Model's getters and i want to put them into a database is shown below.
public void AddNewEntity(ReceivedEntityModel[] entity)
{
// addnewentity
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
for (int i = 0; i < entity.length; i++) {
values.put(rId, entity[i].getRId());
values.put(ParentId, entity[i].getParentId());
values.put(Code, entity[i].getCode());
values.put(Label, entity[i].getLabel());
values.put(LabelFL, entity[i].getLabelFL());
values.put(EntityGroupId, entity[i].getEntityGroupId());
values.put(ReportCode, entity[i].getReportCode());
values.put(Description, entity[i].getDescription());
values.put(Code1Id, entity[i].getCode1Id());
values.put(Code2Id, entity[i].getCode2Id());
values.put(Code3Id, entity[i].getCode3Id());
values.put(Code4Id, entity[i].getCode4Id());
values.put(Code5Id, entity[i].getCode5Id());
values.put(DefaultDimension1, entity[i].getDefaultDimension1Id());
values.put(DefaultDimension2, entity[i].getDefaultDimension2Id());
values.put(DefaultDimension3, entity[i].getDefaultDimension3Id());
values.put(CompanyId, entity[i].getCompanyId());
values.put(BranchId, entity[i].getBranchId());
values.put(ReferenceDate, entity[i].getReferenceDate());
values.put(ResField1, (String) entity[i].getResField1());
values.put(ResField2, (String) entity[i].getResField2());
values.put(AreaId, entity[i].getAreaId());
values.put(ModifiedDateTime, entity[i].getModifiedDateTime());
values.put(CreatedDateTime, entity[i].getCreatedDateTime());
values.put(RecId, entity[i].getRecId());
values.put(IsActive, entity[i].getIsActive());
values.put(ModifiedBy, entity[i].getModifiedBy());
values.put(CreatedBy, (String) entity[i].getCreatedBy());
}
db.insert(TABLE_2_NAME, null, values);
db.close();
}
this is Setup.java,fetchEntities(),AddNewEntity() functions are calling from there.Gson Builder make me a model.And the i call AddNewEntity()
protected String doInBackground(String... urls) {
entityReqestInfo = new EntityReqestInfo();
String cevap = POST_FOR_ENTITY(urls[0], entityReqestInfo);
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
receivedEM = gson.fromJson(cevap, ReceivedEntityModel[].class);
myDB.getDatabaseEntityOperations().AddNewEntity(receivedEM);
pDialog.cancel();
return cevap;
}
and last of all my generated entity Model ReceivedEntityModel class
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ReceivedEntityModel {
private Integer rId;
private Integer ParentId;
private String Code;
private String Label;
private String LabelFL;
private Integer EntityGroupId;
private String Property;
private String ReportCode;
private String Description;
private Integer Code1Id;
private Integer Code2Id;
private Integer Code3Id;
private Integer Code4Id;
private Integer Code5Id;
private Integer DefaultDimension1Id;
private Integer DefaultDimension2Id;
private Integer DefaultDimension3Id;
private Integer CompanyId;
private Integer BranchId;
private String ReferenceDate;
private String ResField1;
private String ResField2;
private String AreaId;
private String ModifiedDateTime;
private String CreatedDateTime;
private Integer RecId;
private Boolean IsActive;
private Integer ModifiedBy;
private String CreatedBy;
private String DBranch;
private String DCompany;
private String MEntityGroup;
private List<String> MEntityTableModule = new ArrayList<String>();
private Map<String, String> additionalProperties = new HashMap<String, String>();
/**
*
* #return The rId
*/
public Integer getRId() {
return rId;
}
/**
*
* #param rId
* The rId
*/
public void setRId(Integer rId) {
this.rId = rId;
}
public ReceivedEntityModel withRId(Integer rId) {
this.rId = rId;
return this;
}
/**
*
* #return The ParentId
*/
public Integer getParentId() {
return ParentId;
}
/**
*
* #param ParentId
* The ParentId
*/
public void setParentId(Integer ParentId) {
this.ParentId = ParentId;
}
public ReceivedEntityModel withParentId(Integer ParentId) {
this.ParentId = ParentId;
return this;
}
/**
*
* #return The Code
*/
public String getCode() {
return Code;
}
/**
*
* #param Code
* The Code
*/
public void setCode(String Code) {
this.Code = Code;
}
public ReceivedEntityModel withCode(String Code) {
this.Code = Code;
return this;
}
/**
*
* #return The Label
*/
public String getLabel() {
return Label;
}
/**
*
* #param Label
* The Label
*/
public void setLabel(String Label) {
this.Label = Label;
}
public ReceivedEntityModel withLabel(String Label) {
this.Label = Label;
return this;
}
/**
*
* #return The LabelFL
*/
public String getLabelFL() {
return LabelFL;
}
/**
*
* #param LabelFL
* The LabelFL
*/
public void setLabelFL(String LabelFL) {
this.LabelFL = LabelFL;
}
public ReceivedEntityModel withLabelFL(String LabelFL) {
this.LabelFL = LabelFL;
return this;
}
/**
*
* #return The EntityGroupId
*/
public Integer getEntityGroupId() {
return EntityGroupId;
}
/**
*
* #param EntityGroupId
* The EntityGroupId
*/
public void setEntityGroupId(Integer EntityGroupId) {
this.EntityGroupId = EntityGroupId;
}
public ReceivedEntityModel withEntityGroupId(Integer EntityGroupId) {
this.EntityGroupId = EntityGroupId;
return this;
}
/**
*
* #return The Property
*/
public String getProperty() {
return Property;
}
/**
*
* #param Property
* The Property
*/
public void setProperty(String Property) {
this.Property = Property;
}
public ReceivedEntityModel withProperty(String Property) {
this.Property = Property;
return this;
}
/**
*
* #return The ReportCode
*/
public String getReportCode() {
return ReportCode;
}
/**
*
* #param ReportCode
* The ReportCode
*/
public void setReportCode(String ReportCode) {
this.ReportCode = ReportCode;
}
public ReceivedEntityModel withReportCode(String ReportCode) {
this.ReportCode = ReportCode;
return this;
}
/**
*
* #return The Description
*/
public String getDescription() {
return Description;
}
/**
*
* #param Description
* The Description
*/
public void setDescription(String Description) {
this.Description = Description;
}
public ReceivedEntityModel withDescription(String Description) {
this.Description = Description;
return this;
}
/**
*
* #return The Code1Id
*/
public Integer getCode1Id() {
return Code1Id;
}
/**
*
* #param Code1Id
* The Code1Id
*/
public void setCode1Id(Integer Code1Id) {
this.Code1Id = Code1Id;
}
public ReceivedEntityModel withCode1Id(Integer Code1Id) {
this.Code1Id = Code1Id;
return this;
}
/**
*
* #return The Code2Id
*/
public Integer getCode2Id() {
return Code2Id;
}
/**
*
* #param Code2Id
* The Code2Id
*/
public void setCode2Id(Integer Code2Id) {
this.Code2Id = Code2Id;
}
public ReceivedEntityModel withCode2Id(Integer Code2Id) {
this.Code2Id = Code2Id;
return this;
}
/**
*
* #return The Code3Id
*/
public Integer getCode3Id() {
return Code3Id;
}
/**
*
* #param Code3Id
* The Code3Id
*/
public void setCode3Id(Integer Code3Id) {
this.Code3Id = Code3Id;
}
public ReceivedEntityModel withCode3Id(Integer Code3Id) {
this.Code3Id = Code3Id;
return this;
}
/**
*
* #return The Code4Id
*/
public Integer getCode4Id() {
return Code4Id;
}
/**
*
* #param Code4Id
* The Code4Id
*/
public void setCode4Id(Integer Code4Id) {
this.Code4Id = Code4Id;
}
public ReceivedEntityModel withCode4Id(Integer Code4Id) {
this.Code4Id = Code4Id;
return this;
}
/**
*
* #return The Code5Id
*/
public Integer getCode5Id() {
return Code5Id;
}
/**
*
* #param Code5Id
* The Code5Id
*/
public void setCode5Id(Integer Code5Id) {
this.Code5Id = Code5Id;
}
public ReceivedEntityModel withCode5Id(Integer Code5Id) {
this.Code5Id = Code5Id;
return this;
}
/**
*
* #return The DefaultDimension1Id
*/
public Integer getDefaultDimension1Id() {
return DefaultDimension1Id;
}
/**
*
* #param DefaultDimension1Id
* The DefaultDimension1Id
*/
public void setDefaultDimension1Id(Integer DefaultDimension1Id) {
this.DefaultDimension1Id = DefaultDimension1Id;
}
public ReceivedEntityModel withDefaultDimension1Id(
Integer DefaultDimension1Id) {
this.DefaultDimension1Id = DefaultDimension1Id;
return this;
}
/**
*
* #return The DefaultDimension2Id
*/
public Integer getDefaultDimension2Id() {
return DefaultDimension2Id;
}
/**
*
* #param DefaultDimension2Id
* The DefaultDimension2Id
*/
public void setDefaultDimension2Id(Integer DefaultDimension2Id) {
this.DefaultDimension2Id = DefaultDimension2Id;
}
public ReceivedEntityModel withDefaultDimension2Id(
Integer DefaultDimension2Id) {
this.DefaultDimension2Id = DefaultDimension2Id;
return this;
}
/**
*
* #return The DefaultDimension3Id
*/
public Integer getDefaultDimension3Id() {
return DefaultDimension3Id;
}
/**
*
* #param DefaultDimension3Id
* The DefaultDimension3Id
*/
public void setDefaultDimension3Id(Integer DefaultDimension3Id) {
this.DefaultDimension3Id = DefaultDimension3Id;
}
public ReceivedEntityModel withDefaultDimension3Id(
Integer DefaultDimension3Id) {
this.DefaultDimension3Id = DefaultDimension3Id;
return this;
}
/**
*
* #return The CompanyId
*/
public Integer getCompanyId() {
return CompanyId;
}
/**
*
* #param CompanyId
* The CompanyId
*/
public void setCompanyId(Integer CompanyId) {
this.CompanyId = CompanyId;
}
public ReceivedEntityModel withCompanyId(Integer CompanyId) {
this.CompanyId = CompanyId;
return this;
}
/**
*
* #return The BranchId
*/
public Integer getBranchId() {
return BranchId;
}
/**
*
* #param BranchId
* The BranchId
*/
public void setBranchId(Integer BranchId) {
this.BranchId = BranchId;
}
public ReceivedEntityModel withBranchId(Integer BranchId) {
this.BranchId = BranchId;
return this;
}
/**
*
* #return The ReferenceDate
*/
public String getReferenceDate() {
return ReferenceDate;
}
/**
*
* #param ReferenceDate
* The ReferenceDate
*/
public void setReferenceDate(String ReferenceDate) {
this.ReferenceDate = ReferenceDate;
}
public ReceivedEntityModel withReferenceDate(String ReferenceDate) {
this.ReferenceDate = ReferenceDate;
return this;
}
/**
*
* #return The ResField1
*/
public String getResField1() {
return ResField1;
}
/**
*
* #param ResField1
* The ResField1
*/
public void setResField1(String ResField1) {
this.ResField1 = ResField1;
}
public ReceivedEntityModel withResField1(String ResField1) {
this.ResField1 = ResField1;
return this;
}
/**
*
* #return The ResField2
*/
public String getResField2() {
return ResField2;
}
/**
*
* #param ResField2
* The ResField2
*/
public void setResField2(String ResField2) {
this.ResField2 = ResField2;
}
public ReceivedEntityModel withResField2(String ResField2) {
this.ResField2 = ResField2;
return this;
}
/**
*
* #return The AreaId
*/
public String getAreaId() {
return AreaId;
}
/**
*
* #param AreaId
* The AreaId
*/
public void setAreaId(String AreaId) {
this.AreaId = AreaId;
}
public ReceivedEntityModel withAreaId(String AreaId) {
this.AreaId = AreaId;
return this;
}
/**
*
* #return The ModifiedDateTime
*/
public String getModifiedDateTime() {
return ModifiedDateTime;
}
/**
*
* #param ModifiedDateTime
* The ModifiedDateTime
*/
public void setModifiedDateTime(String ModifiedDateTime) {
this.ModifiedDateTime = ModifiedDateTime;
}
public ReceivedEntityModel withModifiedDateTime(String ModifiedDateTime) {
this.ModifiedDateTime = ModifiedDateTime;
return this;
}
/**
*
* #return The CreatedDateTime
*/
public String getCreatedDateTime() {
return CreatedDateTime;
}
/**
*
* #param CreatedDateTime
* The CreatedDateTime
*/
public void setCreatedDateTime(String CreatedDateTime) {
this.CreatedDateTime = CreatedDateTime;
}
public ReceivedEntityModel withCreatedDateTime(String CreatedDateTime) {
this.CreatedDateTime = CreatedDateTime;
return this;
}
/**
*
* #return The RecId
*/
public Integer getRecId() {
return RecId;
}
/**
*
* #param RecId
* The RecId
*/
public void setRecId(Integer RecId) {
this.RecId = RecId;
}
public ReceivedEntityModel withRecId(Integer RecId) {
this.RecId = RecId;
return this;
}
/**
*
* #return The IsActive
*/
public Boolean getIsActive() {
return IsActive;
}
/**
*
* #param IsActive
* The IsActive
*/
public void setIsActive(Boolean IsActive) {
this.IsActive = IsActive;
}
public ReceivedEntityModel withIsActive(Boolean IsActive) {
this.IsActive = IsActive;
return this;
}
/**
*
* #return The ModifiedBy
*/
public Integer getModifiedBy() {
return ModifiedBy;
}
/**
*
* #param ModifiedBy
* The ModifiedBy
*/
public void setModifiedBy(Integer ModifiedBy) {
this.ModifiedBy = ModifiedBy;
}
public ReceivedEntityModel withModifiedBy(Integer ModifiedBy) {
this.ModifiedBy = ModifiedBy;
return this;
}
/**
*
* #return The CreatedBy
*/
public String getCreatedBy() {
return CreatedBy;
}
/**
*
* #param CreatedBy
* The CreatedBy
*/
public void setCreatedBy(String CreatedBy) {
this.CreatedBy = CreatedBy;
}
public ReceivedEntityModel withCreatedBy(String CreatedBy) {
this.CreatedBy = CreatedBy;
return this;
}
/**
*
* #return The DBranch
*/
public String getDBranch() {
return DBranch;
}
/**
*
* #param DBranch
* The D_Branch
*/
public void setDBranch(String DBranch) {
this.DBranch = DBranch;
}
public ReceivedEntityModel withDBranch(String DBranch) {
this.DBranch = DBranch;
return this;
}
/**
*
* #return The DCompany
*/
public String getDCompany() {
return DCompany;
}
/**
*
* #param DCompany
* The D_Company
*/
public void setDCompany(String DCompany) {
this.DCompany = DCompany;
}
public ReceivedEntityModel withDCompany(String DCompany) {
this.DCompany = DCompany;
return this;
}
/**
*
* #return The MEntityGroup
*/
public String getMEntityGroup() {
return MEntityGroup;
}
/**
*
* #param MEntityGroup
* The M_EntityGroup
*/
public void setMEntityGroup(String MEntityGroup) {
this.MEntityGroup = MEntityGroup;
}
public ReceivedEntityModel withMEntityGroup(String MEntityGroup) {
this.MEntityGroup = MEntityGroup;
return this;
}
/**
*
* #return The MEntityTableModule
*/
public List<String> getMEntityTableModule() {
return MEntityTableModule;
}
/**
*
* #param MEntityTableModule
* The M_EntityTableModule
*/
public void setMEntityTableModule(List<String> MEntityTableModule) {
this.MEntityTableModule = MEntityTableModule;
}
public ReceivedEntityModel withMEntityTableModule(
List<String> MEntityTableModule) {
this.MEntityTableModule = MEntityTableModule;
return this;
}
public Map<String, String> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, String value) {
this.additionalProperties.put(name, value);
}
public ReceivedEntityModel withAdditionalProperty(String name, String value) {
this.additionalProperties.put(name, value);
return this;
}
}
Where are the column names defined?
The DefaultDimension2 column is not created with the intended name
in your table, because you forgot a space here:
+ DefaultDimension2 + "INTEGER, "
It must be
+ DefaultDimension2 + " INTEGER, "
So, supposing that the DefaultDimension2 column name is defined as
public String DefaultDimension2 = "DefaultDimension2";
it is actually created as "DefaultDimension2INTEGER, " instead of "DefaultDimension2 INTEGER, "
It's really a common mistake, mostly due to hurry.

adding array objects to a list

i'm new to java and I am having problems adding my array objects to my list. I have already checked the topics in this forum but can't find something similar to my problem.
I have already made a class called Item that will save information about an item to be sold, and it has 4 instance variables id, desc, cost, quantity. And then I have a Sales class which has my main method. Basically what I want to do is build an array of objects from my Item class and hard code my data(which I have already created, i'm not sure if I did it right though).
I have created an ArrayList and what I want to do now is add the 5 objects from the array that I created into the list.
This is my Item class
public class Item {
private String itemID;
private String desc;
private double cost;
private int quantity;
public Item() {
itemID="";
desc="";
cost=0;
quantity=0;
}
public Item(String id, String d, double c, int q) {
itemID = id;
desc = d;
cost = c;
quantity = q;
}
/**
* #return the itemID
*/
public String getItemID() {
return itemID;
}
/**
* #param itemID the itemID to set
*/
public void setItemID(String itemID) {
this.itemID = itemID;
}
/**
* #return the desc
*/
public String getDesc() {
return desc;
}
/**
* #param desc the desc to set
*/
public void setDesc(String desc) {
this.desc = desc;
}
/**
* #return the cost
*/
public double getCost() {
return cost;
}
/**
* #param cost the cost to set
*/
public void setCost(double cost) {
this.cost = cost;
}
/**
* #return the quantity
*/
public int getQuantity() {
return quantity;
}
/**
* #param quantity the quantity to set
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Item [itemID=" + itemID + ", desc=" + desc + ", cost=" + cost
+ ", quantity=" + quantity + "]";
}
}
And my Sales class:
import java.util.*;
public class Sales {
/**
* #param args
*/
public static void main(String[] args) {
int i;
Item[] items = new Item[5];
for(i = 0; i < items.length; i++)
{
items[i]= new Item(); // create array
}
//hard-coded values of id, desc, cost, qty
items[0].setItemID("PN250");
items[1].setItemID("ER100");
items[2].setItemID("PP150");
items[3].setItemID("MK200");
items[4].setItemID("PN300");
items[0].setDesc("Pen");
items[1].setDesc("Eraser");
items[2].setDesc("Paper");
items[3].setDesc("Marker");
items[4].setDesc("Pen");
items[0].setCost(1.50);
items[1].setCost(1.25);
items[2].setCost(3.75);
items[3].setCost(2.50);
items[4].setCost(2.25);
items[0].setQuantity(0);
items[1].setQuantity(175);
items[2].setQuantity(310);
items[3].setQuantity(75);
items[4].setQuantity(450);
double total = 0;
for(Item d : items)
{
System.out.print(d.getItemID());
System.out.print("\t" + d.getDesc());
System.out.print("\t" + d.getCost());
System.out.println("\t" + d.getQuantity());
}
List<Item> obj;
obj = new ArrayList<Item>();
}
}
You could add the array into your list with the following:
obj.addAll(Arrays.asList(items));
You can use:
for (i = 0; i < items.length; i++)
{
obj.add(items[i]);
}
but why not add the items as soon as they are created & populated?
instead of creating an array at the beginning of your function, create an arrayList and add objects to it using the put method.
Also, you should think of making your objects immutables and pass their attributes to their constructor instead of calling the setter for each attribute

Categories

Resources