Getting Value from specified Key - Firebase/Android - 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

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.

How to get a key of an object that was pushed just now in Firebase?

I want to create kind of registration without password and email. I use only nickname. So,I have a User class that has nickname field and other fields. So, I want to push new user and the thing that I want is to save its key because I will need it in the future when I have to get some user's data. So how can I get a key of an object that was already pushed?
Here is my code how I push:
User user = new User() ;
user.setNick(nick.getText().toString());
user.setScore(0);
Firebase fire = new Firebase(FirebaseConfig.URL) ;
//how to get key of this object? Is it possible before pushing?
fire.push().setValue(user);
To get the key, please use the code below:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference keyRef = rootRef.push();
String key = keyRef.getKey();
keyRef.setValue(user);
or
Firebase fire = new Firebase(FirebaseConfig.URL) ;
String pushKey = fire.push().getKey();
fire.child(pushKey).setValue(user);
Hope it helps.
It is not possible to get pushKey before you do push().
You can try this one instead.
Firebase fire = new Firebase(FirebaseConfig.URL) ;
String pushKey = fire.push().getKey();
fire.child(pushKey).setValue(user);

How to cteate a Node inside Main Node of Firebase database?

how we create node inside a node in firebase android...i need to creat blood_Group node inside kchzdjn...
The simples way to achieve this is to use updateChildren() method directly on your reference like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference sessionIdRef = rootRef.child("sessions").child(sessionId);
Map<String, Object> map = new HashMap<>();
map.put("blood_Group", "");
sessionIdRef.updateChildren(map);
In which sessionId is the unique key generated by the push() method.
Hope it helps.

How to write a key with its map values in firebase 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

Categories

Resources