How to write a key with its map values in firebase android - android

I want to store users information by adding a key with its map object
private void createUserData() {
Toast.makeText(LoginActivity.this, "test begin",
Toast.LENGTH_SHORT).show();
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference().child("users");
//set fields data
Map<String, String> userData = new HashMap<>();
userData.put("userId", "test id ");
userData.put("email", "as#gmail");
userData.put("userName", "abdo");
usersRef.child("userkey").setValue(userData);
Toast.makeText(LoginActivity.this, "test end",
Toast.LENGTH_SHORT).show();
}
when i click the button to trigger this code, the both Toast objects show up but no node added to users node.
whats wrong with this code to write data to firebase database ?

1.change the <String, String> as <String, Object>
Map<String, Object> userData = new HashMap<>();
userData.put("userId", "test id ");
userData.put("email", "as#gmail");
userData.put("userName", "abdo");
usersRef.child("userkey").updateChildren(userData);
2.change the firebase database get instance like FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance("https://yourdatabasename-default-rtdb.asia-southeast1.firebasedatabase.app")
recieved from this.
might be the database region problem like below
Firebase Database connection was forcefully killed by the server. Will not attempt reconnect. Reason: Database lives in a different region. Please change your database URL to https://databasename-default-rtdb.asia-southeast1.firebasedatabase.app

Related

firebase replaced my data when restarting my app

My app will generate a gameKey everytime user logged in and clicked "start game" button. Variable "gameKey" is generated by the following code, and then I will save data under the gameKey. The problem is, whenever I restart my app, the Firebase replaced the whole data tree with a new gameKey generated.
What I would like to do is to generate a new gameKey without overwriting the old data every time when my app runs. It would be so glad if anyone can point out my problem, thanks so much!
final FirebaseDatabase database = FirebaseDatabase.getInstance();
UserId = mAuth.getCurrentUser().getUid();
DatabaseReference currentUserId = database.getReference("user").child(UserId);
gameKey = currentUserId.child("gameinfo").push().getKey();
Map<String, Object> game = new HashMap<>();
game.put(gameKey, new Game(tv_player1name.getText().toString(), tv_player2name.getText().toString(), tv_player3name.getText().toString(), tv_playerMename.getText().toString(), gameMode, gameDate ));
currentUserId.child("gameInfo").updateChildren(game);
Firebase Data:
- user
- 5xGKRXeHgThQy70lduPEp3mosTj1 (UID)
- gameInfo
-LLV0H0ZJwYT5M42Obfb
gameDate: "20180903_232015"
gameType: "HKMJ"
player1name: "peter"
player2name: "jenny"
player3name: "john"
player4name: "wilson"
*This is the gameKey generated: "LLV0H0ZJwYT5M42Obfb"
This is the code after your suggestions:
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference currentUserId = database.getReference("user").child(UserId);
currentUserId.setValue(new User(mAuth.getCurrentUser().getEmail(), UserPic));
gameKey = currentUserId.child("gameinfo").push().getKey();
Map<String, Object> game = new HashMap<>();
game.put(gameKey, new Game(tv_player1name.getText().toString(), tv_player2name.getText().toString(), tv_player3name.getText().toString(), tv_playerMename.getText().toString(), gameMode, gameDate ));
currentUserId.child("gameInfo").child(gameKey).updateChildren(game);
In addition, I tried to replace this line
game.put(gameKey, new Game(tv_player1name.getText().toString(), tv_player2name.getText().toString(), tv_player3name.getText().toString(), tv_playerMename.getText().toString(), gameMode, gameDate ));
with this line, same result
Game game = new Game(tv_player1name.getText().toString(), tv_player2name.getText().toString(), tv_player3name.getText().toString(), tv_playerMename.getText().toString(), gameMode, gameDate );
Appreciate so much for the help!
Firebase ScreenShot
To solve this, please change the following line of code:
currentUserId.child("gameInfo").updateChildren(game);
to
currentUserId.child("gameInfo").child(gameKey).updateChildren(game);
You are basically generating a random key but you aren't using it at all. So you need to pass the gameKey to the child() method as seen in my above code.
Edit: So solve the entire update process, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference gameInfoRef = rootRef.child("user").child(uid).child("gameInfo");
String key = gameInfoRef.push().getKey();
Map<String, Object> game = new HashMap<>();
game.put("player1name", tv_player1name.getText().toString());
game.put("player2name", tv_player2name.getText().toString());
game.put("player3name", tv_player3name.getText().toString());
game.put("playerMename", tv_playerMename.getText().toString());
game.put("gameMode", gameMode);
game.put("gameDate", gameDate);
gameInfoRef.child(key).updateChildren(game);

