Write new Data in Android Firebase Database - android

I am using Firebase Database in an Android application, and everytime a user is registred I store some values in the database for this purpose I am doing what follows:
database = FirebaseDatabase.getInstance();
DatabaseReference mRef = database.getReference().child("Users").push();
FirebaseUser user = mAuth.getCurrentUser();
String userId = user.getUid();
mRef.child("User").child("age").setValue(selectedAge);
mRef.child("User").child("gender").setValue(finalGender);
mRef.child("User").child("userId").setValue(userId);
mRef.child("User").child("username").setValue(username);
but when I go to my firebase console I see that a kind of id is automaticaly generated which I do not need since as you can see in the image I set my own id.
Is there a way to avoid this, and create nodes like the second User node in the image ??
NOTE: the second user node i added it manualy

To directly answer your question here is the change I'd suggest:
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String userId = user.getUid();
DatabaseReference mRef = database.getReference().child("Users").child(userId);
mRef.child("age").setValue(selectedAge);
mRef.child("gender").setValue(finalGender);
mRef.child("username").setValue(username);
I'd also suggest that you create a Java class to represent whatever user data you want to store in your database. Taking advantage of Firebase's ability to read/write to your database using Java classes will make those operations much easier. For example you add a User class to your project like the following:
public class User {
public double age;
public String gender;
public String userName;
//required default constructor
public User() {
}
public User(double age, String gender, String userName) {
this.age = age;
this.gender = gender;
this.userName = userName;
}
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
By using a java class to write to your database you can update your write operation like so:
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String userId = user.getUid();
User user = new User(26, "M", "user001");
DatabaseReference mRef = database.getReference().child("Users").child(userId);
mRef.setValue(user);
Notice there is no field to the store user's uid in the Java object. This is up to you but I did not include it for two reasons. First, in the database we are using the user's uid as the key to store there data in a unique location. Second, since you are using Firebase Authentication, in your app if you need to get the id of the currently signed in user you can access it via FirebaseAuth.

Just change this line:
DatabaseReference mRef = database.getReference().child("Users").push();
to this:
DatabaseReference mRef = database.getReference().child("Users");
The push() automatically adds a unique key.

Related

Searching in firebase database returns null value

I am working on an app where I have to fetch the status of a message from the database, but whenever I try to fetch and display data, the app crashes back to home screen.
user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
database = FirebaseDatabase.getInstance();
String msg = textView.getText().toString().trim();
DatabaseReference myRef = database.getReference();
myRef.child("Users").child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot db : dataSnapshot.getChildren()) {
if(db.getKey().equals(textView.getText().toString().trim())) {
count=1;
String key = db.getKey();
String key2= db.child(key).child("status").getValue(String.class);
Toast.makeText(CheckMsg.this,key2, Toast.LENGTH_SHORT).show();
}
}
}
Database Format
You should modify the key2 statement to
String key2= db.child("status").getValue(String.class);
OR
String key2= dataSnapshot.child(key).child("status").getValue(String.class);
db is already a child as it is an element of getChildren()(like abc and all) and you are trying to find a child of abc with the name abc.
I am assuming the crash is because key2 is null:
In the for loop:
Change this:
String key2= db.child(key).child("status").getValue(String.class);
to this:
String key2= db.child("status").getValue(String.class);
After Reading your Details Provided.
Issues-
1) Update the key as
String key2=db.child("status").getValue(String.class);
Try this. If this doesn't Work, comment below...

Updating Firebase Database Data with android

