Json parsing with gson not working - android

This is my JSON string:
[{"BranchID":1,"SecurityCode1":13,"SecurityCode2":14,"PrintHeight":10,"PrintWidth":10,"Active":true}]
This is Code I am using to parse the JSON:
Type t = new TypeToken<List<Setting>>() {
}.getClass();
String json = ServiceHelper.getJSON(response);
List<Setting> list = (List<Setting>) gson.fromJson(json, t);
//list is null which it souldnt
This is the Setting class, Entity is ORMDroid entity class:
public class Setting extends Entity {
#Column(name = "id", primaryKey = true)
#SerializedName("BranchID")
public int BranchID;
public int securityCodeLPK;
public int securityCodeSDK;
#SerializedName("PrintHeight")
public int PrintHeight;
#SerializedName("PrintWidth")
public int PrintWidth;
#SerializedName("Active")
public String Active;
#SerializedName("SecurityCode1")
public String SecurityCode1;
#SerializedName("SecurityCode2")
public String SecurityCode2;
public Setting(int BranchID, int height, int width, String active, String securityCode1, String securityCode2) {
super();
BranchID = BranchID;
PrintHeight = height;
PrintWidth = width;
Active = active;
SecurityCode1 = securityCode1;
SecurityCode2 = securityCode2;
}
public Setting () {
super();
}
}
It seems to be OK, but list after gson.FromJson is null. What's wrong with this code?
Please help

You should use getType() instead of getClass().
Type t = new TypeToken<List<Setting>>() {}.getType();

Related

java.lang.ClassCastException: java.util.HashMap cannot be cast to Ride

DatabaseReference ridesRef = database.getReference("rides");
ridesRef.equalTo(from).orderByChild("from").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, "dataSnapshot.getChildrenCount(): " + dataSnapshot.getChildrenCount());
if (dataSnapshot.getChildrenCount() > 0) {
ArrayList<Ride> value = (ArrayList<Ride>) dataSnapshot.getValue();
Log.i(TAG, value.toString());
for (Ride r : value) { // error occurs here
Log.i(TAG, "r.getTime:" + r.getTime());
Log.i(TAG, "getFrom:" + r.getFrom());
}
}
}
});
Log output is:
09-02 18:08:25.070 23651-23651 I/RidesFragment:
dataSnapshot.getChildrenCount(): 1
09-02 18:08:25.070 23651-23651 I/RidesFragment: [{to=Hackerscher
Markt, userID=0, time=1472831718565, regularly=false, price=0,
chosenUserID=0, active=true, places=1, from=Hauptbahnhof Berlin,
meetingPointDescription=blaues ei}]
public class Ride {
private String from;
private String to;
private long time;
private int places;
private String meetingPointDescription;
private boolean regularly;
private boolean active;
private float price;
private int userID;
private int chosenUserID;
public Ride() {
// Default constructor required for calls to DataSnapshot.getValue(Ride.class)
}
public Ride(String from, String to, long time, int places, String meetingPointDescription, boolean regularly,
boolean active, float price, int userID, int chosenUserID) {
this.from = from;
this.to = to;
this.time = time;
this.places = places;
this.meetingPointDescription = meetingPointDescription;
this.regularly = regularly;
this.active = active;
this.price = price;
this.userID = userID;
this.chosenUserID = chosenUserID;
}
// automatically generated getters and setters...
}
Third time I got an answer to my own question :/
ArrayList<Ride> value = (ArrayList<Ride>) dataSnapshot.getValue();
has to be replaced by
GenericTypeIndicator<ArrayList<Ride>> t = new GenericTypeIndicator<ArrayList<Ride>>() {};
ArrayList<Ride> value = dataSnapshot.getValue(t);
and everything works as expected.

How to sort a listview by string numbers?

