4

I'm making an edit page for the user profile in Firebase. I've tried a few different ways. But I could not update. Just a added as a new user to the database.

I am getting new values in the Alert Dialog. Please help me.

My Update Method Code's :

public void editAlert() {
        LayoutInflater layoutInflater = LayoutInflater.from(ProfilePage.this);

        View design = layoutInflater.inflate(R.layout.edit_profile, null);

        final EditText editTextUserName = design.findViewById(R.id.username_editTextProfileEdit);

        final EditText editTextRealName = design.findViewById(R.id.realName_editTextProfileEdit);

        final EditText editTextSurname = design.findViewById(R.id.username_editTextProfileEdit);

        final EditText editTextEmail = design.findViewById(R.id.email_editTextProfileEdit);

        final EditText editTextPassword = design.findViewById(R.id.password_editTextProfileEdit);


        AlertDialog.Builder alertDialoga = new AlertDialog.Builder(ProfilePage.this);
        alertDialoga.setTitle("Edit Profile");
        alertDialoga.setView(design);
        alertDialoga.setPositiveButton("Finish", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String username = editTextUserName.getText().toString().trim();
                String realName = editTextRealName.getText().toString().trim();
                String surname = editTextSurname.getText().toString().trim();
                String email = editTextEmail.getText().toString().trim();
                String password = editTextPassword.getText().toString().trim();
                String admin = "false";
                String url = "test_url";


                String key = myRef.push().getKey();

                Users user = new Users(key,username,realName,surname,email,password,url,admin);


                HashMap<String,Object> data = new HashMap<>();

                data.put("user_email", email);
                data.put("user_name", realName);
                data.put("user_password", password);
                data.put("user_surname", surname);
                data.put("username", username);

                myRef.child(user.getUser_id()).updateChildren(data);

                Toast.makeText(ProfilePage.this, "Uptaded!", Toast.LENGTH_SHORT).show();
            }
        });

        alertDialoga.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });

        alertDialoga.show();
    }

My Create User Code's :

  // Sign Up Method
    // Kullanıcı Kayıt etme metodu
    public void signUp(View view) {
        UUID uuid = UUID.randomUUID();
        final String imageName = "ProfileImages/"+uuid+".jpg";
        final ProgressDialog dialog = new ProgressDialog(signupPage.this);
        dialog.setTitle("Creating user record.. ");
        dialog.setMessage("User registration is in progress..");
        dialog.show();
        StorageReference storageReference = mStorageRef.child(imageName);
        storageReference.putFile(image).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // Url

                StorageReference newReference = FirebaseStorage.getInstance().getReference(imageName);
                newReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {

                        dowloadURL = uri.toString();

                        if (dowloadURL != null) {
                            mAuth.createUserWithEmailAndPassword(emailText.getText().toString(), passwordText.getText().toString())
                                    .addOnCompleteListener(signupPage.this, new OnCompleteListener<AuthResult>() {
                                        @Override
                                        public void onComplete(@NonNull Task<AuthResult> task) {
                                            if (task.isSuccessful()) /* Kullanıcı girişi başarılı ise bu çalışacak */ {
                                                Toast.makeText(signupPage.this, "User Created", Toast.LENGTH_SHORT).show();
                                                String userName = user_name.getText().toString();
                                                String userSurname = user_surname.getText().toString();
                                                String username = user_username.getText().toString();
                                                String user_email = emailText.getText().toString();
                                                String key = myRef.push().getKey();
                                                String password = user_password.getText().toString();
                                                String imageURL = dowloadURL;

                                                Users user = new Users(key, userName, username, userSurname, user_email, password,imageURL, admin);
                                                myRef.push().setValue(user);
                                                Intent homePage = new Intent(signupPage.this, ProfilePage.class);
                                                startActivity(homePage);
                                                finish();
                                                dialog.dismiss();

                                            } else /* Kullanıcı girişi başarısız ise bu çalışacak */ {
                                               /*Intent signBack = new Intent(signupPage.this, signupPage.class);
                                                startActivity(signBack);
                                                finish(); */
                                                dialog.dismiss();
                                            }



                                        }
                                    }).addOnFailureListener(signupPage.this, new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    Toast.makeText(signupPage.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }


                    }
                });


            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(signupPage.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });


    }

The download url comes from a separate image selection method, by the way. My user creation codes are like this.

6
  • 2
    What isn't working about this code? Did you try a simpler version of that code (e.g. just writing a single, hard-coded value)? Did that work? Commented Jul 31, 2019 at 14:13
  • 1
    The code is running but not updating, adding new records. I haven't tried the simpler part.But in a course I was looking at it was simple and working. But when I try adding a new user with a different id. Commented Jul 31, 2019 at 14:20
  • Check my answer. As to @FrankvanPuffelen: He is using the push() method as a key, so that creates a new user every time. That is the error. Commented Jul 31, 2019 at 14:22
  • @YılmazYağızDokumacı Check my answer now. Commented Jul 31, 2019 at 14:38
  • 1
    @TaraIordanov okey, i check now. Commented Jul 31, 2019 at 14:45

2 Answers 2

4

Your problem is that instead of storing a constant and valid key in your firebase database, every time you change your profile you create a new node. How so? Well, you do this:

String key = myRef.push().getKey();

Which every time creates a new node(that is why the push is there) and you get the key of that node. That is also why you create a new user, instead of updating your account profile. The correct way to do it is the following.

When creating your user get the key with this:

String key = FirebaseAuth.getInstance().getCurrentUser().getUid();

After you create your User Object with this key, do the following:

myRef.child(key).setValue(user);

When you want to update your user, you can access the key the same way you created it. After getting all the update information and the key, then do:

myRef.child(key).setValue(data); //For updating

or

myRef.child(key).updateChildren(data); //For updating
Sign up to request clarification or add additional context in comments.

6 Comments

No didn't work. Of course I share the code by updating the question.
There are 1-2 points in your new answer that I don't understand. 1 - String key = myRef.push().getKey(); yerine String key = FirebaseAuth.getInstance().getCurrentUser().getUid(); kullanacağım değil mi? 2 - After using it, you can push the push myRef.child (key) .setValue (user); do with?
I tried and its worked thank you. But not listed my recyclerview.Could this have something to do with the method of creating a new uuid?
Could be if you have not attached the value listener to the reference of UID key. It should myRef.child(uid_key).addOnSingleValueEventListener.
I was pulling the key directly from the Users class. Now that I'm testing, it pulls the right key from the class, but it doesn't list it. My Users List Code : prntscr.com/omju1d (I used printscreen because imgur site is banned in my country.) I just used a query to list the logged-in user
|
1
//Get reference to update location 
DatabaseRefrence dR = FirebaseDatabase.getInstance().getRefrence().child(your child name in string);

//set value
Map<String, Object> hasMap = new HashMap<>();
hasmap.put("name","Ethrak");

//update reference 
dR.updateChildren(hashmap);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.