0

I'm trying to find if there is a way to know if there is fetched data in the Firebase realtime database.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // ARRAY
    accountList = new ArrayList<>();
    // Assigning Object to Controls (bullshit)
    textboxUser = (TextView) findViewById(R.id.textBoxUsername);
    textboxPass = (TextView) findViewById(R.id.textBoxPassword);
    buttonEnter = (Button) findViewById(R.id.buttonEnter);

    postRef = FirebaseDatabase.getInstance().getReference("account");
    dataRefaccount = FirebaseDatabase.getInstance().getReference("account");


    // OnClick Method Button
    buttonEnter.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            try {
                username = textboxUser.getText().toString();
                Query query = FirebaseDatabase.getInstance().getReference("account").orderByChild("username").equalTo(username);
                query.addListenerForSingleValueEvent(valueEventListener);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                Toast.makeText(getApplicationContext(), getted, Toast.LENGTH_LONG).show();
            }



        }
    });
}

ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        for (DataSnapshot data : dataSnapshot.getChildren()) {
            if (data.child(username).exists()) {
                getted = "yes";
            } else {
                getted = "No";
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
    }
};

The getter is always "NO".

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

4 Answers4

0

You can check if the DataSnapshot exists by calling the following:

Query query = FirebaseDatabase.getInstance().getReference().child("account").orderByChild("username").equalTo(username);

ValueEventListener valueEventListener = new ValueEventListener() { 
    @Override 
    public void onDataChange(DataSnapshot dataSnapshot) { 
        if (dataSnapshot.exists()) {
            getted = yes;
        }else{
            getted = no;
        }
    } 

    @Override 
    public void onCancelled(DatabaseError databaseError) { 
        Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show(); 
    } 
};

By providing your database structure it would be easier to provide an answer.

HB.
  • 4,116
  • 4
  • 29
  • 53
0

The only method that is allowed by the firebase community to retrieve data is: You should try the code below as for fetched Username:

DatabaseReference bDatabaseRef;
bDatabaseRef=FirebaseDatabase.getInstance().getReference().child("Users");           bDatabaseRef.addValueEventListener(new ValueEventListener() {
       @Override
       public void onDataChange(DataSnapshot dataSnapshot) {
           if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
               Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();

               if(map.get("Username")!=null){

                   String User_name =map.get("Username").toString();

               }



           }
       }
       @Override
       public void onCancelled(DatabaseError databaseError) {
       }
       });
Megamind Core
  • 114
  • 11
0

You should have to try this. First make sure you are not getting any error in query response.

Query query = FirebaseDatabase.getInstance().getReference().child("account").orderByChild("username").equalTo(username);

ValueEventListener valueEventListener = new ValueEventListener() { 
    @Override 
    public void onDataChange(DataSnapshot dataSnapshot) { 
        if (dataSnapshot.getValue() != null && dataSnapshot.getChildrenCount() > 0) {
           for (DataSnapshot data : dataSnapshot.getChildren()) {

                // I'm sure you are looking for below line.. Go and try this.
                if (data.child("username").getValue().toString().equal(username) ) {
                  getted = "yes";
                  break;
                } else {
                  getted = "No";
                }
           }
        } else {
            getted = No value available;
        }
        Toast.makeText(getApplicationContext(), "getted : " + getted, Toast.LENGTH_LONG).show();
    } 

    @Override 
    public void onCancelled(DatabaseError databaseError) { 
        Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show(); 
    } 
};

FYI : Firebase calls is asynchronous call, so the finally clause on button click will always execute before the response from the firebase. So try to remove try-catch from there and use above code to print getted value.

DHAVAL A.
  • 2,251
  • 2
  • 12
  • 27
  • Thanks. I'm also having the same problem. I forgot that firebase query make async call to firebase database. –  Jun 19 '19 at 06:21
0

When you are trying to use the following line of code:

Toast.makeText(getApplicationContext(), getted, Toast.LENGTH_LONG).show();

The value of getted will always hold the value of No, since by the time you are trying to toast that message, the data hasn't finished loading yet from the database. This is happening because the asynchronous behaviour of onDataChange() method. Please note, that there are no guarantees about how long it will take, it may take from a few hundred milliseconds to a few seconds before that data is available.

A quick solve for this problem would be to use all the logic that is related to the getted variable only inside or called from inside the onDataChange() method.

If you need to use it outside the callback, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193