Update object's field in Firebase

My project has 2 Apps: Admin-app and Client-app. First, I need to use the Admin-app in order to put data into Firebase and here is my data class
public class AllData {
private String placeName;
private ArrayList<String> category;
private String address;
private String openingHour;
private String website;
private HashMap<String, String> review; }
and I use following code to set data into Firebase
AllData alldata = new AllData(placeName, category, address,
, openingHour, website, null);
mDatabaseReference = mFirebaseDatabase.getReference().child("Store Data");
DatabaseReference storeData = mDatabaseReference.child(placeName);
storeData.setValue(alldata);
I have set the review field as null because I want to let my users review each place on Client-app and sync it into Firebase to the review field as HashMap<UserName, Review>
I use these codes in client-app to push review to Firebase
HashMap<String, String> reviewMap = new HashMap<>();
reviewMap.put(UserName, review);
mDatabase = FirebaseDatabase.getInstance();
mReference = mDatabase.getReference().child("Store Data").child(selectedPlace.placeName).child("review");
mReference.push().setValue(reviewMap);
This is not a right approach but that's all I could. What I want is to update the user's review to the AllData's review field in the Firebase asynchronously. How can I make this happen? Every answer is appreciated!
You can simply use setValue() method directly on the reference without using a HashMap like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("Store Data").child(selectedPlace.placeName).child("review").setValue(yourValue);
In which yourValue is the value which you want to set to the review key.
Hope it helps.

Getting Value from specified Key - Firebase/Android

I have run into an issue where I have each child off the root be a separate user account with a object (converted to string through gson). I create each user in the database during user registration.
DatabaseReference root = FirebaseDatabase.getInstance().getReference().getRoot();
Map<String,Object> map = new HashMap<String, Object>();
map.put(firebaseAuth.getCurrentUser().getUid(), "");
root.updateChildren(map);
Then save the user object in it using this method
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child(firebaseAuth.getCurrentUser().getUid());
Gson gson = new Gson();
String json = gson.toJson(this);
databaseReference.setValue(json);
Now I want to be able to pull the json from the firebase database but I can only get the userID key not the value. I am trying to avoid using a listener also.
This is how my database looks now:
-myapp-aaf46
-(userID): {json string}
I need to be able to get json string but I can only get it to return userId

Give unique child Key value for User using Firebase push() Method

How to give user defined key value in push(), instead of unique value created by push?
This is what am currently doing:
User user = new User(Editname.getText().toString(),
Editpid.getText().toString(),Editsem.getText().toString());
mRef.child("users").push().setValue(user);
.push() will create a new item with a unique reference.
You can use updateChildren() to update instead. For example,
User user=new User(Editname.getText().toString(),Editpid.getText().toString(),Editsem.getText().toString());
Map<String, Object> itemValues = user.toMap();
Map<String, Object> childUpdates = new HashMap<>();
// Define the key value here
String username = "yourKeyValueHere";
childUpdates.put("/users/" + username, itemValues);
mDatabase.updateChildren(childUpdates);
You might have to add something similar to the following to your User class.
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("name", name);
result.put("pid", pid);
result.put("sem", sem);
return result;
}
Simplest way is to specify the child key with the child method:
User user = new User(Editname.getText().toString(),
Editpid.getText().toString(),Editsem.getText().toString());
mRef.child("users").child(user.pid).setValue(user);
Where I specify user.pid, you can use whatever unique key you use to identify the user (typically when using Firebase Authentication this would be user.getUid()).
This is one way to do it assuming we want to use the User's name as unique key:
User user = new User(Editname.getText().toString(),
Editpid.getText().toString(),Editsem.getText().toString());
String uniqueKey = user.getName();
//You could use something else for quick reference since two users can have the same name
mDatabaseReference.child("users").child(uniqueKey).push().setValue(user);