I am using this method to store data in my firebase database:
First i store all the data in a Model Class, called SubjectDataModel,
then i get the push key from the firebase database.
and then i set value to that particular key.
Here is my code :
SubjectDataModel:
public class SubjectDataModel {
public String id;
public String dbName;
public String subName;
public String tagline;
public int preference;
public SubjectDataModel()
{
}
public SubjectDataModel(String id, String dbName, String subName, String tagline, int preference) {
this.id = id;
this.dbName = dbName;
this.subName = subName;
this.tagline = tagline;
this.preference = preference;
}
}
Then i use the following code to push it to the database and then i also store the key id locally.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Data");
String id = ref.push().getKey();
SubjectDataModel newSub = new SubjectDataModel(id, txt_dbName, txt_subName, txt_tagline, txt_preference);
ref.child(id).setValue(newSub);
Now imagine, later in time, i want to update this data,
so i have the key id stored, so i can access it, i also have edited all the other data locally, so now if i make a SubjectDataModel Object with that data and again do ref.child(id).setValue(newSub); with the stored id, will the data be updated ? Or is there any other method to do so ?
updateChildren() is the method you are looking for, refer this documentation Firebase Read and Write Data on Android
Here's an example from documentation...
private void writeNewPost(String userId, String username, String title, String body) {
// Create new post at /user-posts/$userid/$postid and at
// /posts/$postid simultaneously
String key = mDatabase.child("posts").push().getKey();
Post post = new Post(userId, username, title, body);
Map<String, Object> postValues = post.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/posts/" + key, postValues);
childUpdates.put("/user-posts/" + userId + "/" + key, postValues);
mDatabase.updateChildren(childUpdates);
}
Okay, so i tried this and it works perfectly, like i expected it to. No need for me to use maps or anything. Simplest way to update data.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Data");
SubjectDataModel newSub = new SubjectDataModel(idForUpdate, txt_dbName, txt_subName, txt_tagline, txt_preference);
ref.child(idForUpdate).setValue(newSub);
So here basically, i created the object with the required data, and pushed it back to the same id with which i created a node in the firebase database, so it updates that same node with the new values.

Data is not showing(not uploading) in firebase database in android studio

This is my code and I am uploading a student name and batch name to firebase database. This method is excecuted after user created the account successfully.
User is created in Authentication but data is not uploaded to database and the only error in logcat is:
E/SpellCheckerSession: ignoring processOrEnqueueTask due to unexpected mState=TASK_CLOSE scp.mWhat=TASK_CLOSE
private void uploadUserDetails(){
String name = studentName.getText().toString();
String batch = "BCA";
database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference(firebaseAuth.getUid());
Student student = new Student(name,batch);
ref.child("Student Details").setValue(student);
}
public class Student {
public String name;
public String batch;
Student(){
this.name= "Hello";
this.batch="Unspecified";
}
Student(String name,String batch){
this.name=name;
this.batch=batch;
}
}
The following snippet uses a map for storing the student name and his batch, in this map key is string and value is of object type. and putting a value of key "l".
Map<String, Object> updates = new HashMap<>();
updates.put("l", Arrays.asList(student.batch,student.name));
ref.child("Student Details").setValue(updates);

Retrieve User Data Firebase on Android

Is there a way to retrieve data from a specific user who is authenticated via firebase through ID?
For example to retrieve information like name, photo etc.
Thanks in advance.
This is more of a port of the iOS answer i have given here
Firebase provides authentication for users using the FIRAuth Clases/API
However they can't be edited with custom fields like the Firebase Database.
To allow custom fields for user, you need to duplicate users in the Database with the same unique uid you receive in the auth of the user. Something like this
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
String name = user.displayName;
String email = user.email;
String photoUrl = user.photoURL;
String uid = user.uid;
FirebaseDatabase database = FirebaseDatabase.getInstance();
String key = database.getReference("users").push().getKey();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put( "uid", uid);
childUpdates.put( "name", name);
// other properties here
database.getReference("users").updateChildren(childUpdates, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
}
}
});
}
We push it at the users end point in our db and with the uid key by the following line /users/\(key).
Now you can retrieve users detail from your database by querying anywhere in your code.

android: cache gson data in sqlite database

I want to use a local sqlite database to cache all gson objects. Therefore I created some Gson classes like this one:
package com.getbro.bro.Json;
import com.google.gson.annotations.SerializedName;
public class User extends Item {
public User(String Sex, String UserName, String[] Followed){
this.Sex = Sex;
this.UserName = UserName;
this.Followed = Followed;
}
#SerializedName("sex")
public String Sex;
#SerializedName("username")
public String UserName;
#SerializedName("followed")
public String[] Followed;
#Override
public String toString() {
return UserName;
}
}
Now I want to use this class as Sugar ORM model, but then, I have to rewrite the constructor to something like this:
public User(Context c, String Sex, String UserName, String[] Followed){
this.Sex = Sex;
this.UserName = UserName;
this.Followed = Followed;
}
How can I get Gson to use this "special" constructor and select the wright context?
With 1.3 release, sugar doesn't require a Context parameter in the constructor. So, it makes easy for Gson classes to use Sugar.
Specifically with Gson, you could use their custom serializers in case you don't have the default constructor. More details here.. https://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserialization

Categories

Resources