Parse xml response using retrofit - android

i am unable to parse xml response using retrofit.
here is xml:
<ossi>
<eventdetail>
<maps>
<settings>...</settings>
<map>...</map>
<map>...</map>
</maps>
</eventdetail>
</ossi>
<------ EDIT ---------->
Here are models
#Root(name = "ossi")
public class RootEventDetail {
#Element
public EventDetail eventdetail;
}
public class EventDetail {
#Element
public General general;
#ElementList
public List<MenuItem> menu;
#ElementList
public List<WebViewItem> module_webview;
//TODO how can i create model for Maps ??????
#Element
public Maps maps;
}
public class Maps {
#Element
public MapSettings settings;
#Element
public List<EventMap> map;
}
How my model will look like?
Thanks in advance.

Finally i solved my problem. I used inline property to solve my issue.
Here is My Model:
public class Maps {
#ElementList(inline = true ,required = false)
public List<Map> map;
#Element
public Settings settings;
}
And Main class is:
public class EventDetail {
#Element
public Maps maps;
}

Related

How to make the changes made to the model effective with DataBinding after setModel?

DataBinding: how can I make sure that as a result of a modification of the data model the view is updated accordingly?
Eg:
public class MyActivity extends AppCompatActivity {
private MyActivityBinding mBinding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.my_activity);
mBinding.setMyModel(new MyModel());
}
public void onClickAnItem(View view) {
MyModel model = mBinding.getMyModel();
model.setField1 = "Jhon";
model.setField2 = "Dho";
mBinding.executePendingBindings();
}
}
In this case the model "MyModel" has been modified but view is not updated; what did I miss?
Reading documentation I found a solution, first of all:
Any plain old Java object (POJO) may be used for data binding, but modifying a POJO will not cause the UI to update!
To give MyModel data object the ability to notify when data changes I made this modifications:
private class MyModel extends BaseObservable {
private String field1;
private String field2;
#Bindable
public String getField1() {
return this.field1;
}
#Bindable
public String getField2() {
return this.field2;
}
public void setField1(String firstName) {
this.field1 = firstName;
notifyPropertyChanged(BR.field1);
}
public void setField2(String lastName) {
this.field2 = lastName;
notifyPropertyChanged(BR.field2);
}
}
I hope this can help someone else
Documentation here

No setter/field for found Android Firebase

I used FirebaseRecyclerAdapter to get all the childs of "Pro" using a Model class named " Spacecraft" and now I want to retrieve all the candidates into a child of Pro like "1"
I created a public static "candidat" into "Spacecraft" and I used the setters and getters but still the same error
This is my database:
this is the Model Class
public class Spacecraft{
private String name;
private String desc;
private String last;
private candidat candidat;
public Spacecraft.candidat getCandidat() {
return candidat;
}
public void setCandidat(Spacecraft.candidat candidat) {
this.candidat = candidat;
}
public Spacecraft() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public static class candidat{
private String info;
private String namecandid;
public candidat(){}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getNamecandid() {
return namecandid;
}
public void setNamecandid(String namecandid) {
this.namecandid = namecandid;
}
}
}
This is my code for FirebaseRecyclerAdapter
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Spacecraft, candidatviewholder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Spacecraft, candidatviewholder>(
Spacecraft.class,
R.layout.candidat,
candidatviewholder.class,
query){
#Override
protected void populateViewHolder(candidatviewholder viewHolder, Spacecraft model, int position) {
viewHolder.setName1(model.getCandidat().getNamecandid());
viewHolder.setInfo1(model.getCandidat().getInfo());
}
};
rv.setAdapter(firebaseRecyclerAdapter);
}
The error:
No setter/field for key1 found on class com.example.ilyas.evotingapplication.Spacecraft$candidat
I had this error but the above solutions didn't fix it. Hopefully, this alternate solution will help others. If you have that error occur for almost every variable, chances are that you have Proguard enabled and it is removing the un-used getter and setter methods. To fix this, add a line similar to this to your proguard-rules.pro file:
-keep class com.example.yourapp.ObjectClass
where ObjectClass is the name of your java object class that is stored to Firebase.
I think it's just that your data models on Firebase and in Java differ.
In your java class, the Spacecraft class has a candidat field of type Candidat. But, in the database, the candidat field is really a nested object (map), containing one key Key1, which value is a Candidat structure.
So, depending on what did you want to achieve:
if you wanted each spacecraft to have exactly one candidat: save the database object properly, so {info: "info 1", namecandid: "name 1"} is saved directly under candidat field, not one level deeper, so the field has type Candidat in the code.
if you wanted each spacecraft to have a few candidats: instead of private Candidat candidat field, it should be typed Map<String, Candidat>, because that's the type it has in your database screenshot.
Work for me:
-keepclassmembers class com.myPackageName.MyClassName { *; }

GSON should ignore class attributes that do not appear in JSON

