• 6
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

I want to retrive the id that generated by firebase when I pushed value to it like next

Firebase

I want to retrieve "-KGdKiPSODz7JXzlgl9J" this id for that email I tried by getKey() but it return "users" and when user get value it return the whole object from the id to profile picture and that won't make me get it as User object in my app

how solve this ?

    Firebase users = myFirebaseRef.child("users");
    users.orderByChild("email").equalTo("z@m.com").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            dataSnapshot.getKey();
            Log.d("User",dataSnapshot.getRef().toString());
            Log.d("User",dataSnapshot.getValue().toString());
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

            Log.d("User",firebaseError.getMessage() );
        }
    });
      • 2
    • Would you consider iterating over the users dataSnapshot and using an identifier value (like the email for example) to see if you have a match and retrieve the values of that matching snapshot?
      • 2
    • For next time: You've included a picture of the JSON tree in your question. Please replace that with the actual JSON as text, which you can easily get by clicking the Export button in your Firebase database. Having the JSON as text makes it searchable, allows us to easily use it to test with your actual data and use it in our answer and in general is just a Good Thing to do.

You can read the key from push() without pushing the values. Later you can create a child with that key and push the values for that key.

// read the index key
String mGroupId = mGroupRef.push().getKey();
....
....
// create a child with index value
mGroupRef.child(mGroupId).setValue(new ChatGroup());

mGroupId contains the key which is used to index the value you're about to save.

  • 69
Reply Report
      • 1
    • But what if I have pushed the child already and later I want to get the key later? Is there any way to get that key?
      • 1
    • @ZeeshanAhmadKhalil Depends, is the child you have created is in the same operation as you need to read the key? then you can use this method, if it is in the different part of the code or if you need in the future, you can check out Frank Van's answer below

UPDATE 1: it can obtain also by one line

String key = mDatabase.child("posts").push().getKey();

//**************************************************************//

after searching and trying a lot of things i came to 2 ways to do that . 1. first one to get the key when i upload the post to the server via this function

 public void uploadPostToFirebase(Post post) {
      DatabaseReference mFirebase = mFirebaseObject
            .getReference(Constants.ACTIVE_POSTS_KEY)
            .child(post.type);
      mFirebase.push().setValue(post);
      Log.d("Post Key" , mFirebase.getKey());
 }
  1. i used it in my code to get the key after i have already pushed it to node for it in my database

    public void getUserKey(String email) {
    
        Query queryRef = databaseRef.child(Constants.USERS_KEY)
            .orderByChild(Constants.USERS_EMAIL)
            .equalTo(email);
    
        queryRef.addChildEventListener(new ChildEventListener() {
          @Override
          public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            //TODO auto generated
          }
    
          @Override
          public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            //TODO auto generated;
          }
    
          @Override
          public void onChildRemoved(DataSnapshot dataSnapshot) {
            //TODO auto generated;
          }
    
          @Override
          public void onChildMoved(DataSnapshot dataSnapshot, String s) {
            //TODO auto generated
          }
    
          @Override
          public void onCancelled(DatabaseError databaseError) {
            //TODO auto generated 
          }
      });
     }
    
  • 23
Reply Report

When you fire a Firebase query there can potentially be multiple results. So when you ask for the value of a query, Firebase returns a list of items. Even if there is only one matching item, it will be a list of one item.

So you will have to handle this list in your code:

users.orderByChild("email").equalTo("z@m.com").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot child: dataSnapshot.getChildren()) {
            Log.d("User key", child.getKey());
            Log.d("User ref", child.getRef().toString());
            Log.d("User val", child.getValue().toString());
        }
    }
  • 15
Reply Report

In Java - Android Studio, you can get the unique pushed ID as the item is written to the db...

Per "Firebase's: Save Data on Android": You can use the reference to the new data returned by the push() method to get the value of the child's auto-generated key or set data for the child. Calling getKey() on a push() reference returns the value of the auto-generated key.

To get the reference at write time, instead of loading DATA with a single push()...

  • use push() to create a blank record in the database, return value is the record's reference.
  • use .getKey() to get the Key for that record.
  • use .setValue(DATA) to fill in the blank record

here's an example:

    FirebaseDatabase fb_db_instance = FirebaseDatabase.getInstance(); 
    DatabaseReference db_ref_Main = fb_db_instance.getReference("string_db_Branch_Name");

    hashMap_record = new HashMap<String, String>();           //some random data 
    hashMap_record.put("key_Item1", "string_Item1");
    hashMap_record.put("key_Item2", "string_Item2");

    DatabaseReference blankRecordReference = db_ref_Main ;   

    DatabaseReference db_ref = blankRecordReference.push();   //creates blank record in db
    String str_NEW_Records_Key = db_ref.getKey();             //the UniqueID/key you seek
    db_ref.setValue( hashMap_record);                         //sets the record 
  • 8
