How can i create an array that contains another array? - android

I need to save some values that i get it from a listview, my question is how can i do this implementation to save my values?
I need to do this.
[
{
"id_question": "my value here",
"answers": [
{
"my_answer":"value for this answer",
"id_answer":"my value here"
},
{
"my_answer":"value for this answer",
"id_answer":"my value here"
}
]
}
]
Recently i use
List<Map<String, String>[]> listOfMaps = new ArrayList<Map<String, String>[]>();

Answer.java
public class Answer {
private String myAnswer;
private String idAnswer;
//constructor, setters and getters
}
Question.java
public class Question {
private String question;
private List<Answer> answerList;
//constructor, setters and getters
}
In your current class
private List<Question> questionList;
If what I understand by the term “saving” in your question as saving to local db, then these classes can directly be converted to Realm Classes.
P.S. Simple way to get to this data structure is to stick to basics. That is objects are representation of real time entity.

Related

Is it possible to serialize and deserialize an object that contain an object as a variable in Firebase?

I am trying to structure my databases, and I was wondering if it's possible to deserialize an object from Firebase RealDatabase with the following structure.
public class Profile{
private String userID;
private TenantProfile tenant;
}
public class TenantProfile{
private String name;
private Room room;
}
public class Room{
private String town;
private int size;
}
Can the entire object Profile from Firebase be deserialized from a single query?
I just want to make sure that this is possible before refactoring my code and changing the references to the database.
Thanks in advance.
The Firebase database serializes/deserializes any public fields, and public properties that follow JavaBean naming conventions for getters and setters. Since the classes you show contain neither of those, they will not read or write any data.
If you mark the fields as public or add public getters/setters, then writing an instance of the Profile class will generate this JSON:
"userID": {
"tenant": {
"name": "the name",
"room": {
"town": "the town",
"size": 42
}
}
}
And that's also the format you'll need to have in the database to read the value back.

Cannot access the getter within POJO class

