0

I am creating an android app in which I have to compare a node and retrieve some values if node is exist and store these values in SharedPreferences as shown in code:

dbRef = FirebaseDatabase.getInstance().getReference().child("users");
dbRef.orderByChild("email").equalTo(mAuth.getCurrentUser().getEmail()).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        //Toast.makeText(google_sign_in.this, "In sign in firebase", Toast.LENGTH_SHORT).show();
        for (DataSnapshot ds : snapshot.getChildren()) {
            SharedPreferences.Editor editor = sf.edit();
            editor.putString("phone", ds.child("phone").getValue(String.class));
            editor.putString("email", ds.child("email").getValue(String.class));
            editor.putString("fullName", ds.child("fName").getValue(String.class));
            editor.putString("lastName", ds.child("lName").getValue(String.class));
            editor.apply();
        }
    }
    @Override
    public void onCancelled(@NonNull DatabaseError error) {
    }
});

OnCreate method

sf = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
name = sf.getString("firstName", "null") + " " + sf.getString("lastName", "null");

Problem

name is always null whenever activity launched for the first time. When the activity launch for the first time ,data retrieving process is too slow and i received null value from sharedpreferenceeven I put this block of code in OnStart method.

What i want

I want to retrieve all data before launching of this activity so that I don't receive null value from sharedpreferences.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Golu
  • 33
  • 2
  • 7
  • 1
    Data is loaded from Firebase asynchronously, so your `sf.getString("lastName", "null")` likely runs before the `editor.putString("lastName", ds.child("lName").getValue(String.class))` is called. If you run the code in a debugger, or add some logging you can verify this. For this reason any code that needs the data needs to be inside `onDataChange` or be called from there. See https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 – Frank van Puffelen Aug 09 '20 at 17:03

1 Answers1

0

According to Android lifecycle, onCreate is executed before onStart. Paste the code in onCreate.

Source: Android Docs

fatalcoder524
  • 1,428
  • 1
  • 7
  • 16