Firebase real time database could not save EditText string or String test_case = "this is test case message" in setValue,but it is successfully saving databaseReference.child(id_key).setValue("given string text");
final Text_Strings text_strings = new Text_Strings(user_name, id_key, title_m, question_m);
// to save elements database referefernce called
databaseReference.child(id_key).setValue(text_strings, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
Log.d("Data could not be saved ", databaseError.getMessage());
} else {
// it is always saying data
Toast.makeText(getContext(), "Data saved succcessfully ", Toast.LENGTH_SHORT).show();
}
}
});
// to save id_key for test cases
databaseReference.child(id_key).setValue(test_case);
/// to save string elements for test cases
databaseReference.child(id_key).setValue("given string text");
}
});
// return view
return view;
}
}
;
Check whether you are in test mode or applied read write rules correctly .
You can refer to Docs for Read and Write data in Firebase Realtime Database : https://firebase.google.com/docs/database/android/read-and-write
Please paste you complete activity code to better understand your problem.
Related
I need to get the string value from the node passcode in my Firebase database to compare with a user input, but unfortunately I am not able to get the value. This is the link to my firebase database in the below image.
This is my codes below:
final DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("pin_code");
mDatabase.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
String rface = (String) dataSnapshot.child("pincode").getValue();
if (rface.equals(userPassword) && !rface.equals("")){
Intent intent = new Intent(PinActivity.this, ProfileActivity.class);
startActivity(intent);
}
else {
if (rface.equals("") || rface.equals(null)){
// Creating new user node, which returns the unique key value
// new user node would be /users/$userid/
String userId = mDatabase.push().getKey();
// creating user object
Pin pin = new Pin(authUserId, userPassword);
mDatabase.child(userId).setValue(pin);
Intent intent = new Intent(PinActivity.this, ProfileActivity.class);
startActivity(intent);
}
else {
Toast.makeText(PinActivity.this,"Invalid PIN code", Toast.LENGTH_SHORT).show();
return;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This is the json code
{
"pin_code" : {
"id" : "TQYTo1NHNnhPJnOxhe1Vok3U6ic2",
"pincode" : "12345"
}
}
This FirebaseDatabase.getInstance().getReference("pin_code") does not refer to the node you're looking for. Most likely you know the id property, in which case you can get the node with:
DatabaseReference collection = FirebaseDatabase.getInstance().getReference("p...");
Query query = collection.orderByChild("id").equalTo("TQT...ic2");
query.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
String rface = (String) child.child("pincode").getValue();
if (rface.equals(userPassword) && !rface.equals("")){
The changes I made:
On the first line we get the collection: the node under which you want to run a query. You struck out the name of that node in the screenshot, but it's the second line you marked.
In the second line we create a query on the id property of each child node under the collection.
In the onDataChange we added a loop. This is needed because a query against the Firebase Database will potentially have multiple results. So the dataSnapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result. We loop over dataSnapshot.getChildren() to handle those multiple results.
If there can ever only be one node with the same id, you should consider changing your data structure to use the id as the key of the node. So:
pin_codes
uid1: "pincode1"
uid2: "pincode2"
Your code then becomes significantly simpler, because you don't need to query for the user anymore. You can just directly read from the path:
DatabaseReference user = FirebaseDatabase.getInstance().getReference("pin_codes").child("TQT...ic2");
user.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
String rface = (String) dataSnapshot.getValue();
if (rface.equals(userPassword) && !rface.equals("")){
Try change this:
String rface = (String) dataSnapshot.child("pincode").getValue();
To this:
String rface = (String) dataSnapshot.child("pincode").getValue(String.class);
Use the following::
Object some = dataSnapshot.getValue();
String value = some.toString();
My code works this way: when I'm on a post and I press "ok" on a AlertDialog.Builder then I go to:
private void borrar_post(){
Intent intent = new Intent(PostDetailActivity.this, MainActivity.class);
intent.putExtra("EXTRA_BORRAR_POST", mPostKey);
startActivity(intent);
}
I come back to main activity and I see if there's anything I need to delete:
String borrar = getIntent().getStringExtra("EXTRA_BORRAR_POST");
if (borrar != null) {
DatabaseReference mipost = FirebaseDatabase.getInstance().getReference();
mipost.child("user-posts").child(getUid()).child(borrar).removeValue();
mipost.child("posts").child(borrar).removeValue();
mipost.child("post-comments").child(borrar).removeValue();
}
I delete my post from the 3 places I have it on my firebase realtime database. The tree is:
It's possible I don't have anything on "post-comments", so I understand I might have a problem there (maybe I should check if there's something there before) but even when I comment that line, I keep having the same problem:
Sometimes everything gets deleted, sometimes nothing, most of the times only "user-posts" child gets deleted.
I know there's similar questions to mine, but I can't seem to find the mistake, any help?
Do you have security rules that limit write access as a function of the current value at a location? That might explain why some removes succeed and others fail.
To understand why some calls to removeValue() are failing, add a CompletionListener. You can define a debug listener as a field in your activity like this:
private DatabaseReference.CompletionListener mRemoveListener =
new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError error, DatabaseReference ref) {
if (error == null) {
Log.d(TAG, "Removed: " + ref);
// or you can use:
System.out.println("Removed: " + ref);
} else {
Log.e(TAG, "Remove of " + ref + " failed: " + error.getMessage());
}
}
};
Then add it to each of your calls to removeValue():
String borrar = getIntent().getStringExtra("EXTRA_BORRAR_POST");
if (borrar != null) {
// always good to log important values
Log.d(TAG, "borrar= " + borrar);
DatabaseReference mipost = FirebaseDatabase.getInstance().getReference();
mipost.child("user-posts").child(getUid()).child(borrar).removeValue(mRemoveListener);
mipost.child("posts").child(borrar).removeValue(mRemoveListener);
mipost.child("post-comments").child(borrar).removeValue(mRemoveListener);
}
I am using Firebase for both authentication and realtime database. My authentication code was successfully run also my enter value to database code also run, but when I am coding for fetch value in database, I am getting run time error trying to enter value at Firebase database:
FATAL EXCEPTION: main
Process:com.xxx.xxx, PID: 22601
com.google.firebase.database.DatabaseException: Invalid Firebase Database
path: https://xxx-exxe.firebaseio.com/. Firebase Database paths must not contain '.', '#', '$', '[', or ']'
My Code is :
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference reference = database.getReference("https://korsa-e03ae.firebaseio.com/");
reference.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
Offerride user = dataSnapshot.getValue(Offerride.class);
if (user == null){
Toast.makeText(getContext(),"User data is null!",Toast.LENGTH_LONG).show();
return;
}
tvsource.setText(user.source + " , " + user.destination + " , " + user.startDate + " , " + user.startTime);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getContext(), "Failefddd", Toast.LENGTH_LONG).show();
}
});
I think the answer is quite obvious you don't need to specific the url because app is already link to the database when you set up the project
just change from
DatabaseReference reference = database.getReference("https://korsae03ae.firebaseio.com/");
to
DatabaseReference reference = database.getReference();
Then it should work
Url of your database is in your google-services.json file.
By firebase docs https://firebase.google.com/docs/database/admin/retrieve-data to read data, you can do the following:
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("posts");
// Attach a listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Post post = dataSnapshot.getValue(Post.class);
System.out.println(post);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
Instead of using getReferance use, getReferanceFromUrl.
and in your case: database.getReference.child("posts");
I have database structure like this in Firebase
I want to search a search on this structure based on key number and get the parent key in return. Meaning if i search for 8860124421 then i should get -KTEtSR7chN8te1WaW-W in return .
I am doing it like this in android -
final String number = "8860124421";
DatabaseReference global_user_entry_ref = ApplicationContext.getGlobalDataBaseReference()
.child("User-Entry-2").getRef(); //Reference to User-Entry-2
Query query = global_user_entry_ref.orderByChild("number").equalTo(number);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot != null){
for(DataSnapshot friend: dataSnapshot.getChildren()){
String firebase_id = (String) friend.getKey();
Log.d("ContactSync","handle number "+firebase_id+" "+number+" "+friend);
}
Log.d("ContactSync","handle number outer "+dataSnapshot);
//user exist
}
else {
//user_does_not_exist
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("ContactSync","handle number oncancel "+databaseError.getMessage());
}
});
But I am not getting proper result , dataSanpshot in onDataChange looks like this -
DataSnapshot { key = User-Entry-2, value = null }
but i want to get dataSnapShot with parent of number key.
Please help , Thanks in advance
As #Frank van Puffelen stated in comments , the problem was that i was comparing a number from code with a string in the database , which does not match , Therefore the solution is to change
final String number = "8860124421";
to
final long number = 8860124421;
Is this the best way to create a user list from facebook users to hold variables on firebase? I want each user to have a few int variables, tokens, spins, and biggestWin. but the createUser method doesn't seem to add any data to the firebase, and doesnt seem to work well with the facebook code. It always toasts "not created"
public void createUser(String mEmail, String mProvide){
Firebase rootRef = new Firebase("https://luckycashslots.firebaseio.com/data/");
Firebase userRef = rootRef.child("users");
userRef.setValue(mAuthData.getUid());
Firebase newRef = new Firebase("https://luckycashslots.firebaseio.com/data/users/" + mAuthData.getUid() + "/");
Firebase tokRef = newRef.child("tokens");
Firebase spinRef = newRef.child("spins");
newRef.setValue(mAuthData.getProvider());
Tokens token = new Tokens("100");
Spins spin = new Spins(55);
tokRef.setValue(token);
//spinRef.setValue(spin);
rootRef.createUser(mEmail, mProvide , new Firebase.ValueResultHandler<Map<String, Object>>() {
#Override
public void onSuccess(Map<String, Object> result){
Toast.makeText(getApplicationContext(), "Yes-UID=" + result.get("Uid") , Toast.LENGTH_LONG).show();
}
#Override
public void onError(FirebaseError firebaseError){
Toast.makeText(getApplicationContext(), "Not Created", Toast.LENGTH_LONG).show();
}
});
}
Creating an email+password user or authenticating a user with Facebook does indeed not store any data about that user in the Firebase Database.
If you want to store user data in the database, see the section on storing user data in the Firebase documentation.