I am trying to access a getter method which is inside a POJO class within my response modal.
public class Event implements Parcelable{
class Name {
#SerializedName("text")
#Expose
public String eventName;
public String getEventName() {
return eventName;
}
}
.
. some parcelable stuff here
.
}
I am trying to access the getEventName method from within my adapter class. my piece of code there goes like this ( cant access the method, geteventname):
holder.cardTextView.setText(eventsList.get(position).getEventName());
If i define another variable outside of an inner pojo class, i can reach its getter, i can only not reach the one within the pojo class.
Edit
I am trying to read a json response like this, the text under name is the one im trying to build the modal for.
"events": [
{
"name": {
"text": "textextextext",
"html": "textextextext"
},
"description": {}
.
.
.
Thank you in advance.
JSON nesting is fun.
name is an inner class. Looks like description is also.
events":[ { "name":{ "text":" text ", "html":"something " }, "description":{ }, ... }]
In the above, there is an array of events.
Every event has a name, and every name has a "text" and an "html".
Every event also has a description, which has it's own fields.
You are on the right track:
public class Event implements Parcelable{
#SerializedName("name")
#Expose
public Name name;
#SerializedName("description")
#Expose
public Description description;
public class Name {
#SerializedName("text")
#Expose
public String eventName;
public String getEventName() {
return eventName;
}
}
public class Description {
//whatever fields are in the description object in the json
}
.
. some parcelable stuff here
.
}
You would access it like: holder.cardTextView.setText(eventsList.get(position).name.getEventName());
If this works you can clean it up by adding custom getters to the event class.
holder.cardTextView.setText(eventsList.get(position).getEventName());
try this. use parentheses for function call
Try this getEventName() with parentheses :
holder.cardTextView.setText(eventsList.get(position).getEventName());

Retrofit returns valid list but items members are null

I have a problem pretty much the same as this: retrofit returning valid json but pojo is empty
But my variables are not declared as static. The are all declared like:
#SerializedName("name")
#Expose
private String name;
I have tried removing the annotations, but that doesn't work.
what could be the problem?
EDIT:
Interface:
#GET("/MyController/MyAction/{name}")
void getSomeData(#Path("name") String name, Callback<List<DataItem>> cb);
Can you show me the actual received data(JSON or XML)? It seems that your callback structure is not matching with your data. For example, it would be possible that your data may have array that have a name, and you ignored it.
In my case, I declared like this,
void getList(#Path("data") String data,//
Callback<OrderList> callback);
OrderList is:
public class OrderList {
List<Order> order_list;
}
And my data is:
{
"order_list":
[
{ "id": "1001", "data": "a" },
{ "id": "1002", "data": "b" }
]
}
I mean, it seems that your data may have nested structure and your class may not matching with that.

Practical use of #Ignore in Realm?

I've been trying to add Realm in my Android app. Their docs are pretty well explained & easy to follow. But it fails to explain this one particular area. I'm unable to figure out the practical use for the #Ignore annotation. I know that fields under this annotation are not persisted.
Can someone please share a few use cases. Also I wanted to know the scope of such fields. I mean, if I set an #Ignore field to some value, would that value be available to the other classes in my app for that particular launch session. If yes, then how do we access it? If no (which I guess is the case), then why do we need such a field anyway?
I've searched here and on web but couldn't find the relevant information. If out of my ignorance, I've missed upon some resource, please guide me to it.
Thanks.
Accordingly to the official documentation (see https://realm.io/docs/java/latest/) #Ignore is useful in two cases:
When you use GSON integration and your JSON contains more data than you want to store, but you still would like to parse it, and use right after.
You can't create custom getters and setter in classes extending RealmObject, since they are going to be overridden. But in case you want to have some custom logic anyway, ignored fields can be used as a hack to do that, because Realm doesn't override their getter & setters. Example:
package io.realm.entities;
import io.realm.RealmObject;
import io.realm.annotations.Ignore;
public class StringOnly extends RealmObject {
private String name;
#Ignore
private String kingName;
// custom setter
public void setKingName(String kingName) { setName("King " + kingName); }
// custom getter
public String getKingName() { return getName(); }
// setter and getter for 'name'
}
Ignored fields are accessible only from the object they were set in (same as with regular objects in Java).
UPDATE: As the #The-null-Pointer- pointed out in the comments the second point is out of date. Realm now allows having custom getters and setters in Realm models.
Here's a couple of real-world use cases:
1 - Get user's fullname:
public class User extends RealmObject {
private String first;
private String last;
#Ignore
private String fullName;
public String getFullName() {
return getFirst() + " " + getLast();
}
Get JSON representation of object:
public class User extends RealmObject {
private String first;
private String last;
#Ignore
private JSONObject Json;
public JSONObject getJson() {
try {
JSONObject dict = new JSONObject();
dict.put("first", getFirst());
dict.put("last", getLast());
return dict;
} catch (JSONException e) {
// log the exception
}
return null;
}
I've found it useful to define field names for when I am querying. For example
User.java
public class User extends RealmObject {
#Index
public String name;
#Ignore
public static final String NAME = "name";
}
And then later on I can do something like:
realm.where(User.class).equalTo(User.NAME, "John").findFirst();
This way if the schema changes from say name to id I don't have to hunt down every occurrence of "name".
Please see the the official documentation about #Ignore annotation:
The annotation #Ignore implies that a field should not be persisted to disk. Ignored fields are useful if your input contains more fields than your model, and you don’t wish to have many special cases for handling these unused data fields.

Parsing JSON with GSON

I'm having some trouble with GSON, mainly deserializing from JSON to a POJO.
I have the following JSON:
{
"events":
[
{
"event":
{
"id": 628374485,
"title": "Developing for the Windows Phone"
}
},
{
"event":
{
"id": 765432,
"title": "Film Makers Meeting"
}
}
]
}
With the following POJO's ...
public class EventSearchResult {
private List<EventSearchEvent> events;
public List<EventSearchEvent> getEvents() {
return events;
}
}
public class EventSearchEvent {
private int id;
private String title;
public int getId() {
return id;
}
public String getTitle() {
return title;
}
}
... and I'm deserializing with the following code, where json input is the json above
Gson gson = new Gson();
return gson.fromJson(jsonInput, EventSearchResult.class);
However, I cannot get the list of events to populate correctly. The title and id are always null. I'm sure I'm missing something, but I'm not sure what. Any idea?
Thanks
OK, I figured this out. I attest this to a long day of coding with little sleep the night before!
The "events" data structure contained multiple "events", which each contain an "event" type. I had to move the EventSearchEvent under a new class called EventContainer. This event container contained one field "event". This "event" was the "EventSearchEvent". THerefore, when GSON iterated over the JSON array, it saw the Container (which is of type "events") and then inside of that object it looked for a "event" member. When it finally found that it loaded up the id and title appropriately.
The short of it: I didn't have my object hierarchy built correctly.

Categories

Resources