Null Pointer at foreign key - java

I'm using MySQL and Hibernate. I've added record to Receiving table and have id and barcode fields as foreign keys in transaction table rcid and barcode.
When I search a specific record using id:
int id =(Integer)defaultTableModel.getValueAt(jReceivingsTable.getSelectedRow(),0);
Receivings receivings = manager.searchReceivingsId(id);
that doesn't null, printing id return appropriate value so why I'm getting null when I set it to Transaction table?
Rctransaction rctransaction = new Rctransaction();
rctransaction.getReceivings().getId().setId(id); // here id has value
rctransaction.getReceivings().getId().setBarcode(barcode);
rctransaction.setReceivings(receivings);
Here are classes :
Receivings.java
public class Receivings implements java.io.Serializable {
private ReceivingsId id;
private Suppliers suppliers;
private String itemName;
private String category;
private double wholesalePrice;
private double retailPrice;
private long tax1;
private long tax2;
private String type1;
private String type2;
private int quantityStock;
private int receivingQuantity;
private int recorderLevel;
private String receivingDate;
private double discount;
private Set itemses = new HashSet(0);
private Set rctransactions = new HashSet(0);
public Receivings() {
}
public Receivings(ReceivingsId id, Suppliers suppliers, String itemName, String category, double wholesalePrice, double retailPrice, long tax1, long tax2, String type1, String type2, int quantityStock, int receivingQuantity, int recorderLevel, String receivingDate, double discount) {
this.id = id;
this.suppliers = suppliers;
this.itemName = itemName;
this.category = category;
this.wholesalePrice = wholesalePrice;
this.retailPrice = retailPrice;
this.tax1 = tax1;
this.tax2 = tax2;
this.type1 = type1;
this.type2 = type2;
this.quantityStock = quantityStock;
this.receivingQuantity = receivingQuantity;
this.recorderLevel = recorderLevel;
this.receivingDate = receivingDate;
this.discount = discount;
}
public Receivings(ReceivingsId id, Suppliers suppliers, String itemName, String category, double wholesalePrice, double retailPrice, long tax1, long tax2, String type1, String type2, int quantityStock, int receivingQuantity, int recorderLevel, String receivingDate, double discount, Set itemses, Set rctransactions) {
this.id = id;
this.suppliers = suppliers;
this.itemName = itemName;
this.category = category;
this.wholesalePrice = wholesalePrice;
this.retailPrice = retailPrice;
this.tax1 = tax1;
this.tax2 = tax2;
this.type1 = type1;
this.type2 = type2;
this.quantityStock = quantityStock;
this.receivingQuantity = receivingQuantity;
this.recorderLevel = recorderLevel;
this.receivingDate = receivingDate;
this.discount = discount;
this.itemses = itemses;
this.rctransactions = rctransactions;
}
public ReceivingsId getId() {
return this.id;
}
public void setId(ReceivingsId id) {
this.id = id;
}
public Suppliers getSuppliers() {
return this.suppliers;
}
public void setSuppliers(Suppliers suppliers) {
this.suppliers = suppliers;
}
public String getItemName() {
return this.itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getCategory() {
return this.category;
}
public void setCategory(String category) {
this.category = category;
}
public double getWholesalePrice() {
return this.wholesalePrice;
}
public void setWholesalePrice(double wholesalePrice) {
this.wholesalePrice = wholesalePrice;
}
public double getRetailPrice() {
return this.retailPrice;
}
public void setRetailPrice(double retailPrice) {
this.retailPrice = retailPrice;
}
public long getTax1() {
return this.tax1;
}
public void setTax1(long tax1) {
this.tax1 = tax1;
}
public long getTax2() {
return this.tax2;
}
public void setTax2(long tax2) {
this.tax2 = tax2;
}
public String getType1() {
return this.type1;
}
public void setType1(String type1) {
this.type1 = type1;
}
public String getType2() {
return this.type2;
}
public void setType2(String type2) {
this.type2 = type2;
}
public int getQuantityStock() {
return this.quantityStock;
}
public void setQuantityStock(int quantityStock) {
this.quantityStock = quantityStock;
}
public int getReceivingQuantity() {
return this.receivingQuantity;
}
public void setReceivingQuantity(int receivingQuantity) {
this.receivingQuantity = receivingQuantity;
}
public int getRecorderLevel() {
return this.recorderLevel;
}
public void setRecorderLevel(int recorderLevel) {
this.recorderLevel = recorderLevel;
}
public String getReceivingDate() {
return this.receivingDate;
}
public void setReceivingDate(String receivingDate) {
this.receivingDate = receivingDate;
}
public double getDiscount() {
return this.discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public Set getItemses() {
return this.itemses;
}
public void setItemses(Set itemses) {
this.itemses = itemses;
}
public Set getRctransactions() {
return this.rctransactions;
}
public void setRctransactions(Set rctransactions) {
this.rctransactions = rctransactions;
}
}
ReceivingsId.java
//Composition of Id and Barcode of Receivings
public class ReceivingsId implements java.io.Serializable {
private int id;
private int barcode;
public ReceivingsId() {
}
public ReceivingsId(int id, int barcode) {
this.id = id;
this.barcode = barcode;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public int getBarcode() {
return this.barcode;
}
public void setBarcode(int barcode) {
this.barcode = barcode;
}
public boolean equals(Object other) {
if ( (this == other ) ) return true;
if ( (other == null ) ) return false;
if ( !(other instanceof ReceivingsId) ) return false;
ReceivingsId castOther = ( ReceivingsId ) other;
return (this.getId()==castOther.getId())
&& (this.getBarcode()==castOther.getBarcode());
}
public int hashCode() {
int result = 17;
result = 37 * result + this.getId();
result = 37 * result + this.getBarcode();
return result;
}
}
Rctransaction.java
public class Rctransaction implements java.io.Serializable {
private Integer id;
private Receivings receivings;
private String transaction;
private String supplierName;
private String itemName;
private double quantity;
private String paymentType;
private double amountTendred;
private double due;
private double total;
private double price;
private int recorderLevel;
public Rctransaction() {
}
public Rctransaction(Receivings receivings, String transaction, String supplierName, String itemName, double quantity, String paymentType, double amountTendred, double due, double total, double price, int recorderLevel) {
this.receivings = receivings;
this.transaction = transaction;
this.supplierName = supplierName;
this.itemName = itemName;
this.quantity = quantity;
this.paymentType = paymentType;
this.amountTendred = amountTendred;
this.due = due;
this.total = total;
this.price = price;
this.recorderLevel = recorderLevel;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Receivings getReceivings() {
return this.receivings;
}
public void setReceivings(Receivings receivings) {
this.receivings = receivings;
}
public String getTransaction() {
return this.transaction;
}
public void setTransaction(String transaction) {
this.transaction = transaction;
}
public String getSupplierName() {
return this.supplierName;
}
public void setSupplierName(String supplierName) {
this.supplierName = supplierName;
}
public String getItemName() {
return this.itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public double getQuantity() {
return this.quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public String getPaymentType() {
return this.paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public double getAmountTendred() {
return this.amountTendred;
}
public void setAmountTendred(double amountTendred) {
this.amountTendred = amountTendred;
}
public double getDue() {
return this.due;
}
public void setDue(double due) {
this.due = due;
}
public double getTotal() {
return this.total;
}
public void setTotal(double total) {
this.total = total;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
public int getRecorderLevel() {
return this.recorderLevel;
}
public void setRecorderLevel(int recorderLevel) {
this.recorderLevel = recorderLevel;
}
}

You are instantiating the Hibernate objects in the wrong order.
First you need a ReceivingsId :
ReceivingsId rid = new ReceivingsId (id, barcode);
Then add this rid to a Receivings:
Receivings rec = new Receivings();
rec.setId(rid);
And finally set it to the Rctransaction:
Rctransaction rctransaction = new Rctransaction();
rctransaction.setReceivings(rec);
If you try to call getReceivings after instantiating the object without setting it before you'll always get a NullPointerException. To avoid this, you can instantiate the Receivings object in the Rctransaction constructor.

Related

ObjectMapper can't map the variables of inner class

ObjectMapper mapper = new ObjectMapper();
try {
attractionMainResponse = mapper.readValue(response,AttractionMainResponse.class);
} catch(IOException io) {
showToast("Something went wrong");
FirebaseCrash.log(io.toString());
finish();
}
AttractionMainResponse :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AttractionMainResponse {
private AttractionDetailModel Attraction_Info;
private String response;
public AttractionMainResponse() {
Attraction_Info = null;
response =null;
}
public AttractionMainResponse(AttractionDetailModel aa,String ab) {
Attraction_Info = aa;
response = ab;
}
public AttractionDetailModel getAttraction_Info() {
return Attraction_Info;
}
public void setAttraction_Info(AttractionDetailModel attraction_Info) {
Attraction_Info = attraction_Info;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
AttractionDetailModel :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AttractionDetailModel {
private AddressDataAttraction address_data;
private List<Image> Images;
private TypesInAttraction Type;
private String architect;
private String architectural_style;
private int city_id;
private String founder;
private String description;
private int id;
private String name;
private String height;
private String opened_since;
private String popularity;
private String timings;
private String visitors;
private String profile_image_url;
public AttractionDetailModel() {
address_data = null;
architect = null;
architectural_style = null;
city_id=-1;
founder = null;
description = null;
id=-1;
name=null;
height=null;
opened_since=null;
popularity = null;
timings=null;
visitors=null;
Images = null;
Type=null;
profile_image_url=null;
}
public AttractionDetailModel(AddressDataAttraction address_data, List<Image> images, TypesInAttraction type, String architect, String architectural_style, int city_id, String founder, String description, int id, String name, String height, String opened_since, String popularity, String timings, String visitors, String profile_image_url) {
this.address_data = address_data;
Images = images;
Type = type;
this.architect = architect;
this.architectural_style = architectural_style;
this.city_id = city_id;
this.founder = founder;
this.description = description;
this.id = id;
this.name = name;
this.height = height;
this.opened_since = opened_since;
this.popularity = popularity;
this.timings = timings;
this.visitors = visitors;
this.profile_image_url = profile_image_url;
}
public String getProfile_image_url() {
return profile_image_url;
}
public void setProfile_image_url(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public AddressDataAttraction getAddress_data() {
return address_data;
}
public void setAddress_data(AddressDataAttraction address_data) {
this.address_data = address_data;
}
public List<Image> getImages() {
return Images;
}
public void setImages(List<Image> images) {
Images = images;
}
public TypesInAttraction getType() {
return Type;
}
public void setType(TypesInAttraction type) {
Type = type;
}
public String getArchitect() {
return architect;
}
public void setArchitect(String architect) {
this.architect = architect;
}
public String getArchitectural_style() {
return architectural_style;
}
public void setArchitectural_style(String architectural_style) {
this.architectural_style = architectural_style;
}
public int getCity_id() {
return city_id;
}
public void setCity_id(int city_id) {
this.city_id = city_id;
}
public String getFounder() {
return founder;
}
public void setFounder(String founder) {
this.founder = founder;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
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 getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getOpened_since() {
return opened_since;
}
public void setOpened_since(String opened_since) {
this.opened_since = opened_since;
}
public String getPopularity() {
return popularity;
}
public void setPopularity(String popularity) {
this.popularity = popularity;
}
public String getTimings() {
return timings;
}
public void setTimings(String timings) {
this.timings = timings;
}
public String getVisitors() {
return visitors;
}
public void setVisitors(String visitors) {
this.visitors = visitors;
}
}
AddressDataAttractions :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AddressDataAttraction {
private String address;
private String city;
private String country;
private String landmark;
private float latitude;
private float longitude;
private String pincode;
private String state;
public AddressDataAttraction() {
address=null;
city=null;
country=null;
landmark=null;
latitude=-1;
longitude=-1;
pincode=null;
state=null;
}
public AddressDataAttraction(String address, String city, String country, String landmark, float latitude, float longitude, String pincode, String state) {
this.address = address;
this.city = city;
this.country = country;
this.landmark = landmark;
this.latitude = latitude;
this.longitude = longitude;
this.pincode = pincode;
this.state = state;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLandmark() {
return landmark;
}
public void setLandmark(String landmark) {
this.landmark = landmark;
}
public float getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
TypeInAttraction :
#JsonIgnoreProperties (ignoreUnknown = true)
public class TypesInAttraction{
private String type;
private int id ;
public TypesInAttraction() {
type=null;
id=-1;
}
public TypesInAttraction(String type, int id) {
this.type = type;
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
In debug mode, string response in objectMapper shows correct response, string response in attractionMainResponse giving a success but can't map the attractionDetailModel, giving null.
Is this about a Jackson ObjectMapper? Is it possible to create a smaller example, that makes it easier to give a solution.

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

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

List of class objects from list of strings

I am getting data from gemfire
List<String> objects = restTemplate.getForObject(geodeURL+"/gemfire-api/v1/queries/adhoc?q=SELECT * FROM /region s",List.class);
which is like below:
[('price':'119','volume':'20000','pe':'0','eps':'4.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'), ('price':'112','volume':'20000','pe':'0','eps':'9.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'), ('price':'118','volume':'20000','pe':'0','eps':'1.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996')]
This is a list of String I am getting.Currently I have 3 values in list.
I have a pojo class like below:
public class StockInfo {
// #Id
#JsonProperty("symbol")
private String symbol;
#JsonProperty("price")
private String price;
#JsonProperty("volume")
private String volume;
#JsonProperty("pe")
private String pe;
#JsonProperty("eps")
private String eps;
#JsonProperty("week53low")
private String week53low;
#JsonProperty("week53high")
private String week53high;
#JsonProperty("daylow")
private String daylow;
#JsonProperty("dayhigh")
private String dayhigh;
#JsonProperty("movingav50day")
private String movingav50day;
#JsonProperty("marketcap")
private String marketcap;
#JsonProperty("time")
private String time;
private String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getVolume() {
return volume;
}
public void setVolume(String volume) {
this.volume = volume;
}
public String getPe() {
return pe;
}
public void setPe(String pe) {
this.pe = pe;
}
public String getEps() {
return eps;
}
public void setEps(String eps) {
this.eps = eps;
}
public String getWeek53low() {
return week53low;
}
public void setWeek53low(String week53low) {
this.week53low = week53low;
}
public String getWeek53high() {
return week53high;
}
public void setWeek53high(String week53high) {
this.week53high = week53high;
}
public String getDaylow() {
return daylow;
}
public void setDaylow(String daylow) {
this.daylow = daylow;
}
public String getDayhigh() {
return dayhigh;
}
public void setDayhigh(String dayhigh) {
this.dayhigh = dayhigh;
}
public String getMovingav50day() {
return movingav50day;
}
public void setMovingav50day(String movingav50day) {
this.movingav50day = movingav50day;
}
public String getMarketcap() {
return marketcap;
}
public void setMarketcap(String marketcap) {
this.marketcap = marketcap;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
How do I create a List of StockInfo class object from the value I am getting from restTemplate.getForObject
I think you could just use:
List<StockInfo> objects = restTemplate.getForObject(geodeURL+"/gemfire-api/v1/queries/adhoc?q=SELECT * FROM /region s",List.class);

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.

Java Object Serialization to JSON using Jackson

I have the following POJO classes
#JsonIgnoreProperties(ignoreUnknown = true)
public class GroupUser {
#JsonProperty("userId")
int userId;
#JsonProperty("status")
int status;
#JsonProperty("admin")
int isAdmin;
#JsonProperty("email")
String email;
#JsonProperty("creator")
int Creator;
#JsonProperty("new")
int isNew;
// generated and cached
#JsonProperty("user_name")
String userName;
public GroupUser() {
}
#JsonIgnore
public GroupUser(String email, int isCreator) {
this.userId = 0;
this.email = email;
this.Creator = isCreator;
this.isAdmin = isCreator;
if (isCreator == 1) {
this.status = Group.STATE_ACCEPTED;
this.isNew = 0;
} else {
this.isNew = 1;
this.status = Group.STATE_INVITED;
}
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(int isAdmin) {
this.isAdmin = isAdmin;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getCreator() {
return Creator;
}
public void setCreator(int creator) {
Creator = creator;
}
public int getIsNew() {
return isNew;
}
public void setIsNew(int isNew) {
this.isNew = isNew;
}
}
And
#JsonIgnoreProperties(ignoreUnknown = true)
public class Group {
#JsonIgnore
final public static int STATE_INVITED = 1;
#JsonIgnore
final public static int STATE_REJECTED = 2;
#JsonIgnore
final public static int STATE_ACCEPTED = 3;
#JsonIgnore
final public static int STATE_PENDING = 4;
#JsonProperty("location")
String location;
#JsonProperty("radius")
int radius;
#JsonProperty("adminApprovalForObservers")
int isAdminApprovalRequired;
#JsonProperty("title")
String Title;
#JsonProperty("groupUsers")
GroupUser[] Users;
#JsonProperty("newVotingOnlyByAdmin")
int onlyAdminCreatesVote;
#JsonProperty("new")
int isNew;
#JsonProperty("requiredVotes")
int requiredVotes;
#JsonProperty("type")
int type;
#JsonProperty("allowObservers")
int allowObservers;
#JsonProperty("thumb")
String imageUrl;
#JsonProperty("timestamp")
long timeStamp;
#JsonProperty("openForAnyone")
int isOpenForAnyone;
#JsonProperty("uniqueId")
String uiqueId;
#JsonProperty("newDecisionOnlyByAdmin")
int newDecisionOnlyByAdmin;
#JsonProperty("requirePresence")
int requirePresence;
#JsonProperty("groupId")
int groupId;
#JsonProperty("automaticExclusions")
int autoExclusion;
#JsonProperty("adminApprovalForMembership")
int adminApprovalForMembership;
#JsonProperty("description")
String description;
// generated and cached
#JsonProperty("creator_name")
String creatorName;
public Group() {
}
#JsonIgnore
public Group(int id) {
this.groupId = id;
}
#JsonIgnore
public Group(String name, String description, String imagePath) {
this.Title = name;
this.description = description;
this.groupId = 0;
this.location = "";
this.radius = 0;
this.imageUrl = imagePath;
this.isNew = 1;
this.Users = new GroupUser[] {};
this.isOpenForAnyone = 1;
this.onlyAdminCreatesVote = 0;
this.adminApprovalForMembership = 0;
this.allowObservers = 1;
this.timeStamp = Calendar.getInstance().getTimeInMillis() / 1000;
}
#JsonIgnore
public String getCreatorsEmail() {
for (GroupUser u : Users) {
if (u.getCreator() == 1) {
return u.getEmail();
}
}
return null;
}
#JsonIgnore
public int getCreatorsId() {
for (GroupUser u : Users) {
if (u.getCreator() == 1) {
return u.getUserId();
}
}
return -1;
}
#JsonIgnore
public GroupUser getUser(int userId) {
if (Users != null) {
for (GroupUser gu : Users) {
if (gu.getUserId() == userId) {
return gu;
}
}
}
return null;
}
public String getCreatorName() {
return creatorName;
}
public void setCreatorName(String creatorName) {
this.creatorName = creatorName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public int getIsAdminApprovalRequired() {
return isAdminApprovalRequired;
}
public void setIsAdminApprovalRequired(int isAdminApprovalRequired) {
this.isAdminApprovalRequired = isAdminApprovalRequired;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
#JsonProperty("groupUsers")
public GroupUser[] getUsers() {
return Users;
}
#JsonProperty("groupUsers")
public void setUsers(GroupUser[] users) {
Users = users;
}
public int getOnlyAdminCreatesVote() {
return onlyAdminCreatesVote;
}
public void setOnlyAdminCreatesVote(int onlyAdminCreatesVote) {
this.onlyAdminCreatesVote = onlyAdminCreatesVote;
}
public int getIsNew() {
return isNew;
}
public void setIsNew(int isNew) {
this.isNew = isNew;
}
public int getRequiredVotes() {
return requiredVotes;
}
public void setRequiredVotes(int requiredVotes) {
this.requiredVotes = requiredVotes;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getAllowObservers() {
return allowObservers;
}
public void setAllowObservers(int allowObservers) {
this.allowObservers = allowObservers;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(long timeStamp) {
this.timeStamp = timeStamp;
}
public int getIsOpenForAnyone() {
return isOpenForAnyone;
}
public void setIsOpenForAnyone(int isOpenForAnyone) {
this.isOpenForAnyone = isOpenForAnyone;
}
public String getUiqueId() {
return uiqueId;
}
public void setUiqueId(String uiqueId) {
this.uiqueId = uiqueId;
}
public int getNewDecisionOnlyByAdmin() {
return newDecisionOnlyByAdmin;
}
public void setNewDecisionOnlyByAdmin(int newDecisionOnlyByAdmin) {
this.newDecisionOnlyByAdmin = newDecisionOnlyByAdmin;
}
public int getRequirePresence() {
return requirePresence;
}
public void setRequirePresence(int requirePresence) {
this.requirePresence = requirePresence;
}
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public int getAutoExclusion() {
return autoExclusion;
}
public void setAutoExclusion(int autoExclusion) {
this.autoExclusion = autoExclusion;
}
public int getAdminApprovalForMembership() {
return adminApprovalForMembership;
}
public void setAdminApprovalForMembership(int adminApprovalForMembership) {
this.adminApprovalForMembership = adminApprovalForMembership;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
I am using jackson library to serialize the Group Object to JSON like below:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true);
return mapper.writeValueAsString(group);
But the Users fields never gets serialized, no matter what groupUsers always is an empty array []. Any idea what am I doing wrong?

Categories

Resources