Reply Report
      • 2
    • firebase.google.com/docs/database/android/read-and-write demonstrates what kind of data that firebase can handle... it's all JSON, and includes String, Long, Double, Boolean, Map, List... the above example corresponds to Map

      For those using TVAC Tutorials(https://www.youtube.com/watch?v=cSMMWOHkP68&list=PLGCjwl1RrtcTXrWuRTa59RyRmQ4OedWrt&index=16)

      You can get Key using onClick method as follows:

         viewHolder.mView.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
      
                 String key = getRef(position).getKey();
      
                }
           });
      
      • 3
      Reply Report

      Just add new field to Users like userID, when you create new User add uid and than you can receive it by reading query

      I'm doing it like this.

      String userID;// in Users
      
      
      Firebase users = myFirebaseRef.child("users");
          users.orderByChild("email").equalTo("z@m.com").addListenerForSingleValueEvent(new ValueEventListener() {
              @Override
              public void onDataChange(DataSnapshot dataSnapshot) {
                  Users user= dataSnapshot.getChildren().iterator().next().getValue(Users.class);
                  Log.d("User",user.getUserID());
              }
      
              @Override
              public void onCancelled(FirebaseError firebaseError) {
                  Log.d("User",firebaseError.getMessage() );
              }
          });
      
      • 2
      Reply Report

      Another Option to get the unique Post-id from firebase is by getting key (dataSnapshot.getKey()) in @Override method public void onChildAdded and maintaining it locally for example

      private void attachDatabaseReadListener() {
              if (mTaskEventListener == null) {
                  mTaskEventListener = new ChildEventListener() {
                      @Override
                      public void onChildAdded(DataSnapshot dataSnapshot, String s) {
      
                      Task friendlyMessage = dataSnapshot.getValue(Task.class);
                      friendlyMessage.setId(dataSnapshot.getKey());
      
                      System.out.println("friendlyMessage  = " + friendlyMessage);
      
                      DummyContent.ITEMS.add(new DummyContent.DummyItem("" + DummyContent.ITEMS.size()+1,friendlyMessage.getStatus(),friendlyMessage.getSummary()));
                  }
      
                  public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
                  public void onChildRemoved(DataSnapshot dataSnapshot) {}
                  public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
                  public void onCancelled(DatabaseError databaseError) {}
              };
                           mUserDatabaseReference.addChildEventListener(mTaskEventListener); // remove it
          }
      }
      

      dataSnapshot.getKey will set the unique post id in Task Instance and can be used later to perform any update operation.

      • 1
      Reply Report

      Use this

       mFirebaseDatabase=mFirebaseDatabase.getInstance().getReference("tablename");
       Query query = mFirebaseDatabase.orderByChild("tablenme").getRef();
      
      
          query.orderByChild("Id").addValueEventListener(new ValueEventListener() {
              @Override
              public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                  for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                      String id =dataSnapshot1.child("Id").getKey();
      
                          String Name = dataSnapshot1.child("Name").getValue().toString();
                          String lastName= dataSnapshot1.child("lastname").getValue().toString();
                          flatDataGets.add(Name+"-"+lastname);
      
      
      
                  }
      
                  ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(RagisterActivity.this, R.layout.support_simple_spinner_dropdown_item, DataGets);
                  arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                  mRegisterSpinner.setAdapter(arrayAdapter);
                  mRegisterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                      @Override
                      public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        flatName =DataGets.get(position);
      
      
                      }
      
                      @Override
                      public void onNothingSelected(AdapterView<?> parent) {
      
                      }
      
                  });
      
              }
      
      
                  @Override
              public void onCancelled(@NonNull DatabaseError databaseError) {
      
              }
          });
      
      • 1
      Reply Report
      FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
      DatabaseReference databaseReference1 = firebaseDatabase.getReference("users");
      databaseReference1.addValueEventListener(new ValueEventListener() {
                  @Override
                  public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
      
                      for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
      
                          String key = dataSnapshot1.getKey();
                          Log.d(TAG, "onCreate: key :" + key);
      
                          String email = dataSnapshot1.child("email").getValue(String.class);
                          String roomno =dataSnapshot1.child("address").getValue(String.class);
                          Log.d(TAG, "onDataChange: email: " + email);
                          Log.d(TAG, "onDataChange: address: " + address)
                      }
                  }
                  @Override
                  public void onCancelled(@NonNull DatabaseError databaseError) {
      
                  }
              });
      
      • 0
      Reply Report

      Simply do similar:

       HashMap<String, Object> hashLcl = new HashMap<>();
          hashLcl.put("admin", firebaseUser.getUid());
          hashLcl.put("name", textPrm);
          DatabaseReference referenceLcl = FirebaseDatabase.getInstance().getReference();
          String keyLcl = referenceLcl.child("GroupChats").push().getKey();
          hashLcl.put("key", keyLcl);
          Task task = referenceLcl.child("GroupChats").child(keyLcl).setValue(hashLcl);
          task.addOnSuccessListener(aVoid -> {
              //the data is added and now we are sure to do something related
          });
      

      This is the result: enter image description here

      • -1
      Reply Report