Main file
Hello guys, I've to do something like this, as shown in the picture below -
but I don't know how to do this!!, And the thing is that document is not that clear to understand
and need someone to help me ...
UserSongUploadDetails user_song_upload_details = new UserSongUploadDetails(user_uid,song_artist_name_field_string,
song_artist_name_field_string,
song_description_field_string,
date_time_formatter,
song_firebase_url);
firebaseDatabase = FirebaseDatabase.getInstance();
user_song_database_refrence = firebaseDatabase.getReference("Users");
user_song_database_refrence.child(FirebaseAuth.getInstance().getUid()).setValue(user_song_upload_details);
Users.java file
putting all these values to setValue(), as you can see.
public class UserSongUploadDetails {
private String user_id;
private String song_name;
private String song_artist;
private String song_description;
private String song_upload_time_stamp;
private Uri song_storage_url;
UserSongUploadDetails(){
}
UserSongUploadDetails(String user_id, String song_name, String song_artist, String song_description, String song_upload_time_stamp, Uri song_storage_url){
this.user_id = user_id;
this.song_name = song_name;
this.song_artist = song_artist;
this.song_description = song_description;
this.song_upload_time_stamp = song_upload_time_stamp;
this.song_storage_url = song_storage_url;
}
public String getUser_id(){
return user_id;
}
public String getSong_name(){
return song_name;
}
public String getSong_artist(){
return song_artist;
}
public String getSong_description(){
return song_description;
}
public String getSong_upload_time_stamp(){
return song_upload_time_stamp;
}
public Uri getSong_storage_url() {
return song_storage_url;
}
Errors
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$200(CustomClassMapper.java:48)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.serialize(CustomClassMapper.java:676)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(CustomClassMapper.java:168)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$200(CustomClassMapper.java:48)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.serialize(CustomClassMapper.java:676)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(CustomClassMapper.java:168)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$200(CustomClassMapper.java:48)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.serialize(CustomClassMapper.java:676)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(CustomClassMapper.java:168)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$200(CustomClassMapper.java:48)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.serialize(CustomClassMapper.java:676)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(CustomClassMapper.java:168)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$200(CustomClassMapper.java:48)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.serialize(CustomClassMapper.java:676)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(CustomClassMapper.java:168)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$200(CustomClassMapper.java:48)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.serialize(CustomClassMapper.java:676)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(CustomClassMapper.java:168)
1. Match the class structure to the database structure
You need to match the structure between your custom Java Class and Database Structure. In your case, the Java Class structure is as follows:
public class User implements Serializable {
private String name;
private String email_id;
private AudioUpload audio_upload;
public class AudioUpload implements Serializable {
private String song_artist;
private String song_genre;
private String song_name;
private String song_url;
public AudioUpload(String song_artist, String song_genre, String song_name, String song_url) {
this.song_artist = song_artist;
this.song_genre = song_genre;
this.song_name = song_name;
this.song_url = song_url;
}
public String getSong_artist() {
return song_artist;
}
public void setSong_artist(String song_artist) {
this.song_artist = song_artist;
}
public String getSong_genre() {
return song_genre;
}
public void setSong_genre(String song_genre) {
this.song_genre = song_genre;
}
public String getSong_name() {
return song_name;
}
public void setSong_name(String song_name) {
this.song_name = song_name;
}
public String getSong_url() {
return song_url;
}
public void setSong_url(String song_url) {
this.song_url = song_url;
}
}
public User(String name, String email_id, AudioUpload audio_upload) {
this.name = name;
this.email_id = email_id;
this.audio_upload = audio_upload;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail_id() {
return email_id;
}
public void setEmail_id(String email_id) {
this.email_id = email_id;
}
public AudioUpload getAudio_upload() {
return audio_upload;
}
public void setAudio_upload(AudioUpload audio_upload) {
this.audio_upload = audio_upload;
}
}
In order to pass object to setValue(), your custom class must implements Serializable. Don't forget to add the Setter and Getter method, since the serialize and deserialize procedure will use it to construct your object. The important thing here is that the serialization procedure only care to your Setter method. So, even if you don't specify a variable as a class member, as long as there is Setter method exist, those variable with Setter method return type will be created in your database. And also, you need to match the name of Setter and Getter method to your database field name.
2. Set Value to Field
To set value to field, you only need to do the following:
User userObject = new User();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase.getInstance().getReference("users").child(uid).setValue(userObject);
Related
I was inserting some code to make a registration form, but iIfound this
class User {
private String Nama;
private String Kelas;
private int NIM;
public String getNama{
return Nama;
}
public String setNama{
}
}
The error message was all "variable is never read". Can someone explain why there is a message on this, and how I can fix it?
Though it is not clear where you use your codes, but the following is a java model class, with setter and getter method. Even it is not the direct answer of you question, but I have used this types of model class in my projects, one can find the idea of setter and getter from the following user class.
For using in various purposes You can create your User class as follows with constructors and setter and getter methods :
public class User {
private String Nama;
private String Kelas;
private int NIM;
public User() {
}
public User(String nama, String kelas, int NIM) {
Nama = nama;
Kelas = kelas;
this.NIM = NIM;
}
public String getNama() {
return Nama;
}
public void setNama(String nama) {
Nama = nama;
}
public String getKelas() {
return Kelas;
}
public void setKelas(String kelas) {
Kelas = kelas;
}
public int getNIM() {
return NIM;
}
public void setNIM(int NIM) {
this.NIM = NIM;
}
}
I am trying to call a stored procedure for my application using Microsoft SQL. However, when I run the stored procedure to pass back the contents of the object it fails. I have the objects as AVSApplication and in that class it has a list of variables and methods. I tried using an Iterable and a List but both produce the same error. I am not sure where I went wrong. I looked at other similar StackOverflow questions but I didn't get much from it.
Error:
java.lang.ClassCastException: java.base/[Ljava.lang.Object; cannot be cast to com.Mapping.AVSApplication
at com.Mapping.Employeecontroller.getAll(Employeecontroller.java:33) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~
Java Entity Code:
import java.util.*;
import javax.persistence.*;
#Entity
#NamedStoredProcedureQueries(value= {
#NamedStoredProcedureQuery(name= "procedure-one", procedureName= "GetAllAppWithStatus")
})
public class AVSApplication implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#Id
private String appcode;
private String acronym;
private String appname;
private String sys_id;
private String mapstatus;
private String sdg;
private String status;
private String statuscode;
//Constructor
public AVSApplication(String appcode, String acronym, String appname, String sys_id, String mapstatus,
String sdg, String status, String statuscode) {
super();
this.appcode = appcode;
this.acronym = acronym;
this.appname = appname;
this.sys_id = sys_id;
this.mapstatus = mapstatus;
this.sdg = sdg;
this.status = status;
this.statuscode = statuscode;
}
//Getters
public String getAppcode() {
return appcode;
}
public String getAcronym() {
return acronym;
}
public String getAppname() {
return appname;
}
public String getSys_id() {
return sys_id;
}
public String getMapstatus() {
return mapstatus;
}
public String getSdg() {
return sdg;
}
public String getStatus() {
return status;
}
public String getStatuscode() {
return statuscode;
}
//Setters
public void setAppcode(String appcode) {
this.appcode = appcode;
}
public void setAcronym(String acronym) {
this.acronym = acronym;
}
public void setAppname(String appname) {
this.appname = appname;
}
public void setSys_id(String sys_id) {
this.sys_id = sys_id;
}
public void setMapstatus(String mapstatus) {
this.mapstatus = mapstatus;
}
public void setSdg(String sdg) {
this.sdg = sdg;
}
public void setStatus(String status) {
this.status = status;
}
public void setStatuscode(String statuscode) {
this.statuscode = statuscode;
}
}
DAO:
#Repository
public class Employeedao {
#Autowired
private EntityManager em;
/**
* Method to fetch all employees from the db.
* #return
*/
#SuppressWarnings("unchecked")
public List<AVSApplication> getAllEmployees() {
return em.createNamedStoredProcedureQuery("procedure-one").getResultList();
}
}
Controller:
#RestController
public class Employeecontroller {
#Autowired
Employeedao edao;
/**
* Method to fetch all employees from the db.
* #return
*/
#RequestMapping(value= "/getall")
public void getAll() {
System.out.println("All objects: " + edao.getAllEmployees());
System.out.println("Get the first item in list: " + edao.getAllEmployees().get(0).getAppcode());
}
}
In given code there is nothing that would map rows returned by stored procedure AVSApplication instances:
#NamedStoredProcedureQueries(value= {
#NamedStoredProcedureQuery(name= "procedure-one", procedureName= "GetAllAppWithStatus")
})
If stored procedure matches nicely to entity, then definining result class can be enough:
#NamedStoredProcedureQueries(value= {
#NamedStoredProcedureQuery(
name= "procedure-one",
procedureName= "GetAllAppWithStatus",
resultClasses = {AVSApplication.class}
})
If there is some discrepancies, one must define SqlResultSetMapping and refer to it from resultsetMappings.
I am trying to assign the value returned by some function to a field in the deserialized class of json.
FileInfo.java
public class FileInfo {
#SerializedName("Name")
private String mName;
#SerializedName("Url")
private String mUri;
#SerializedName("Size")
private Integer mSize;
#SerializedName("ModTime")
private Long mModifiedTime;
private FileType mType;
#SerializedName("Children")
private ArrayList<FileInfo> mChildren = new ArrayList<>();
public ArrayList<FileInfo> getChildren() {
return mChildren;
}
public long getModifiedTime() {
return mModifiedTime;
}
public String getName() {
return mName;
}
public Integer getSize() {
return mSize;
}
public String getUrl() {
return mUri;
}
public FileType getType() {
return mType;
}
public void setChildren(ArrayList<FileInfo> mChildren) {
this.mChildren = mChildren;
}
public void setModifiedTime(long mModifiedTime) {
this.mModifiedTime = mModifiedTime;
}
public void setName(String mName) {
this.mName = mName;
}
public void setSize(Integer mSize) {
this.mSize = mSize;
}
public void setType(FileType mType) {
this.mType = mType;
}
public void setUri(String mUri) {
this.mUri = mUri;
}
#Override
public String toString() {
return FileInfo.class.toString();
}
public FileInfo() {
}
}
The mType needs to be assigned to foo(mName). I looked up custom deserializers and instance creators but none of those helped. I also thought of TypeAdapters which i feel defeats the purpose of keeping deserialization(using GSON) simple.
This is a sample JSON string that will be deserialized.
[
{
"Name":"Airport",
"Url":"http://192.168.2.2/api/sites/Baltimore%20Airport/Airport",
"Size":0,
"ModTime":"2015-12-02T14:19:17.29824-05:00",
"Children":null
}
]
P.S. I'm not sure if this should be done during deserialization but trying anyways. Also please let me know of alternative ways to achieve this.
I am new to implement Azure Mobile Service. I have refer the demo of ToDoItem given by Azure.
In same manner i have make class User for my own app. Then I am inserting the data in to the MobileServiceTable but it gives me error like below:
{"message":"The operation failed with the following error: 'A null store-generated value was returned for a non-nullable member 'CreatedAt' of type 'CrazyLabApp.Models.User'.'."}
I have not created any field like this as it is not created in ToDoItem demo as well. I have seen that there are 4 fields that are by Default created by the MobileServiceTable. createdAt is one of the field of that.
I am wonder about whats wrong i am doing.
Check my below Userclass:
public class User {
#com.google.gson.annotations.SerializedName("id")
private String ServiceUserId;
#com.google.gson.annotations.SerializedName("email")
private String Email;
#com.google.gson.annotations.SerializedName("firstname")
private String FirstName;
#com.google.gson.annotations.SerializedName("lastname")
private String LastName;
#com.google.gson.annotations.SerializedName("profilepic")
private String ProfilePic;
#com.google.gson.annotations.SerializedName("introduction")
private String Introduction;
#com.google.gson.annotations.SerializedName("website")
private String Website;
#com.google.gson.annotations.SerializedName("title")
private String Title;
#com.google.gson.annotations.SerializedName("_createdAt")
private Date CreatedAt;
#com.google.gson.annotations.SerializedName("coverimage")
private ArrayList<CoverImage> CoverImages;
/*public Date getCreatedAt() {
return CreatedAt;
}
public void setCreatedAt(Date createdAt) {
CreatedAt = createdAt;
}*/
#com.google.gson.annotations.SerializedName("followers")
private ArrayList<User> Followers;
#com.google.gson.annotations.SerializedName("likes")
private ArrayList<Likes> Likes;
#com.google.gson.annotations.SerializedName("collections")
private ArrayList<Collections> Collections;
#com.google.gson.annotations.SerializedName("comments")
private ArrayList<Comments> Comments;
#com.google.gson.annotations.SerializedName("stories")
private ArrayList<Story> Stories ;
//-------------- Methods
public ArrayList<Story> getStories() {
return Stories;
}
public void setStories(ArrayList<Story> stories) {
Stories = stories;
}
public ArrayList<com.promact.crazylab.model.Comments> getComments() {
return Comments;
}
public void setComments(ArrayList<com.promact.crazylab.model.Comments> comments) {
Comments = comments;
}
public ArrayList<com.promact.crazylab.model.Collections> getCollections() {
return Collections;
}
public void setCollections(ArrayList<com.promact.crazylab.model.Collections> collections) {
Collections = collections;
}
public ArrayList<com.promact.crazylab.model.Likes> getLikes() {
return Likes;
}
public void setLikes(ArrayList<com.promact.crazylab.model.Likes> likes) {
Likes = likes;
}
public ArrayList<User> getFollowers() {
return Followers;
}
public void setFollowers(ArrayList<User> followers) {
Followers = followers;
}
public ArrayList<CoverImage> getCoverImages() {
return CoverImages;
}
public void setCoverImages(ArrayList<CoverImage> coverImages) {
CoverImages = coverImages;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getWebsite() {
return Website;
}
public void setWebsite(String website) {
Website = website;
}
public String getIntroduction() {
return Introduction;
}
public void setIntroduction(String introduction) {
Introduction = introduction;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getProfilePic() {
return ProfilePic;
}
public void setProfilePic(String profilePic) {
ProfilePic = profilePic;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getServiceUserId() {
return ServiceUserId;
}
public void setServiceUserId(String serviceUserId) {
ServiceUserId = serviceUserId;
}
#Override
public boolean equals(Object o) {
return o instanceof User && ((User) o).ServiceUserId == ServiceUserId;
}
}
Also check below code the way i am inserting it:
final User u = new User();
u.setFirstName(mName);
u.setEmail(mEmail);
u.setProfilePic(mUrl);
mUserTable = mClient.getTable(User.class);
// Insert the new item
new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
final User entity = mUserTable.insert(u).get();
} catch (Exception e){
//createAndShowDialog(e, "Error");
System.out.println("Error: "+e.toString());
}
return null;
}
}.execute();
Please help me in this.
The "_createdat" column will be populated automatically by Azure Mobile Services so there is no need to include it in your model. Delete this property from the User class. Its presence is probably overwriting the auto-populated value with a null.
you can solve this problem by just deleting createdAt column from your user table in azure.
Why this error is coming :
I am not sure But I guess this error is coming because createdAt is a non-nullable member and you cannot left it null.
EDIT :
Another aspect of the system columns is that they cannot be sent by the client. For new tables (i.e., those with string ids), if an insert of update request contains a property which starts with ‘__’ (two underscore characters), the request will be rejected. The ‘__createdAt’ property can, however, be set in the server script (although if you really don’t want that column to represent the creation time of the object, you may want to use another column for that) – one way where this (rather bizarre) scenario can be accomplished. If you try to update the ‘__updatedAt’ property, it won’t fail, but by default that column is updated by a SQL trigger, so any updates you make to it will be overridden anyway.
for more info take a look here :-http://blogs.msdn.com/b/carlosfigueira/archive/2013/11/23/new-tables-in-azure-mobile-services-string-id-system-properties-and-optimistic-concurrency.aspx
I'm facing this task:
I have class A and class B. These two classes are different but almost the same.
I need to somehow merge them into 1 Single array of objects so I will be able to use them later in a list that combines both classes.
Class A:
public class Followers {
private String request_id;
private String number_sender;
private String state;
public String getRequest_id() {
return request_id;
}
public String getNumber_sender() {
return number_sender;
}
public String getState() {
return state;
}
}
Class B:
public class Following {
private String name;
private String state;
private String request_id;
public String getRequest_id() {
return request_id;
}
public String getName() {
return name;
}
public String getState() {
return state;
}
}
I've tried doing this next move:
Object[] obj1 = (Object[]) followers;
Object[] obj2 = (Object[]) followings;
Object[] completeArray = ArrayUtils.addAll(obj1, obj2);
Where followers and followings are both arrays of the corresponding classes. Then in my list adapter I use:
if (values[currentItem] instanceof Followers) { BLA BLA BLA}
else if (values[currentItem] instanceof Following) { BLA BLA BLA}
But I get this exception:
Caused by: java.lang.ArrayStoreException: source[0] of type json.objects.Following cannot be stored in destination array of type json.objects.Followers[]
What will be the best way to merge two arrays of different objects into one array?
Will just implementing the same interface between them do the job and then they will basically be in an array of the interface type?
what other ways do you recommend?
Try this
Object[] completeArray = new Object[0];
completeArray = ArrayUtils.addAll(completeArray, obj1);
completeArray = ArrayUtils.addAll(completeArray, obj2);
If you make both classes implement a common interface you can manipulate arrays/lists of them as if they contains instances of the interface.
public interface Follow {
public String getRequest_id();
public String getState();
}
public class Follower implements Follow {
private String request_id;
private String number_sender;
private String state;
public String getRequest_id() {
return request_id;
}
public String getNumber_sender() {
return number_sender;
}
public String getState() {
return state;
}
}
public class Following implements Follow {
private String name;
private String state;
private String request_id;
public String getRequest_id() {
return request_id;
}
public String getName() {
return name;
}
public String getState() {
return state;
}
}
public void test() {
List<Follow> all = new ArrayList<>();
all.add(new Following());
all.add(new Follower());
for ( Follow f : all ) {
String id = f.getRequest_id();
String state = f.getState();
}
}
Alternatively you could put them in a hierarchy:
public class Entity {
private String request_id;
private String state;
public String getRequest_id() {
return request_id;
}
public String getState() {
return state;
}
}
public class Follower extends Entity {
private String number_sender;
public String getNumber_sender() {
return number_sender;
}
}
public class Following extends Entity {
private String name;
public String getName() {
return name;
}
}
public void test() {
List<Entity> all = new ArrayList<>();
all.add(new Following());
all.add(new Follower());
for ( Entity f : all ) {
String id = f.getRequest_id();
String state = f.getState();
}
}
Or you could make the extra fields into attributes.
enum Attribute {
Follows,
Followed;
}
public static class Entity {
private String request_id;
private String state;
EnumMap<Attribute, String> attributes = new EnumMap<>(Attribute.class);
public String getRequest_id() {
return request_id;
}
public String getState() {
return state;
}
// Factory to make entities.
static Entity make(Attribute attribute, String value) {
Entity e = new Entity();
e.attributes.put(attribute, value);
return e;
}
}
public void test() {
List<Entity> all = new ArrayList<>();
all.add(Entity.make(Attribute.Follows, "Fred"));
all.add(Entity.make(Attribute.Followed, "Gill"));
for (Entity f : all) {
String id = f.getRequest_id();
String state = f.getState();
}
}
There are an infinite number of possibilities.
USE concat
var combined= obj1.concat(obj2); // Merges both arrays
Try this.
private Object[] appendObj(Object[] obj, Object newObj) {
ArrayList<Object> temp = new ArrayList<Object>(Arrays.asList(obj));
temp.add(newObj);
return temp.toArray();
}