Model class for Firebase Database - java

Currently I have this model class to collect data from firebase database. To show the data I am using firebaserecycleradapter.
News.class
public class News {
private String message, author, thumb_author, type;
private Long timestamp;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getThumb_author() {
return thumb_author;
}
public void setThumb_author(String thumb_author) {
this.thumb_author = thumb_author;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
}
But the problem is there is another child named images that consist of pushId and an Object. This is how it looks
news {
message:"value"
author:"value"
thumb_author:"value"
type:"value"
timestamp:"value"
images {
pushId01:"value"
pushId02:"value"
pushId03:"value"
pushId04:"value"
pushId05:"value"
}
}
So my question is how can I add the image child to the news.class or is there any possible solution for this? My possible solution for this is to get the image child data inside the onBindViewHolder using databasereference.

Add a property to represent the images node. Since these are simple string key/value pairs, you can represent it with a Map<String,String>. So:
public class News {
private String message, author, thumb_author, type;
private Long timestamp;
public Map<String,String> images; // this is a new field for the images
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
...

Related

#ResponseBody, don't respect the constructors of an object

I have a #restController type controller, when I access a resource for a request I get a json as a response, the problem is that all attributes appear to me and it does not respect the constructors I have generated.
However, all the attributes of the class always appear to me:
{
"code":0,
"message":"ERROR",
"details":null
}
And I would like the answer to be like this:
{
"code":0,
"message":"ERROR"
}
I appreciate your help
#RestController
#RequestMapping("/api")
public class WsController implements WsInterface{
#Override
#PostMapping("/add")
public Response add(#RequestBody Person person) {
Response r= =null;
if(person.getName().equals("A")){
r= new Response(1,"OK","Details of person");
}else{
r= new Response (0,"ERROR");
}
return r;
}
}
public class Response{
private int code;
private String message;
private String details;
public Response() {
}
public Response(int code, String message, String details) {
this.code = code;
this.message = message;
this.details = details;
}
public Response(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
If you want to use same object in both cases with null details and without. You can try to configure json serialization accordingly.Spring by default use Jackson and you can configure object mapper directly or use annotation #JsonInclude(Include.NOT_NULL) on model class to include only not null values.

Firestore can't convert Document toObject

Im trying to retrieve a Document but I just can't get it to work. Here is my Code:
fm.getColRefProgramms().document(programmKey).collection("items").document("HIXQobZtlMxn4OblgOMi").get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String s = documentSnapshot.getId();
OverviewItem item = documentSnapshot.toObject(OverviewItem.class);
item.setKey(item.getKey());
}
});
String s return the correct Id, so the Document is found and loaded from the Database but it canĀ“t create a OverviewIdem Object from it.
I get this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Constructor.newInstance(java.lang.Object[])' on a null object reference
And this is the OverviewItem Class:
public class OverviewItem implements IProgrammItem, Serializable{
private String instance;
private String key;
private Programm programm;
private ArrayList<BasicElement> elements;
public OverviewItem() {}
public void setInstance(String instance) {
this.instance = instance;
}
public String getInstance() {
return instance;
}
#Exclude
public Programm getProgramm() {
return programm;
}
#Exclude
public String getKey() {
return key;
}
#Exclude
public void setKey(String key) {
this.key = key;
}
#Exclude
public void setProgramm(Programm programm) {
this.programm = programm;
}
public ArrayList<BasicElement> getElements() {
return elements;
}
public void setElements(ArrayList<BasicElement> elements) {
this.elements = elements;
}
}
And this is my Document:
FIX: I waited for half an hour, then it started to retrieve the data (Date's value was retrieved and wasn't null anymore). Maybe the database takes time to update, so give it some time (if you added a new value or document) and then check again.
I'm facing the same issue. This is my code:
firebasefirestore.collection("events").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot documentSnapshots, #Nullable FirebaseFirestoreException e) {
for(DocumentChange doc: documentSnapshots.getDocumentChanges()){
if(doc.getType() == DocumentChange.Type.ADDED){
Map<String, Object> a = doc.getDocument().getData();
HomeViewModel event = doc.getDocument().toObject(HomeViewModel.class);
eventlist.add(event);
eventRecyclerAdapter.notifyDataSetChanged();
}
}
}
});
Here I created a variable 'a' to see the data, and the data is being successfully retrieved from Firestore (I was checking in the debugger).
Value of a
However when I use toObject(), Date is null.
My HomeViewModel class:
public class HomeViewModel{
private String Date;
private String Description;
private String Imagepath;
private String Title;
public void setDate(String date) {
this.Date = date;
}
public String getDate() {
return Date;
}
public String getImagepath() {
return Imagepath;
}
public void setImagepath(String imagepath) {
Imagepath = imagepath;
}
public void setDescription(String description) {
Description = description;
}
public void setTitle(String title) {
Title = title;
}
public String getDescription() {
return Description;
}
public String getTitle() {
return Title;
}
public HomeViewModel(){
}
public HomeViewModel(String title, String desc, String date, String imagepath) {
this.Title = title;
this.Description = desc;
this.Date = date;
this.Imagepath = imagepath;
}
}
Therefore it is clear that toObject is the problem.

