0

I need some help with my app. I have an Activity where I add user info like name, birthday and add an profileimage for the user. And when I add the profileimage I get this in my firebase:

Firebase when added profileimage

And that is working fine. I am using ModelClass, and I know that when I use setValue it deletes the the existing data under that child and saves the new data. But is there a way to just add the new data and still not delete the existing data with ModelClass? I know it works with Hashmap, but I want to use ModelClass.

Firebase when adding user info

Here is my Activity for saving info:

public class UserInfoActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {

private CircleImageView civuserinfoprofileimage;
private EditText etuserinfofirstname, etuserinfolastname;
private Button btnbirthdaypicker, btnsaveuserinfo;
private TextView tvbirthday;


private FirebaseAuth mAuth;
private DatabaseReference UsersRef;
private StorageReference UserProfileImageRef;

private ProgressDialog loadingBar;

String currentUserID;
final static int Gallery_Pick = 1;




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

    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();
    UsersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
    UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profilepictures");

    loadingBar = new ProgressDialog(this);

    civuserinfoprofileimage = (CircleImageView)findViewById(R.id.civ_userinfoprofileimage);
    etuserinfofirstname = (EditText)findViewById(R.id.et_userinfofirstname);
    etuserinfolastname = (EditText)findViewById(R.id.et_userinfolastname);
    btnbirthdaypicker = (Button)findViewById(R.id.btn_birthdaypicker);
    tvbirthday = (TextView) findViewById(R.id.tv_birthday);
    btnsaveuserinfo = (Button)findViewById(R.id.btn_saveuserinfo);

    btnsaveuserinfo.setVisibility(View.INVISIBLE);


    btnbirthdaypicker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            DialogFragment datePicker = new DatePickerFragment();
            datePicker.show(getSupportFragmentManager(), "date picker");
        }
    });

    btnsaveuserinfo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


                SaveAccountSetupInformation();



        }
    });

    civuserinfoprofileimage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent galleryIntent = new Intent();
            galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
            galleryIntent.setType("image/*");
            startActivityForResult(galleryIntent, Gallery_Pick);
        }
    });


}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == Gallery_Pick && resultCode == RESULT_OK && data != null) {
        Uri ImageUri = data.getData();


        CropImage.activity()
                .setGuidelines(CropImageView.Guidelines.ON)
                .setAspectRatio(1,1)
                .start(this);
    }

    if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
    {
        CropImage.ActivityResult result = CropImage.getActivityResult(data);

        if (resultCode == RESULT_OK) {

            loadingBar.setTitle("Profile Image");
            loadingBar.setMessage("Saving profileimage");
            loadingBar.show();
            loadingBar.setCanceledOnTouchOutside(true);

            Uri resultUri = result.getUri();

            StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");

            filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                    if(task.isSuccessful()) {

                        btnsaveuserinfo.setVisibility(View.VISIBLE);


                        Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();


                        result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                final String downloadUrl = uri.toString();


                                UsersRef.child("profileimage").setValue(downloadUrl)
                                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                                            @Override
                                            public void onComplete(@NonNull Task<Void> task) {
                                                if (task.isSuccessful()) {
                                                    Intent selfIntent = new Intent(UserInfoActivity.this, UserInfoActivity.class);
                                                    selfIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                                                    startActivity(selfIntent);

                                                    Toast.makeText(UserInfoActivity.this, "Pofileimage saved", Toast.LENGTH_SHORT).show();
                                                    loadingBar.dismiss();
                                                } else {
                                                    String message = task.getException().getMessage();
                                                    Toast.makeText(UserInfoActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
                                                    loadingBar.dismiss();


                                                }
                                            }
                                        });
                            }
                        });

                    }
                }
            });
        }
        else {
            Toast.makeText(UserInfoActivity.this, "Error: Image can not be cropped. Try Again.", Toast.LENGTH_SHORT).show();
            loadingBar.dismiss();




        }


    }

}
private void SaveAccountSetupInformation() {

    String firstname = etuserinfofirstname.getText().toString();
    String lastname = etuserinfolastname.getText().toString();
    String birthday = tvbirthday.getText().toString();



    if (TextUtils.isEmpty(firstname) || TextUtils.isEmpty(lastname) || TextUtils.isEmpty(birthday)) {

        Toast.makeText(this, "Please enter information..", Toast.LENGTH_SHORT).show();


    } else {

        FirebaseUser firebaseUser = mAuth.getCurrentUser();

        String userid = firebaseUser.getUid();



        User user = new User(userid, firstname, lastname, birthday);



        UsersRef.setValue(user);
    }
}

ModelClass:

public class User {

private String id;
private String lastname;
private String firstname;
private String birthday;
private String profileimage;

public User(String id, String lastname, String firstname, String birthday, String profileimage) {
    this.id = id;
    this.lastname = lastname;
    this.firstname = firstname;
    this.birthday = birthday;
    this.profileimage = profileimage;
}

public User() {
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getLastname() {
    return lastname;
}

public void setLastname(String lastname) {
    this.lastname = lastname;
}

public String getFirstname() {
    return firstname;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}

public String getBirthday() {
    return birthday;
}

public void setBirthday(String birthday) {
    this.birthday = birthday;
}

public String getProfileimage() {
    return profileimage;
}

public void setProfileimage(String profileimage) {
    this.profileimage = profileimage;
}
Tore
  • 1
  • 2

1 Answers1

0

As far as I understand you're asking about this code:

User user = new User(userid, firstname, lastname, birthday);

UsersRef.setValue(user);

Please read about how to create a minimal, complete, verifiable example, as it's harder for us to isolate that code than it is/should be for you.

When you call setValue() on a location, any existing data at that location is replaced. To only update part of a location, you have to call updateChildren() on it. But as you found, you can't use updateChildren() with a Java class, it only takes a Map.

If you want to update just one child, you can use setValue on a DatabaseReference to that specific child. For example:

UsersRef.child("profileimage").setValue("Value of profile image");

If you want to update multiple-but-not-all child nodes, you'll need to use updateChildren() with a Map. Java 9 and 10 seems to have some nice syntactic sugar to make that more readable: https://stackoverflow.com/a/6802502

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • That is right. Maybe it will work if I put the imagestorage under my `SaveAccountSetupInformation()` void ? Because now I first add the profileimage and when that is stored I add the other information. – Tore Sep 22 '19 at 10:57
  • I'm not sure what you mean there, but if you call `setValue` on a `DatabaseReference`, it replaces all existing data at that reference. – Frank van Puffelen Sep 22 '19 at 10:59
  • Ok, so what you are saying is that I have to use `Map` and `updatechildren` to do this? It is no other options? – Tore Sep 22 '19 at 11:00
  • There's no way that allows you to use your `User` java class and somehow only update some of the child nodes. If you want to update just one child, you can use `setValue` on a `DatabaseReference` to that specific child. `UsersRef.child("profileimage").setValue("Value of profile image");` If you want to update multiple-but-not-all child nodes, you'll need to use `updateChildren()` with a `Map`. – Frank van Puffelen Sep 22 '19 at 11:44