Mehul Kothari
Mehul Kothari

Reputation: 421

Instead of updating data of user the data gets deleted from firebase

I created a login sign up system using Firebase and in profile page, I retrieved data of the user from Firebase Next, I created an edit profile page for my user where the user can edit information and profile picture but here is my problem

As user click on save button the whole node of that particular user is deleted from firebase .Here is my code for

edit profile.java

 public class ProfileEditInfo extends AppCompatActivity {
private EditText newUserName, newUserEmail, newUserPhone;
private Button save;
private DatabaseReference databaseReference;
private FirebaseAuth firebaseAuth;
private FirebaseDatabase firebaseDatabase;
private ImageView updateProfilePic;
private static int PICK_IMAGE = 123;
Uri imagePath;
private StorageReference storageReference;
private FirebaseStorage firebaseStorage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile_edit_info);
    updateProfilePic = findViewById(R.id.ivProfileUpdate);
    newUserName = findViewById(R.id.etNameUpdate);
    newUserEmail = findViewById(R.id.etEmailUpdate);
    newUserPhone = findViewById(R.id.etPhoneUpdate);
    save = findViewById(R.id.btnSave);
    databaseReference= FirebaseDatabase.getInstance().getReference("users");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    firebaseAuth = FirebaseAuth.getInstance();
    firebaseDatabase = FirebaseDatabase.getInstance();
    String userID = firebaseAuth.getUid();
    firebaseStorage = FirebaseStorage.getInstance();

    storageReference = FirebaseStorage.getInstance().getReference();

    final StorageReference storageReference = firebaseStorage.getReference();
    storageReference.child("images").child(firebaseAuth.getUid() + "." + "jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            Picasso.get().load(uri).fit().centerCrop().into(updateProfilePic);
        }
    });

    // final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users").child(userID);
    databaseReference.child(userID).addListenerForSingleValueEvent(new ValueEventListener()
    {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Users userProfile = dataSnapshot.getValue(Users.class);

            newUserName.setText(userProfile.getName());
            newUserPhone.setText(userProfile.getPhone());
            newUserEmail.setText(userProfile.getEmail());
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Toast.makeText(ProfileEditInfo.this, databaseError.getCode(), Toast.LENGTH_SHORT).show();
        }

    });



    save.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View view) {

            String name = newUserName.getText().toString();
            String phone = newUserPhone.getText().toString();
            String email = newUserEmail.getText().toString();
            //     Users userProfile = new Users(name, phone, email);
            //     databaseReference.setValue(userProfile);




            String id = firebaseAuth.getCurrentUser().getUid();
            Users user = new Users(id,name, email, phone);
            databaseReference.child(id).setValue(user);

            StorageReference imageReference = storageReference.child("images").child(firebaseAuth.getUid() + "." + "jpg");  //User id/Images/Profile Pic.jpg
            UploadTask uploadTask = imageReference.putFile(imagePath);

            uploadTask.addOnFailureListener(new OnFailureListener() {
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(ProfileEditInfo.this, "Upload failed!", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(ProfileEditInfo.this, DisplayProfile.class));
                    finish();
                }

            }).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                    Toast.makeText(ProfileEditInfo.this, "Upload successful!", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(ProfileEditInfo.this, DisplayProfile.class));
                    finish();

                }

            });

            finish();
        }
    });

    updateProfilePic.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE);

        }

    });


}

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data.getData() != null) {
        imagePath = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagePath);
            updateProfilePic.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    super.onActivityResult(requestCode, resultCode, data);
} 
}

The Code for users.java is here

Users.java

   package com.example.deepak.myapplication;

public class Users {  
public String imageUrl;
public String imageName;
public String uid;
public String name;
public String email;
public String password;
public String phone;

public Users(){}

public Users(String id, String name, String phone, String email){}
public Users(String uid, String name, String email, String password, String phone) {
    this.uid = uid;
    this.name = name;
    this.email = email;
    this.password = password;
    this.phone = phone;
}

public String getUid() {
    return uid;
}

public void setUid(String uid) {
    this.uid = uid;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getPhone() {
    return phone;
}
public void setPhone(String phone) {
    this.phone = phone;
}
}

The Database Structure is here

Database Strcuture

As I Click on edit info I am able to retrieve all data in edit text box but once I edit data and click on save button the whole node of user id by which I am creating user gets deleted and then I get null pointer exception

So please help e and let me know where I am going wrong Thanks.

Upvotes: 0

Views: 499

Answers (1)

sats
sats

Reputation: 657

Firebase requires that there be atleast one child per node with both key and value. Both. Having only a key without value as a child or no child at all will cause the entire node to be deleted. I suggest you ensure that the user object has values set before saving it to Firebase.

Upvotes: 1

Related Questions