Creating a model class of a child node firebase

How to create a model class with this firebase structure?
So the first node inside the group_messages is UserId inside that is Group_id and inside that is the message_id.
I want to get all the group_message data and display it to my app. So I am using RecyclerView.Adapter and in order to do that I need to have a model class.
This is my model class (GroupMessages.java)
public class GroupMessages {
//TODO: Get the list of seen node;
private String message, from, type;
private long time;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}

How to Parse below XML using java?

Iam trying to get Status and message tag info using java 1.7
Please any guide me ,
Thanks in advance
<API version="0.0">
<response>
<operation name="ADD">
<result>
<statuscode>200</statuscode>
<status>Success</status>
<message> successfully</message>
</result>
<Details type="ADD"/>
</operation>
</response>
</API>
This is not a JSON response that you are getting, it's an XML response,
you just need to convert the XML response to POJO class and use the POJO class instead.
Here is how the POJO class will look like
public class MyPojo{
private API API;
public API getAPI() {
return API;
}
public void setAPI(API API) {
this.API = API;
}
}
now MyPojo will contain another class named API
public class API {
private Response response;
private String version;
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
now the API class contains another class called Response
public class Response {
private Operation operation;
public Operation getOperation() {
return operation;
}
public void setOperation(Operation operation) {
this.operation = operation;
}
}
Now the Response class is containing another class called Operation
public class Operation {
private Result result;
private Details Details;
private String name;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public Details getDetails() {
return Details;
}
public void setDetails(Details Details) {
this.Details = Details;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now you guessed it the Operation class is containing two classes Details and Result
Here is the Result class that is containing the status and message you want to access
public class Result {
private String message;
private String status;
private int statuscode;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getStatuscode() {
return statuscode;
}
public void setStatuscode(int statuscode) {
this.statuscode = statuscode;
}
}
Here is the Details class
public class Details {
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
finally, you can access the status and message by creating an object from MyPojo class like this:
String message = myPojo.getAPI().getResponse().getOperation().getResult().getMessage();
String status = myPojo.getAPI().getResponse().getOperation().getResult().getStatus();
you can use this online converter to convert XML/JSON to POJO.
I hope my answer was helpful :)

Duplicated attribute in Firebase

I have a model NewsFeedItem like this:
public class NewsFeedItem {
#PropertyName("like_number")
protected int likeCount = 0;
#PropertyName("time")
protected long timestamp;
#PropertyName("ownerUid")
protected String ownerUid;
#PropertyName("ownerUsername")
protected String ownerUsername;
#PropertyName("comments")
protected List<Comment> comments;
#PropertyName("likes")
protected Set<String> likes; //Store user uid of who like this status
public NewsFeedItem() {
}
protected NewsFeedItem(int likeCount, long timestamp, String ownerUid, String ownerUsername, List<Comment> comments, Set<String> likes) {
this.ownerUid = ownerUid;
this.ownerUsername = ownerUsername;
this.likeCount = likeCount;
this.timestamp = timestamp;
this.comments = comments;
this.likes = likes;
}
public int getLikeCount() {
return likeCount;
}
public void setLikeCount(int likeCount) {
this.likeCount = likeCount;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String getOwnerUid() {
return ownerUid;
}
public void setOwnerUid(String ownerUid) {
this.ownerUid = ownerUid;
}
public String getOwnerUsername() {
return ownerUsername;
}
public void setOwnerUsername(String ownerUsername) {
this.ownerUsername = ownerUsername;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
public Set<String> getLikes() {
return likes;
}
public void setLikes(Set<String> likes) {
this.likes = likes;
}
}
Then I subclass it in Status model:
#IgnoreExtraProperties
public class Status extends NewsFeedItem {
#PropertyName("content")
protected String content;
#PropertyName("photo")
protected String photoUrl;
public Status() {
//Required for deserialize
}
public Status(String ownerUid, String ownerUsername, String content, String photoUrl, int likeCount, long timestamp, List<Comment> comments, Set<String> likes) {
super(likeCount, timestamp, ownerUid, ownerUsername, comments, likes);
this.content = content;
this.photoUrl = photoUrl;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
}
The code pushing data to Firebase:
#Override
public void pushStatusToFirebase(Status status) {
database.getReference("status").push().setValue(status);
}
But when I push to Firebase the like_number and likeCount display together like this:
It also happen to all of my model class. Please help me.
To solve this, you need to make all your fields public and not protected as they are now, otherwise the annotations will not work.
Now, the annotation takes into account both the field name as well as the getter/setter names to serialize. You have this problem because the fields as well as the getter/setters were getting serialized and that's why are resulting duplicates.
So use the annotation on the field name which are public and ignore the getter/setters. This will solve your problem. Your data will be properly serialized with the property name you want and there will be no duplicates as well.
Try to mark with #PropertyName your getters instead of fields. Another option that may be working - mark with #Exclude your getters.

Categories