简体   繁体   中英

How to retrieve data from firebase database in a efficient way

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 sharedpreference even 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 .

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

Source: Android Docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM