Database Structure:
appname/users/userID/personal/Name
The child "name" is upadated in the database but is returning as null.
mChildReference = FirebaseDatabase.getInstance().getReference().child("users").child(uid).child("personal"); //DatabaseReference
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
User post = dataSnapshot.getValue(User.class);
Toast.makeText(MainActivity.this, "Name: "+post.uname+"dob: "+post.udob+"phno: "+post.phone_number+"email: "+post.uemail, Toast.LENGTH_LONG).show();
Log.e("RETRIEVED DATA", "Name: "+post.getUname()+"dob: "+post.getDob()+"phno: "+post.getPhone_number()+"email: "+post.getEmail());
Log.e("DEBUG",dataSnapshot.getKey());
fname.setText(post.getUname());
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.e("DEBUG", "loadPost:onCancelled", databaseError.toException());
// [START_EXCLUDE]
Toast.makeText(MainActivity.this, "Failed to load post.",
Toast.LENGTH_SHORT).show();
// [END_EXCLUDE]
}
};
mChildReference.addValueEventListener(postListener);
mPostListener = postListener;
If the database is acting wierd, make sure you double-check your database rules. You can try to make them public for now. I find this useful when I am developing.
In the Firebase Console, click Database -> RULES
Set all permissions to public (Warning anyone
can read and write!)
// These rules give anyone, even people who are not users of your app,
// read and write access to your database
{
"rules": {
".read": true,
".write": true
}
}
Try the query on Android again and see if it works.
Related
I wish to add fields in my firebase without overwriting it.
As you can see below, the user for my app will screen their emotions and the emotion will be uploaded to firebase.
Actually, user will be screened many times and each time they will get different emotions or same emotions.
Lets say the user screened their face and get Happiness, Sadness, Happiness respectively.
I wish to have my fields in the firebase console like this:
FaceEmotion: Happiness
FaceEmotion: Sadness
FaceEmotion: Happiness
Using my code below, at this moment I only get to overwrite the (FaceEmotion:) with same emotion values but not adding values as I wish like above. I've tried using array but I guess the problem is because the fieldname "FaceEmotion" is the same.
Is there a way for me to let Firestore generate autoID for the fieldname "FaceEmotion"? like maybe to have something like this:
FaceEmotion1: Happiness
FaceEmotion2: Sadness
FaceEmotion3: Happiness
String Emotion = EmotionType.toString();
userID = fAuth.getCurrentUser().getUid();
FaceEmotion = "FaceEmotion";
Map<String,Object> user = new HashMap<>();
user.put("FaceEmotion",Emotion);
DocumentReference documentReference = fStore.collection("users").document(userID).collection("FaceEmotion").document(FaceEmotion);
documentReference.update("FaceEmotion",FieldValue.arrayUnion(user)).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: Data has been saved "+ userID);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.toString());
}
});
The issue is on how you are writing to the document, the solution is to create a new document for every new emoton, this way you will be able to add emotions to that collection.
The code to write the emotions with this modification would be something like:
String emotion = EmotionType.toString();
userID = fAuth.getCurrentUser().getUid();
faceEmotion = "FaceEmotion";
Map<String,Object> val = new HashMap<>();
val.put("FaceEmotion",emotion);
DocumentReference documentReference = fStore.collection("users").document(userID).collection("FaceEmotion").document();
documentReference.set(val).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: Data has been saved "+ userID);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.toString());
}
});
I'm trying to add data to a document to Firebase Firestore. I've added a collection named users to it. Also the read/write permissions are open for now. I'm following this doc. And I'm not able to add data to document.
Here is what I'm trying to do:
private void getNewUserSnapShot() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
Log.d(TAG, "getNewUserSnapShot: user_uid: " + user.getUid());
DocumentReference user_doc_ref = db.collection("users").document();
Log.d(TAG, "getNewUserSnapShot: document ref: " + user_doc_ref.getId());
Map<String, Object> user_data = new HashMap<>();
user_data.put("name", user.getDisplayName());
user_data.put("email", user.getEmail());
user_data.put("profile_url", user.getPhotoUrl());
Log.d(TAG, "getNewUserSnapShot: user_data: " + user_data.toString());
user_doc_ref
.set(user_data)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(LoginActivity.this, task.toString(), Toast.LENGTH_LONG).show();
if (task.isSuccessful()) {
Log.d(TAG, "getNewUserSnapShot: success");
} else {
Log.d(TAG, "getNewUserSnapShot: failed");
}
}
});
}
In Logs I see only these (neither the log for failure nor for success):
2020-03-04 19:48:47.489 30744-30744/com.example.expenditure D/LoginActivity: getNewUserSnapShot: user_uid: iXOzfju6kORnhuUND8zFCPTzxY93
2020-03-04 19:48:47.499 30744-30744/com.example.expenditure D/LoginActivity: getNewUserSnapShot: document ref: 7AluPzcYMLzDKLh8YtBt
2020-03-04 19:48:47.499 30744-30744/com.example.expenditure D/LoginActivity: getNewUserSnapShot: user_data: {profile_url=https://someurl/security/reasons, name=Nikhil Wagh, email=null}
And when I see firebase console, I can't find the document with ID 7AluPzcYMLzDKLh8YtBt, according to logs which should have been created.
There is a similar question: Unable to add information to Cloud Firestore But it doesn't have right answers.
Can someone help. What am I doing wrong?
The issue was user.getPhotoUrl() returns url, but Firestore doesn't support urls. The url needs to be casted as a string, and then it works.
Cast your urls to string before adding data to Firestore.
I´m trying to connect two Apps to same database project with firebase, I can create a new user into new application to the same database but when I try to retrieve data valueeventlistener always return null after few seconds, I check already google-services.json and two files are different, packages and ids, is there someone with same problem?
Query query = myRef.child("xxxx/").orderByChild("xxxx").equalTo(Utils.decodeEmail(userEmail));
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String stLogoUrl;
stLogoUrl = dataSnapshot.child("imageEncode").getValue(String.class);
try {
if (stLogoUrl!=null) {
bitmapPhotoProfile[0] = decodeFromFirebaseBase64(stLogoUrl);
} else {
}
imgLogo.setImageBitmap(bitmapPhotoProfile[0]);
} catch (Exception e){
e.printStackTrace();
}
}
Ok I am a running into a weird problem with firestore
I have the following structure
collection1 -> document1- >collection2
I am adding a new document to collection2 with on complete listener( I tried the success listener as well). No errors are shown. The new document is not shown on the console. The listener is not being called. However, when I query, I get ALL the added documents including the new ones. What's going on here?
Map<String, Object> data = new HashMap<>();
data.put("completed", true;
data.put("date_completed", new Date());
data.put("location", "123 main st");
data.put("notes", "");
data.put("work", "");
db.collection("collection1").document(document1).collection("collection2")
.add(data)
.addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
if (task.isSuccessful()) {
DocumentReference documentReference = task.getResult();
Log.d(TAG, "DocumentSnapshot written with ID: " + documentReference.getId());
det.setDocId(documentReference.getId());
addr_arr.add(det);
} else {
Log.w(TAG, "Error adding document", task.getException());
Toast.makeText(EditListActivity.this, "Failed operation - " + task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
}
});
Here is the query I do
CollectionReference collecRef = db.collection("collection1").document(document1).collection("collection2");
collecRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
// here I do document.get on all the fields, add them to object and add object to array
}
adapter.notifyDataSetChanged();
} else {
Log.d(TAG, "get failed with ", task.getException());
Toast.makeText(EditListActivity.this, "Failed operation - " + task.getException(),
Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
}
});
Your app is acting like it's offline or somehow lacking a working internet connection.
When there is no network connection, the Firestore SDK won't fail on writes. It will store the write locally, and eventually sync that to the server. In the meantime, the local write becomes part of any queries, just like if the data was available on the server. So probably what you're seeing is the result of your local write.
(This is the same behavior you would see with Realtime Database.)
As far why the Firestore SDK doesn't have a connection, I don't know. You might have to troubleshoot that on your own.
I am new to Firebase and I trying to implement it into an Android application. It was all going well until now. I have to check the records for duplicates before inserting them and even after the tons of tutorials I watched online I can't figure it out.
I tried with rules, but apparently I was not able to write them down in a way they would work. I tried with push(), but this was not working either.
At the moment this is the code that I have:
private void updateDatabase(String year, String courseOfStudent, String workshopGroup, String day, String time, String lecture){
try{
mDatabase.child("student-timetables").child("course-of-student").setValue(courseOfStudent);
mDatabase.child("student-timetables").child(courseOfStudent).child("year").setValue(year);
mDatabase.child("student-timetables").child(courseOfStudent).child(year).child("workshop-group").setValue(workshopGroup);
mDatabase.child("student-timetables").child(courseOfStudent).child(year).child(workshopGroup).child("day").setValue(day);
mDatabase.child("student-timetables").child(courseOfStudent).child(year).child(workshopGroup).child(day).child("time").setValue(time);
mDatabase.child("student-timetables").child(courseOfStudent).child(year).child(workshopGroup).child(day).child(time).child("lecture").setValue(lecture);}
catch (Exception e)
{
Toast.makeText(getContext(), "Internal error occurred, please try again.", Toast.LENGTH_LONG).show();
}
}
And the rules from the Firebase console:
{
"rules": {
".read": "true",
".write": "auth != null",
"course-of-student": {
"year": {
"workshop-group": {
"day":{
"time": {
".write": "!data.exists()"
}
}
}
}
}
}
}
As of now what happens is that if there is a lecture detail at a specific time and I try to create a new record for this time the previous one gets overwritten. I want to reject this and display a message instead.
Where am I wrong?
First, add "ListenerForSingleValueEvent", and only then save the data in Firebase (if not exist..)
For example:
mDatabase.child("student-timetables").child(courseOfStudent).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if(!(snapshot.child("year").exist))
mDatabase.child("student-timetables").child(courseOfStudent).child("year").setValue(year);
else
Toast.maketext....."year exist.."
if(!(snapshot.child(year).child("workshop-group").exist))
mDatabase.child("student-timetables").child(courseOfStudent).child(year).child("workshop-group").setValue(workshopGroup);
else
Toast.maketext....."workshopGroup exist.."
}
}