Here is my main issue, after some researches, I didn't find a solution so... I would like to sort my list of custom objects. These items have a price, but for a reason they are strings not int. I would like to know how to achieve this, thanks for helping !
Little personnal question, sorting a listview and a recyclerview are they done the same way ?
EDIT:
public class Product implements Parcelable {
private String imgUrl, titre, description, prix, nomAgence, pays, ville, type_produit, nbPieces = null;
List<String> urlImageList_thumb = new ArrayList<>();
List<String> urlImageList_full = new ArrayList<>();
private int isAdded = 0;
/* getters and setters*/
}
EDIT 2 :After your help, here's my code for comparable
#Override
public int compareTo(Product otherProduct) {
String tmp = prix.replace(" €", "");
String tmp2 = otherProduct.prix.replace(" €", "");
//Integer p1 = Integer.valueOf(tmp); --> does not work
//Integer p2 = Integer.valueOf(tmp2); --> does not work
Integer p1 = Integer.parseInt(tmp); //same error
Integer p2 = Integer.parseInt(tmp2); // same error
return p1.compareTo(p2);
}
Here's the code in the activity:
bouton_tri.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Collections.sort(productList);
}
});
EDIT 3 :
#Override
public int compareTo(Product otherProduct) {
String tmp = prix.replace(" €", "").replaceAll(" ", "");
String tmp2 = otherProduct.prix.replace(" €", "").replaceAll(" ", "");
Integer p1 = Integer.valueOf(tmp);
Integer p2 = Integer.valueOf(tmp2);
return p1.compareTo(p2);
}
I still have an error, but when I just take off " €" the value is "5 300 000", if only spaces "5300000€". But putting both together gives me this error java.lang.NumberFormatException: Invalid int: "-" ... Any ideas ? Thanks
You can make modify your Product class to implement Comparable
Before converting the String to an Integer you need to remove the €and all spaces.
public class Product implements Parcelable, Comparable<Product> {
private String prix;
//...
#Override
public int compareTo(Product otherProduct) {
String tmp = prix.replace(" €", "").replaceAll(" ", "");
String tmp2 = otherProduct.prix.replace(" €", "").replaceAll(" ", "");
Integer p1 = Integer.valueOf(tmp);
Integer p2 = Integer.valueOf(tmp2);
return p1.compareTo(p2);
}
}
Once done to sort your collection you can use : Collections.sort(...); this method will take as parameter the list of custom objects you are using in your adapter.
For example:
List<Product> l = new ArrayList();
Collections.sort(l);
Note that sorting the collection will not refresh the views of the recyclerview.
You will have to call notifyDataSetChanged() on your adapter to refresh the recyclerview:
You can do this in your main activity where you have declared your adapter :
yourAdapter.notifyDataSetChanged();
Just assuming you have List<String> sampleData object
Collections.sort(sampleData, new Comparator<String>() {
#Override
public int compare(String c1, String c2) {
return Integer.valueOf(c1) - Integer.valueOf(c2);
}
});
This will sort your data.
(int) Integer.parseInt(p2.getNumberOfRecords()) - Integer.parseInt(p1.getNumberOfRecords())
So the simple compare of an integer in a String data type would not result correctly but to parse the string first by:
int value = Integer.parseInt(string)
Try this:
Collections.sort (list, new Comparator<String> () {
#Override
public int compare (String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
OR
Collections.sort (list, new Comparator<String> () {
#Override
public int compare (String s1, String s2) {
//cast string price to integer
int price1 = Integer.parseInt(s1);
int price2 = Integer.parseInt(s2);
if (price1 > price1) {
return 1;
}
else if (price2 > price1) {
return -1;
}
else {
return 0;
}
}
});

Add new object into relationship in Realm

I have a problem with Realm that ill my brain :(
The problem is when I try to add a new object into RealmList. The object is inserted but it is not linked with the relationship.
Now, my database has multiple relationships:
User 1-->M Trip 1-->M Vehicle 1-->M
And then:
Vehicle 1-->M VehicleInfo
VehicleInfo 1-->M Temperature
The problem reside when I try to insert a new object into Temperature class.
My classes:
Vehicle:
#RealmClass
public class Vehicle extends RealmObject
{
private String state; //R: Reservado | P: Listo para embarcar | E: Embarcado | P1: Pdte. confirmar medidas | P2: Tª no válida | R1: No embarca
private String locata = "";
private String customer = "";
private String customerCode = "";
private String originPort = ""; //Origin port
private String destinyPort = ""; //Destiny port
private int fp; //Method pay (0 = CASH | 1 = CREDIT)
//Relationship
private Trip trip; //Inverse
private RealmList<VehicleInfo> vehicleInfo = new RealmList<>(); //One-to-many
private RealmList<Observation> observations = new RealmList<>();; //One-to-many
.....
}
VehicleInfo:
#RealmClass
public class VehicleInfo extends RealmObject {
private String sv; //Vehicle type
private String licensePlate = ""; //License
private String seal = ""; //Seal
private String temperature = ""; //Temperature control
private String iv = ""; //Ida/Vuelta
private String commodityCode = "";
private int tara = 0; //TARA
private int packages = 0; //Bultos
private int weight = 0;
private double length = 0.0; //Meters
private boolean flagFT; //Flag Technical data
private boolean flagDua;
private boolean flagManifest;
private boolean flagTransport;
private boolean flagDangerCommodity;
//Relationship
private RealmList<Temperature> temperatures = new RealmList<>(); //One-to-many
....
}
My code to add new Temperature:
Temperature temp = new Temperature();
temp.setDate(appCommon.getCurrentTimeOrDate("DATE"));
temp.setTime(appCommon.getCurrentTimeOrDate("TIME"));
temp.setValue(Double.parseDouble(etTemp.getText().toString()));
VehicleInfoPersistence.updateVehicleInfoTemperature(realm, vehicle.getLocata(), selectedUnitPosition, temp);
updateRecycler(tempRecyclerAdapter, temp);
Method to find and persist in Realm:
public static VehicleInfo findVehicleInfoFromLocata(Realm realm, String locata, int position) {
RealmQuery<Vehicle> query = realm.where(Vehicle.class).equalTo("locata", locata);
Vehicle realmVehicle = query.findFirst();
return realmVehicle.getVehicleInfo().get(position);
}
public static void updateVehicleInfoTemperature(Realm realm, String locata, int position, Temperature temperature) {
Vehicle vehicle = VehiclePersistence.findVehicleFromLocata(realm, locata);
realm.beginTransaction();
Temperature realmTemp = realm.copyToRealm(temperature);
vehicle.getVehicleInfo().get(position).getTemperatures().add(realmTemp);
realm.commitTransaction();
}
How I said, object is created in database but it is not linked with the vehicle-->vehicleInfo-->Temperature.
What's wrong in my code??
Thanks in advance :)
I resolved my problem :)
By some motive, realm fails when I try to add new object into sub-array of a RealmClass.
To solve this issue I've created an intermediate object and then I've added the object to this intermediate object.
public static void updateVehicleInfoTemperature(Realm realm, String locata, int position, Temperature temperature) {
Vehicle vehicle = VehiclePersistence.findVehicleFromLocata(realm, locata);
realm.beginTransaction();
VehicleInfo vInfo = vehicle.getVehicleInfo().get(position);
VehicleInfo realmVehicleInfo = realm.copyToRealm(vInfo);
Temperature realmTemp = realm.copyToRealm(temperature);
realmVehicleInfo.getTemperatures().add(realmTemp);
realm.commitTransaction();
}
I hope to help someone :)

sending a customized object to intent android

I want to pass an object of type Annonce to an Intent. As you can see, it's simple if the class attributes are primitives, However; in my case I have an image (Bitmap) and an attribute of type Client ( I have created a Client class).
My solution is to access the Client attributes (using getter and setter) and parsing it in the writeToParcel method one by one (it takes too much time), and for the image, I am sending it in the mainActivity using ByteArrayOutputStream. Can anyone help me do it all in Annonce class.
public class Annonce implements Parcelable {
String article, desc, temps, ville, categorie;
int prix;
Bitmap img;
Client c;
public Annonce(String article, String desc, String temps, String ville,
String categorie, int prix, Bitmap img, Client c) {
this.article = article;
this.desc = desc;
this.c = c;
this.prix = prix;
this.img = img;
this.temps = temps;
this.categorie = categorie;
this.ville = ville;
}
public static final Parcelable.Creator<Annonce> CREATOR = new Parcelable.Creator<Annonce>() {
public Annonce createFromParcel(Parcel source) {
return new Annonce(source);
}
public Annonce[] newArray(int size) {
return new Annonce[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(article);
parcel.writeString(desc);
parcel.writeString(temps);
parcel.writeString(ville);
parcel.writeString(categorie);
parcel.writeInt(prix);
}
public Annonce(Parcel source) {
article = source.readString();
desc = source.readString();
temps = source.readString();
ville = source.readString();
categorie = source.readString();
prix = source.readInt();
}
}
Having an attribut of type "bitmap" is not a good solution . Instead of that , we can use the path of the image to refer to the bitmap image .
Also, we can convert the Client into object in parcelable in order to send it through intent.

Android Parcelable object return Null

I have Product class.I want to pass product object one activity to another.
I have implemented like this :
public class Product implements Parcelable{
private double availableQuantity;
private double price;
private String productCode;
private String description;
private String nonStockItemFlag;
private String activeFlag;
private String kitProductFlag;
private double value;
private ArrayList<Product> product;
private double qty;
public Product() {
}
/**
* #param availableQuantity
* #param price
* #param productCode
* #param description
* #param nonStockItemFlag
* #param kitProductFlag
* #param qty
* #param grossValue
* #param value
*/
public Product(double availableQuantity, double price, String productCode,
String description, String nonStockItemFlag, String kitProductFlag,
double qty, double value) {
super();
this.availableQuantity = availableQuantity;
this.price = price;
this.productCode = productCode;
this.description = description;
this.nonStockItemFlag = nonStockItemFlag;
this.kitProductFlag = kitProductFlag;
this.qty = qty;
this.value = value;
}
// setter & getter
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
Bundle b = new Bundle();
b.putParcelableArrayList("enteredProduct", product);
dest.writeBundle(b);
}
public static final Parcelable.Creator<Product> CREATOR = new Parcelable.Creator<Product>() {
public Product createFromParcel(Parcel in) {
Product prod = new Product();
Bundle b = in.readBundle(Product.class.getClassLoader());
prod.product = b.getParcelableArrayList("enteredProduct");
System.out.println("***product***" + prod.product.get(0).getPrice());
return prod;
}
public Product[] newArray(int size) {
return new Product[size];
}
};
This is caller part :
if(productMap.size() >0){
ArrayList<Product> enteredProductList = new ArrayList<Product>(productMap.values());
System.out.println("-enteredProductList --" + enteredProductList.size());
System.out.println("--- " +enteredProductList.get(0).getPrice() );
Bundle b = new Bundle();
b.putParcelableArrayList("enteredProduct", enteredProductList);
Intent showContent = new Intent(getApplicationContext(),RetailerOrderIActivity.class);
showContent.putExtras(b); //Insert the Bundle object in the Intent' Extras
startActivity(showContent);
}else{
Toast.makeText(RetailerOrderActivity.this," You don't have invoice records" ,Toast.LENGTH_SHORT).show();
}
This is receive part :
Bundle b = this.getIntent().getExtras();
ArrayList<Product> p = b.getParcelableArrayList("enteredProduct");
System.out.println("-- RetailerOrderIActivity --" + p.size() );
for(Product s : p){
System.out.println(" --Qty-" + s.getQty());
System.out.println(" --price -" + s.getPrice());
System.out.println(" --code -" + s.getProductCode());
}
The receiving part return null value.But in the sending Activity part contain value.Please correct my code?
what is wrong in my code?
I have lot of property for product entity calss.But i want to set some of entity.
Thanks in advance.
I guess you misunderstood the Parcelable examples.
You have to put all needed elements into the parcel, and get it from it later:
To write your object to the parcel, this is needed:
public void writeToParcel(Parcel dest, int flags)
{
dest.writeString(productCodce);
dest.writeString(description);
// and all other elements
}
Plus, you need a constructor receiving a parcel:
public Product(Parcel in)
{
this.productCode=in.readString();
this.description=in.readString();
// and all other elements
}
Your Creator should be something like:
public static final Parcelable.Creator CREATOR = new Parcelable.Creator()
{
public Product createFromParcel(Parcel in) { return new Product(in); }
public Product[] newArray(int size) { return new Product[size]; }
};
Now, at your activity level (NOT in your Product class!):
Push it into extras, use:
bundle.putParcelableArrayList("whatevername",products);
To get it from the extras, use a simple:
ArrayList<Product> products=bundle.getParcelableArrayList("whatevername");

Categories

Resources