How do you include a username when storing email and password using Firebase (BaaS) in an Android app?

The Firebase createUser() method takes an email and password field, but what if I want to also allow the user a custom username similar to Snapchat, Instagram, StackOverflow etc? Is there any way to modify the existing method to accept that field as well or do I need to do push and manage this info manually and if so how?
This is my first attempt at storing the desired user info:
Firebase ref = new Firebase(firebaseURL);
ref.createUser(email, password, new Firebase.ValueResultHandler<Map<String, Object>>() {
#Override
public void onSuccess(Map<String, Object> result) {
System.out.println("Successfully created user account with uid: " + result.get("uid"));
//Sign user in
Firebase ref = new Firebase(firebaseURL);
ref.authWithPassword(email, password, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider());
//Save user info
Firebase userRef = new Firebase(firebaseURL + "Users/");
User user = new User(username, authData.getUid());
userRef.setValue(user);
Is this good practice? I figured storing the UID with the username may help me in the future handling changes etc. Also, should I be implementing the updateChildren() or push() method so the entries do not get overwritten if this is a social media app?
This is my second attempt:
#Override
public void onAuthenticated(AuthData authData) {
System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider());
//Save user info and username
Firebase ref = new Firebase(firebaseURL);
Map<String, String> map = new HashMap<String, String>();
map.put("email", email);
map.put("username", username);
map.put("provider", authData.getProvider());
ref.child("users").child(authData.getUid()).setValue(map);
Yes, there is a way how to update user info in Firebase.
All you need - to read this article in Firebase docs and implement method described here Update user info
Using this method you can update diplayName property of FirabaseUser object. Just set user name for displayName property and commit your changes.
I hope this will help you.
Show a form with three fields:
Username
Email address
Password
Send the latter two to Firebase's createUser() method. Then in the completion callback for that, store all information in your Firebase database.
var userName, emailAddress, password;
// TODO: read these values from a form where the user entered them
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.createUser({
email : emailAddress,
password : password
}, function(error, authData) {
if (error) {
console.log("Error creating user:", error);
} else {
// save the user's profile into the database so we can list users,
// use them in Security and Firebase Rules, and show profiles
ref.child("users").child(authData.uid).set({
provider: authData.provider,
name: userName
});
}
});
See this page on storing user data in the Firebase docs for more information.
Here is one way to store the registered details in database,
Map<String, String> parameters = new HashMap<>();
FirebaseDatabase mFirebaseInstance;
parameters.put(Constant.TAG_USER, strUsrS.trim());
parameters.put(Constant.TAG_EMAIL, strEmailS.trim());
parameters.put(Constant.TAG_PASS, strPassS.trim());
//use this if needed(pushId)
String pushId = mFirebaseInstance.getReference(YOUR TABLE NAME).getRef().push().getKey();
parameters.put(Constant.TAG_KEY, pushId.trim());
mFirebaseInstance.getReference(YOUR TABLE NAME).getRef().child(strUsrS.trim()).setValue(parameters);
Try this implementation and execute... Thankyou
Hope that you aware about how to alter(create) table with required fields in firebase.
Related question & discussion with solutions

Categories

Resources