0

I'm new in firebase and I am trying to get data from firebase database and insert them(nickname, userDescription, profileImage, pictureOne, pictureTwo) to Firestore database.

The problem is that the code return null when I execute datasnapshot. Can anyone help me? I would really thankful if anyone could help me. Thank you in advance!

My realtime database

enter image description here

My Java Code:

public class SettingsActivity extends AppCompatActivity
{
    private FirebaseFirestore db;

    private FirebaseDatabase mFirebaseDatabase;
    DatabaseReference AllUsersProfileRef;

    private FirebaseAuth mAuth;

    private Toolbar mToolbar;
    private ProgressDialog loadingBar;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        mAuth= FirebaseAuth.getInstance();
        currentUserID = mAuth.getCurrentUser().getUid();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        loadingBar = new ProgressDialog(this);

        db = FirebaseFirestore.getInstance();

        mFirebaseDatabase = FirebaseDatabase.getInstance();
        AllUsersProfileRef= mFirebaseDatabase.getReference();


        FirebaseStorage.getInstance().getReference();

        settingsSaveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadingBar.setTitle("자기소개 저장");
                loadingBar.setMessage("자기소개 저장중이니 기다리세요");
                loadingBar.setCanceledOnTouchOutside(true);
                loadingBar.show();

                SaveDataToFirestore();
                RetrieveDataFromFirebase();
            }
        });
    }

    private void RetrieveDataFromFirebase()
    {
        DatabaseReference AllUsersProfileRef = FirebaseDatabase.getInstance().getReference("allUsers");
        AllUsersProfileRef.addListenerForSingleValueEvent(new ValueEventListener() {
                     @Override
                     public void onDataChange(@NonNull DataSnapshot snapshot)
                     {
                         for (DataSnapshot dsp : snapshot.getChildren())
                         {
                             Users users = dsp.getValue(Users.class);

                             nickname = users.getNickname();
                             userDescription = users.getUserDescription();
                             profileImage = users.getProfileImage();
                             pictureOne = users.getPictureOne();
                             pictureTwo = users.getPictureTwo();
                         }
                     }

                     @Override
                     public void onCancelled(@NonNull DatabaseError error) {

                     }
                 });
    }


    private void SaveDataToFirestore()
    {
        Map<String, Object> profile = new HashMap<>();

        profile.put("nickname", nickname );
        profile.put("userDescription", userDescription );
        profile.put("profileImage", profileImage );
        profile.put("pictureOne", pictureOne );
        profile.put("pictureTwo", pictureTwo );
        profile.put("currentUserID", currentUserID);
        profile.put("marriage", marriage);
        profile.put("gender", gender);
        profile.put("timestamp", FieldValue.serverTimestamp());
        profile.put("age", a);
        profile.put("school", school);
        profile.put("occupation", occupation);
        profile.put("salary", salary);
        profile.put("address", address);
        profile.put("height", height);
        profile.put("weight", weight);
        profile.put("blood", blood);
        profile.put("leadership", leadership);
        profile.put("religion", religion);
        profile.put("housing", housing);
        profile.put("manWealth", manWealth);
        profile.put("hobbyOne", hobbyOne);
        profile.put("hobbyTwo", hobbyTwo);
        profile.put("hobbyThree", hobbyThree);
        profile.put("hobbyFour", hobbyFour);
        profile.put("hobbyFive", hobbyFive);
        profile.put("hobbySix", hobbySix);

        db.collection("usersProfiles").document()
                .set(profile)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid)
                    {
                        SendUserToProfileActivity();
                        Toast.makeText(SettingsActivity.this, "프로필 데이터 저장", Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                }).addOnFailureListener(new OnFailureListener()
        {
            @Override
            public void onFailure(@NonNull Exception e)
            {
                Toast.makeText(SettingsActivity.this, "프로필 데이터 저장실패", Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        });
    }
}

My Firestore Db Result:

enter image description here

realtime database child data such as nickname, userDescription, profileImage, pictureOne, pictureTwo did not saved. the others are saved.

2021-01-29 08:53:53.544 16107-16107/? E/Zygote: isWhitelistProcess - Process is Whitelisted 2021-01-29 08:53:53.545 16107-16107/? E/Zygote: accessInfo : 1 2021-01-29 08:54:11.183 16107-16107/com.maintoppartners.jakiya_hun E/ViewRootImpl: sendUserActionEvent() returned. 2021-01-29 08:54:15.464 16107-16107/com.maintoppartners.jakiya_hun E/ViewRootImpl: sendUserActionEvent() returned. 2021-01-29 08:54:18.494 16107-16107/com.maintoppartners.jakiya_hun E/ViewRootImpl: sendUserActionEvent() returned. 2021-01-29 08:54:30.506 16107-16107/com.maintoppartners.jakiya_hun E/ViewRootImpl: sendUserActionEvent() returned.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

The problem is here:

SaveDataToFirestore();
RetrieveDataFromFirebase();

First off, you're calling these methods in the wrong order: you should first load the data from the realtime database, and then save it to Firestore.

But even just swapping the calls won't work, since data is loaded from/and save to the databases asynchronously. Instead of repeating what that means, I recommend reading getContactsFromFirebase() method return an empty list.

For your code: the simplest way to fix it is to:

  1. Pass the data to be saved to SaveDataToFirestore as parameters, instead of as a bunch of fields.
  2. Then call SaveDataToFirestore from within RetrieveDataFromFirebase.

So something like:

private void SaveDataToFirestore(String nickname, String userDescription, String profileImage, String pictureOne, String pictureTwo /* same for the other fields */)
{
    ...
}

And then:

DatabaseReference AllUsersProfileRef = FirebaseDatabase.getInstance().getReference("allUsers");
AllUsersProfileRef.addListenerForSingleValueEvent(new ValueEventListener() {
     @Override
     public void onDataChange(@NonNull DataSnapshot snapshot)
     {
         for (DataSnapshot dsp : snapshot.getChildren())
         {
             Users users = dsp.getValue(Users.class);

             nickname = users.getNickname();
             userDescription = users.getUserDescription();
             profileImage = users.getProfileImage();
             pictureOne = users.getPictureOne();
             pictureTwo = users.getPictureTwo();

             SaveDataToFirestore(nickname, userDescription, profileImage, pictureOne, pictureTwo);
         }
     }

     @Override
     public void onCancelled(@NonNull DatabaseError error) {
         throw error.toException(); // never ignore errors
     }
 });
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you very much for your help. I can save data in Firestore sucessfully. Thank again!! – Joohun Park Jan 29 '21 at 21:36
  • I can't know where i click the checkmark to accept. Let me know how. – Joohun Park Jan 30 '21 at 03:19
  • Linked from the link I provided before: https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Frank van Puffelen Jan 30 '21 at 04:20
  • I asked FirestoreRecyclerAdapter, but nobody answered. I would be very helpful, if you could comment about my problem. The question is " FirestoreRecyclerAdapter shows Nothing". I am very sorry for bothering you. – Joohun Park May 10 '21 at 03:10