I've an object pObject
Object pObject = someRpcCall();
I don't know the type of pObject
What i know is System.out.println(pObject.toString()) outputs
{partner_shipping_id=12, partner_order_id=11, user_id=1, partner_invoice_id=13, pricelist_id=1, fiscal_position=false, payment_term=false}
How can I convert this pObject to object of the following class
import android.os.Parcel;
import android.os.Parcelable;
public class Customer implements Parcelable {
private int id;
private String name = "";
public Customer() {
// TODO Auto-generated constructor stub
}
/**
* This will be used only by the MyCreator
*
* #param source
*/
public Customer(Parcel source) {
/*
* Reconstruct from the Parcel
*/
id = source.readInt();
name = source.readString();
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(name);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
#Override
public Customer createFromParcel(Parcel source) {
return new Customer(source);
}
#Override
public Customer[] newArray(int size) {
return new Customer[size];
// TODO Auto-generated method stub
}
};
}
Whats the output of System.out.println(pObject.getClass().getName());
If its the same Customer class, then you could cast the object like this
Customer cust = (Customer) pObject;
The answer to the above problem is provided, but I have a generic solution which I want to share all of you.
First, fetch the class name using Object object(provided)
Using Enum know the Class name
Create a reference object of the known class
Initialize your Object class object
e.g:
package com.currentobject;
import com.currentobject.model.A;
import com.currentobject.model.B;
import com.currentobject.model.C;
Class CurrentObject{
public void objectProvider(Object object){
String className = object.getClass().getCanonicalName();
ModelclassName modelclass = ModelclassName.getOperationalName(className);
switch (modelclass) {
case A:
A a = (A) object;
break;
case B:
B b = (B) object;
break;
case C:
C c = (C) object;
break;
}
}
}
enum ModelclassName {
A("com.currentobject.model.A"),
B("com.currentobject.model.B"),
C("com.currentobject.model.C");
private ModelclassName(String name) {
this.name = name;
}
public static ModelclassName getOperationalName(final String operationName) {
for(ModelclassName oprname :ModelclassName.values()) {
if(oprname.name.equalsIgnoreCase(operationName)){
return oprname ;
}
}
return null;
}
String name;
}
Related
So i have 2 classes, and in the class race i have a method ( public Athlete getAthlete(int codAthlete) ) that
should return the object corresponding to the Athlete with the code passed by parameter, but i am not sure how to
implement it. Can someone give me a hand?
public class Athlete {
private int codAthlete;
private String name;
public Athlete(int codAthlete){
this.codAthlete = codAthlete;
}
public int getCodAthlete() {
return this.codAthlete;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public String getInformation() {
return "Code: " + this.codAthlete +
" Name " + this.name;
}
}
.
public class Race {
private String idRace;
private Set<Athlete> athletes;
public Race(String idRace) {
athletes = new HashSet<>();
this.idRace = idRace;
}
public String getIdRace () {
return this.idRace;
}
public Athlete getAthlete(int codAthlete){
for(Athlete a: Athlete){
if(a.getCodAthlete() == codAthlete)
a.getInformation();
}
return (????);
// Returns the object corresponding to the Athlete with the code passed by parameter.
}
}
I have One Inner Class and One Outer Class. Using Java Reflection I want to access the data of the inner class instance.
public class OuterClass {
public OuterClass() {
super();
}
public OuterClass(InnerClass innerClass1, InnerClass innerClass2) {
super();
this.innerClass1 = innerClass1;
this.innerClass2 = innerClass2;
}
private InnerClass innerClass1;
private InnerClass innerClass2;
public class InnerClass {
public InnerClass() {
super();
}
public InnerClass(int id, String name, String rollNo) {
super();
this.id = id;
this.name = name;
this.rollNo = rollNo;
}
private int id;
private String name;
private String rollNo;
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 getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
}
public InnerClass getInnerClass1() {
return innerClass1;
}
public void setInnerClass1(InnerClass innerClass1) {
this.innerClass1 = innerClass1;
}
public InnerClass getInnerClass2() {
return innerClass2;
}
public void setInnerClass2(InnerClass innerClass2) {
this.innerClass2 = innerClass2;
}
}
Main Class:-
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Reflection {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
OuterClass outerClass = new OuterClass();
OuterClass.InnerClass innerClass1 = outerClass.new InnerClass(1, "Iftekhar", "1234");
OuterClass.InnerClass innerClass2 = outerClass.new InnerClass(2, "Ahmed", "123");
outerClass.setInnerClass1(innerClass1);
outerClass.setInnerClass2(innerClass2);
Field[] fields = outerClass.getClass().getDeclaredFields();
for (Field f : fields) {
Method method = OuterClass.InnerClass.class.getMethod("getId", null);
int id = (int) method.invoke(f, null);
System.out.println(id);
}
}
}
I am anticipating the output to be 1 and 2. But i am getting the below Exception:-
Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
I am instantiating the inner Class attributes using the way show above.Can anyone please help where i am doing wrong.
You are calling getId() on a java.lang.reflect.Field instance. And a java.lang.reflect.Field is not an instance of OuterClass.InnerClass.
To fix this, you first have to get the value of the field and call getId() on that:
Field[] fields = outerClass.getClass().getDeclaredFields();
// We only have to find the method once and can reuse it
Method method = OuterClass.InnerClass.class.getMethod("getId");
// We have to call .setAccessible because the fields are private
AccessibleObject.setAccessible(fields, true);
for (Field f : fields) {
OuterClass.InnerClass value = (OuterClass.InnerClass) f.get(outerClass);
// At this point, you could also use value.getId();
int id = (int) method.invoke(value);
System.out.println(id);
}
I am getting error while loading the bundle. I have checked all the initialization and casting but not able to resolve this.
Please see the reference:
Bundle bundle = getIntent().getExtras();
if (bundle.containsKey("MEASUREMENT_DATA")) {
body_scaleMeasurement = bundle.getParcelable("MEASUREMENT_DATA");
evaluate_info();
}
The code for body _scaleMeasurement
package model;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
public class BodyScaleMeasurement implements Parcelable {
#SerializedName("id")
private String id;
#SerializedName("client_platform_version")
private String client_platform_version;
#SerializedName("client_build_number")
#SerializedName("client_platform_data")
private Client_platform_data client_platform_data;
#SerializedName("ble_device_data")
private Ble_device_data ble_device_data;
private transient boolean is_synchronized;
public BodyScaleMeasurement() {
}
public BodyScaleMeasurement(String id, String client_platform_version, int client_build_number, Client_platform_data client_platform_data, Ble_device_data ble_device_data, boolean is_synchronized) {
this.id = id;
this.client_platform_version = client_platform_version;
this.client_build_number = client_build_number;
this.client_platform_data = client_platform_data;
this.ble_device_data = ble_device_data;
this.is_synchronized = is_synchronized;
}
public boolean is_synchronized() {
return is_synchronized;
}
public void setIs_synchronized(boolean is_synchronized) {
this.is_synchronized = is_synchronized;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClient_platform_version() {
return client_platform_version;
}
public void setClient_platform_version(String client_platform_version) {
this.client_platform_version = client_platform_version;
}
public int getClient_build_number() {
return client_build_number;
}
public void setClient_build_number(int client_build_number) {
this.client_build_number = client_build_number;
}
public Client_platform_data getClient_platform_data() {
return client_platform_data;
}
public void setClient_platform_data(Client_platform_data client_platform_data) {
this.client_platform_data = client_platform_data;
}
public Ble_device_data getBle_device_data() {
return ble_device_data;
}
public void setBle_device_data(Ble_device_data ble_device_data) {
this.ble_device_data = ble_device_data;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.id);
dest.writeString(this.client_platform_version);
dest.writeInt(this.client_build_number);
dest.writeParcelable(this.client_platform_data, 0);
dest.writeParcelable(this.ble_device_data, 0);
dest.writeByte(is_synchronized ? (byte) 1 : (byte) 0);
}
protected BodyScaleMeasurement(Parcel in) {
this.id = in.readString();
this.client_platform_version = in.readString();
this.client_build_number = in.readInt();
this.client_platform_data = in.readParcelable(Client_platform_data.class.getClassLoader());
this.ble_device_data = in.readParcelable(Ble_device_data.class.getClassLoader());
this.is_synchronized = in.readByte() != 0;
}
public static final Parcelable.Creator<BodyScaleMeasurement> CREATOR = new Parcelable.Creator<BodyScaleMeasurement>() {
public BodyScaleMeasurement createFromParcel(Parcel source) {
return new BodyScaleMeasurement(source);
}
public BodyScaleMeasurement[] newArray(int size) {
return new BodyScaleMeasurement[size];
}
};
}
This is the error which i get. Please refer the image I have attached.
It was happening because I changed the type of other variables from double to int. It was not expected though, but I am myself not understaning it. I reverted the changes in which the conversion was done.
Also, there was change in values too after conversion. For example : if i was sending 50 to bundle with a key. It was being setted as some negative integer.
Is it possible that the Client_platform_data implements Parcelable and has
Parcelable.Creator<Ble_device_data> ?
I am trying to save an enum 'Status' into a custom class that implements parcelable. I have found online how I can save Strings, ints or enums in one class that implements parcelable, but not how I can save these three things all at once. I am sorry if the solution is obvious, but I just can't figure it out.
Here is what my enum looks like:
public enum Status {
INITIALIZED, UPDATED, DELETED
}
And this is what I have so far:
public class Recipe implements Parcelable{
private String id;//this should be an int, same problem
private String recipeName;
private String recipePreperation;
private Status status;
private final static int MAX_PREVIEW = 50;
public Recipe(int parId, String parRecipeName, String parRecipePreperation) {
this.id = "" + parId;
this.recipeName = parRecipeName;
this.recipePreperation = parRecipePreperation;
this.status = Status.INITIALIZED;
}
public Recipe(Parcel in){
String[] data = new String[4];
in.readStringArray(data);
this.id = data [0];
this.recipeName = data[1];
this.recipePreperation = data[2];
this.status = data[3];//what I intend to do, I know this is wrong
}
public int GetId() {
return Integer.parseInt(id);
}
public String GetRecipeName() {
return this.recipeName;
}
public void SetRecipeName(String parRecipeName) {
this.recipeName = parRecipeName;
}
public String GetRecipePreperation() {
return this.recipePreperation;
}
public void SetRecipePreperation(String parRecipePreperation) {
this.recipePreperation = parRecipePreperation;
}
public Status GetStatus() {
return this.status;
}
public void SetStatus(Status parStatus) {
this.status = parStatus;
}
public String toString() {
String recipe = this.recipeName + "\n" + this.recipePreperation;
String returnString;
int maxLength = MAX_PREVIEW;
if (recipe.length() > maxLength) {
returnString = recipe.substring(0, maxLength - 3) + "...";
} else {
returnString = recipe;
}
return returnString;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int arg1) {
dest.writeStringArray(new String [] {
this.id,
this.recipeName,
this.recipePreperation,
this.status//what I intend to do, I know this is wrong
});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Recipe createFromParcel(Parcel in) {
return new Recipe(in);
}
public Recipe[] newArray(int size) {
return new Recipe[size];
}
};
}
How do I save an int, an array of strings and an enum into a class that implements the parcelable, so it can writeToParcel()?
There's no need to read and write to/from string array. Just write each string and finally the status as Serializable. This is how I fix it.
public Recipe(Parcel in){
this.id = in.readString();
this.recipeName = in.readString();
this.recipePreperation = in.readString();
this.status = (Status) in.readSerializable();
}
public void writeToParcel(Parcel dest, int arg1) {
dest.writeString(this.id);
dest.writeString(this.recipeName);
dest.writeString(this.recipePreperation);
dest.writeSerializable(this.status);
}
I have make a class which has a custom class object/variable and i want to make this class parcelable for passing it in to the intend so that i receive the reponse in next activity
MORE DETAILED
I Have class first ie
public class Data implements Parcelable{
#SerializedName("barlist")
Bar bar_list[];
public Bar[] getBarLst() {
return bar_list;
}
public void setBarLst(Bar lst[]) {
this.bar_list = lst;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeParcelableArray(bar_list, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
}
public static final Parcelable.Creator<Data> CREATOR = new Creator<Data>() {
public Data createFromParcel(Parcel source) {
Data data = new Data();
data.bar_list = (Bar[]) source.readParcelableArray(this.getClass().getClassLoader());
return data;
}
#Override
public Data[] newArray(int size) {
// TODO Auto-generated method stub
return new Data[size];
}
};
}
In the above class i have a custom type object/variable ie of type Bar
and my next class is ::
public class Bar implements Parcelable{
#SerializedName("name")
String Name;
#SerializedName("sex")
String sex;
#SerializedName("type")
String type;
#SerializedName("userid")
String userId;
#SerializedName("contactno")
String ContactNo;
#SerializedName("zipcode")
String zipCode;
#SerializedName("address")
String Address;
#SerializedName("email")
String Email;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getContactNo() {
return ContactNo;
}
public void setContactNo(String contactNo) {
ContactNo = contactNo;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(Name);
parcel.writeString(sex);
parcel.writeString(type);
parcel.writeString(userId);
parcel.writeString(ContactNo);
parcel.writeString(zipCode);
parcel.writeString(Address);
parcel.writeString(Email);
}
public static final Parcelable.Creator<Bar> CREATOR = new Creator<Bar>() {
public Bar createFromParcel(Parcel source) {
Bar barlst = new Bar();
barlst.Name = source.readString();
barlst.sex = source.readString();
barlst.ContactNo = source.readString();
barlst.type = source.readString();
barlst.userId = source.readString();
barlst.zipCode = source.readString();
barlst.Address = source.readString();
barlst.Email = source.readString();
return barlst;
}
#Override
public Bar[] newArray(int size) {
// TODO Auto-generated method stub
return new Bar[size];
}
};
}
I want to make a data class (first class) object be parcelable so in my first activity i did some this like this
EmptyRequest empt = new EmptyRequest();
Data responsestr = userManager.getMainMenuItems(empt,"url","Post","getBarList");
Intent myintent = new Intent(MainMenuPageActivity.this, BarListPageActivity.class);
Bundle mbundle = new Bundle();
mbundle.putParcelable("BARLIST", responsestr);
myintent.putExtras(mbundle);
startActivity(myintent);
till here my code worked fine and i kept the responsestr of type data into the parcelable
and in my next acitivity i tried to fetch data object like this
Data responseStr = (Response)getIntent().getParcelableExtra("BARLIST");
to fetch the object of type data but this didnt work and give exception the second activity class not found but my debugger reaches in the second activity.
Thanks in advance....
use
getIntent().getExtras().getParcelableExtra("BARLIST");