Variable "Name" is not readable, how can I fix it? - java

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;
}
}

Related

How to add Value child in child in Firebase?

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);

Firebase: No properties to serialise - Android

I'm running into problems trying to read and write data to/from my Firebase realtime database. I have a register and login activity. When I register a user, I want to authenticate them and add the User's data to the database.
Here is my User class:
public class myUser {
public static boolean onlineStatus;
public static int userAge;
public static String userGender;
public static String userId;
public static String userName;
public myUser() {
}
//Default constructor will have/set the default info for the users such as:
//(auto generated) id name, age, and gender initialised at creation time
public myUser(boolean onlineStatus, int userAge, String userGender, String userId, String userName ) {
this.onlineStatus = onlineStatus;
this.userAge = userAge;
this.userGender = userGender;
this.userId = userId;
this.userName = userName;
}
//Getters
public static String getUserId() {
return userId;
}
public static String getUserName() {
return userName;
}
public static int getUserAge() {
return userAge;
}
public static String getUserGender() {
return userGender;
}
public static boolean getOnlineStatus() {
return onlineStatus;
}
//Setters
public static void setOnlineStatusTrue() {
onlineStatus = true;
}
public static void setOnlineStatusFalse() {
onlineStatus = false;
}
}
Now when I set a Database reference to my User object like so:
String id = databaseUsers.push().getKey();
myUser userRef = new myUser(onlineStatus, age, gender, id, name );
databaseUsers.setValue(userRef);
Now when I go register a user in my register activity my App crashes and I get the following error:
No properties to serialise:
(https://puu.sh/A08NT.png
I've also added some ProGuard rules but I still get the same error.
-keepattributes Signature
-keepclassmembers class com.example.teamc.friendfinder.** {
*;
}
All I would like to do is to register a user, add them to the database and set their online status to False. Then when the user signs in I'd like to set it to True so I'm able to get their online status activity and update the UI.
To solve your problem, please use the following steps.
Change all your fileds from your model class from public static to private.
private boolean onlineStatus;
private int userAge;
private String userGender;
private String userId;
private String userName;
Change all your setters and getters from your model class from public static to only public.

Object become null when converted to json

Here is the problem, when I send my object to server using retrofit I got it null. I'm doing this to create the json object:
HashMap<String, UserModel> map = new HashMap<>();
map.put("user", user);
But, when the json arrives in the server I got something like this:
{"user":null}
Then I printed ny json file with this line:
Log.d("TAG", new JSONObject(map).toString());
And I saw the same null object.
So, here is my question, Why is this happening? And how can I fix that?
Here goes some information about my project:
Retrofit version: 2.0.0
Retrofit serializer: jackson version 2.0.0
using also jackson to convert JodaTime version 2.4.0
here goes how I get retrofit instance:
public T buildServiceInstance(Class<T> clazz){
return new Retrofit.Builder().baseUrl(BuildConfig.API_HOST)
.addConverterFactory(JacksonConverterFactory.create())
.build().create(clazz);
}
I call that method here:
public static final IUserApi serviceInstance = new ApiBuildRequester<IUserApi>()
.buildServiceInstance(IUserApi.class);
Method declaration on interface IUserApi:
#POST("User.svc/Save")
Call<ResponseSaveUserApiModel> save(#Body HashMap<String, UserModel> map);
And at last, but I guess, not less important:
public class UserModel implements Parcelable {
private String idUser;
private String name;
private String email;
#JsonProperty("password")
private String safePassword;
private String salt;
private String phoneNumber;
private String facebookProfilePictureUrl;
private String facebookUserId;
public UserModel() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdUser() {
return idUser;
}
public void setIdUser(String idUser) {
this.idUser = idUser;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSafePassword() {
return safePassword;
}
public void setSafePassword(String safePassword) {
this.safePassword = safePassword;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getFacebookProfilePictureUrl() {
return facebookProfilePictureUrl;
}
public void setFacebookProfilePictureUrl(String facebookProfilePictureUrl) {
this.facebookProfilePictureUrl = facebookProfilePictureUrl;
}
public String getFacebookUserId() {
return facebookUserId;
}
public void setFacebookUserId(String facebookUserId) {
this.facebookUserId = facebookUserId;
}
#Override
public int describeContents() {
return 0;
}
public UserModel(Parcel in) { // Deve estar na mesma ordem do "writeToParcel"
setIdUser(in.readString());
setName(in.readString());
setEmail(in.readString());
setSafePassword(in.readString());
setPhoneNumber(in.readString());
setFacebookProfilePictureUrl(in.readString());
setFacebookUserId(in.readString());
}
#Override
public void writeToParcel(Parcel dest, int flags) { //Deve estar na mesma ordem do construtor que recebe parcel
dest.writeString(idUser);
dest.writeString(name);
dest.writeString(email);
dest.writeString(safePassword);
dest.writeString(phoneNumber);
dest.writeString(facebookProfilePictureUrl);
dest.writeString(facebookUserId);
}
public static final Parcelable.Creator<UserModel> CREATOR = new Parcelable.Creator<UserModel>(){
#Override
public UserModel createFromParcel(Parcel source) {
return new UserModel(source);
}
#Override
public UserModel[] newArray(int size) {
return new UserModel[size];
}
};
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
}
Debug screen:
#Selvin and #cricket_007 You are the best!
I got this using your hint that my printing was wrong, and I found the solution.
I have two types of users in my app, facebook users or native users, two forms, but just one object, and here was the problem, when I sent facebook objects (complete) it worked fine, but when I tried to send native users, with some null properties, it crashed my serialization.
So I had to check every property before send it, it's just a workaround, but for now it's enough, thank you a lot folks!

Assign one json value for two fields in java using GSON

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.

AzureMobileService: Insert data in to table gives exception

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

Categories