currently I'm playing with GSON and got into some trouble that I couldn't solve on my own.
I've got these three classes:
One abstract class CustomEntity
public abstract class CustomEntity {
private View customView;
public CustomEntity() {}
public void setCustomView(View customView) {
this.customView = customView;
}
public View getCustomView() {
return customView;
}
}
Another class LastChange which extends from CustomEntity
public class LastChange extends CustomEntity {
public Config config;
public LastChange() {}
#Override
public String toString() {
return "LastChange:" + config.toString();
}
public Config getConfig() {
return config;
}
public void setConfig(Config config) {
this.config = config;
}
}
And a third class Config
public class Config extends CustomEntity {
public String config;
public String nav_items;
public Config() {}
#Override
public String toString() {
return "config data:" + config + ", " + nav_items;
}
public String getConfig() {
return config;
}
public void setConfig(String config) {
this.config = config;
}
public String getNav_items() {
return nav_items;
}
public void setNav_items(String nav_items) {
this.nav_items = nav_items;
}
}
In the MainActivity I've tried to deserialize the following JSON into a LastChange object with GSON.
String lastChangeJson = "{\"config\":{\"config\":\"2016-07-20 15:32:14\",\"nav_items\":\"2016-08-24 12:36:06\"},\"background_images\":{\"background_url_landscape\":\"2015-07-28 17:21:56\",\"background_url\":\"2015-07-28 17:21:56\",\"icon_for_accessory_view\":\"2015-07-28 17:21:56\",\"icon_for_route_view\":\"2015-07-28 17:21:56\",\"background_url_landscape_big\":\"2015-07-28 17:21:56\",\"background_url_big\":\"2015-07-28 17:21:56\"},\"nav_content\":[{\"last_change\":\"2016-06-29 11:06:16\",\"pageId\":\"10262\"},{\"last_change\":\"2016-08-24 12:36:06\",\"pageId\":\"10264\"},{\"last_change\":\"2016-08-09 16:13:03\",\"pageId\":\"10378\"},{\"last_change\":\"2016-08-09 16:13:03\",\"pageId\":\"10263\"},{\"last_change\":\"2016-07-20 15:32:14\",\"pageId\":\"10265\"}]}";
CustomEntity lastChangeEntity = gson.fromJson(lastChangeJson, LastChange.class);
The code above gives me the following exception:
java.lang.SecurityException: Can't make method constructor accessible
at java.lang.reflect.Constructor.setAccessible(Constructor.java:336)
at com.google.gson.internal.ConstructorConstructor.newDefaultConstructor(ConstructorConstructor.java:101)
at com.google.gson.internal.ConstructorConstructor.get(ConstructorConstructor.java:83)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:99)
at com.google.gson.Gson.getAdapter(Gson.java:423)...
But if I remove the attribute "customView" from the class CustomEntity and its getter and setter, the deserialization works fine.
Anybody got an idea on how I can tell GSON to ignore class attributes, if they don't appear in my json?
Thanks in advance.
When building new gson instance:
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Annotate every field you want to serialize with #Expose:
#Expose
public Config config;
Edit:
One small side note - try to avoid keeping references to views (or any Context-related objects) in your models. You may encounter memory leaks if you persist instances of this model in static way and it smells like mixing presentation and data layers, which is never good thing to do for code readability and maintainability.

Failed to handle RealmList<RealmList<RealmInt>> in Realm.io

My JSON data looks like this from server api
{
//...
PredecessorIds:[[1,2][3,4][5]]
//...
}
I can successfully handle the arrays of Integer or String by RealmList<RealmInt> but this time I failed with an error, because RealmList> is not supported saying, "Type parameter 'io.realm.realmList' is not within its bounds...."
For RealmInt see this link.
I tried to solve it using RealmList<RealmLista> where RealmLista extends from RealmObject and has a RealmList like this
public class RealmLista extends RealmObject {
public RealmList<RealmInt> value;
public RealmLista() {
}
public RealmLista(RealmList<RealmInt> val) {
this.value = val;
}
}
and then created a RealmListaTypeAdapter and added it to Gson but when deserializing Gson expects an Object (RealmLista) but is found array, as the data shown above from server is obvious.
//RealmListAdapter for Gson
#Override
public RealmLista read(JsonReader in) throws IOException {
RealmLista lista = new RealmLista();
Gson gson = new Gson();
//how to read that [[1],[3,4]] int into RealmLista
in.beginArray();
while (in.hasNext()) {
lista.value.add(new RealmInt(in.nextInt()));
}
in.endArray();
return lista;
}
Is there any way to store a simple List<List<Integer>> by converting to RealmObject of any type while saving, List<List<Integer>> is easily converted by Gson. :-/
Realm doesn't support lists of lists currently. See https://github.com/realm/realm-java/issues/2549.
So #EpicPandaForce's idea about creating a RealmObject that holds that inner list is probably the best work-around.
It could look something like this:
public class Top extends RealmObject {
private RealmList<ChildList> list;
}
public class ChildList extends RealmObject {
private RealmList<RealmInt> list;
}
public class RealmInt extends RealmObject {
private int i;
}
The correct link for the gist should be: https://gist.github.com/cmelchior/1a97377df0c49cd4fca9

parse complex Gson , nested inner class was not parsed

I use gson.fromJson(jsonStr, JVisitorResponse) method to parse the JSON reponse string, all were parsed except the inner class JUserUrls, there must be something wrong, my wrong usage of Gson caused this, please help me.
My outer reponse class defined below:
public class JVisitorResponse extends BaseResponsePojo {
public int count;
#SerializedName("visitor_list")
public ArrayList<JVisitor> visitorList;
public JVisitorResponse() {
}
}
JVIsitor class defined below:
public class JVisitor {
#SerializedName("user_id")
public long uid;
#SerializedName("user_name")
public String userName;
#SerializedName("user_urls")
public JUserUrls userHeadUrls;
}
JUserUrls class defiend below:
public class JUserUrls {
#SerializedName("main_url")
public String mainUrl;
}
my JSON response was
{
count:30,
visitor_list:[
{
user_id:333333,
user_name:"jason lee",
user_urls:{
main_url:"http://xxxxxxxxxx.jpg"
}
},
...
]
}

Categories

Resources