java - 如何将不同 Activity 的数据保存到同一个表?

标签 java android firebase firebase-realtime-database firebase-authentication

下面是我的两项 Activity 的代码。通过这样的编码,数据像这样存储在 firebase 中。这是存储数据的快照:

这就是我得到的:

This is what I get

我想要的是这个

What I want is this

我知道发生这种情况是因为我有两个数据库类,但我尝试放入一个类,但没有成功。我认为这是因为我的代码

下面是我的代码:

Registration ACtivity`public class RegisterActivityUser extends AppCompatActivity {

    ImageView ImgUserPhoto;
    static int PReqCode=1;
    static int REQUESTCODE=1;
    Uri pickedImgUri;


    //*************** Firebase User Auth **********//
    private EditText userEmail, userPassword, userPassword2, userName, userWeight, userHeight;
    private ProgressBar loadingProgress;
    private Button regBtn;
    private FirebaseAuth mAuth;


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


        //*************** Login Account User *************//

        //Ini Views
        userEmail=findViewById(R.id.redMail);
        userPassword=findViewById(R.id.regPassword);
        userPassword2=findViewById(R.id.regPassword2);
        userName=findViewById(R.id.regName);
        loadingProgress=findViewById(R.id.progressBar);
        regBtn = findViewById(R.id.regBtn);
        loadingProgress.setVisibility(View.INVISIBLE);
        userWeight=findViewById(R.id.userWeight);
        userHeight=findViewById(R.id.userHeight);


        mAuth= FirebaseAuth.getInstance();

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

                regBtn.setVisibility(View.INVISIBLE);
                loadingProgress.setVisibility(View.VISIBLE);
                final String email=userEmail.getText().toString().trim();
                final String password=userPassword.getText().toString();
                final String password2=userPassword2.getText().toString();
                final String name=userName.getText().toString().trim();


                if (email.isEmpty() || name.isEmpty() || password.isEmpty() || password2.isEmpty() || !password.equals(password2)){

                    //something goes wrong, all fields must be filled
                    //we need to display error message
                    showMessage("Please Fill All Details Above");
                    regBtn.setVisibility(View.VISIBLE);
                    loadingProgress.setVisibility(View.INVISIBLE);
                }
                else {
                    //everything is okay
                    //Create New User Account

                    CreateUserAccount(email,name,password);


                }
            }
        }) ;


        ImgUserPhoto = findViewById(R.id.editUserPhoto) ;
        ImgUserPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT>=23){
                    checkAndRequestForPermission();
                }
                else {
                    openGallery();
                }
            }
        });

    }

    // ************* Create User Account  *************//
 private void CreateUserAccount(final String email, final String name, String password) {
        //this method to create user account with specific email and password;

        mAuth.createUserWithEmailAndPassword(email,password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()){
                            //user account created successfully

                            User user = new User(
                                    name,
                                    email
                            );

                            FirebaseDatabase.getInstance().getReference("Users")
                                    .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                                    .setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    //progressBar.setVisibility(View.GONE);
                                    if (task.isSuccessful()) {
                                        //acc successfully registered
                                        showMessage("Account Created");

                                        //after we created account, we need to update the user profile picture
                                        updateUserInfo (name ,pickedImgUri,mAuth.getCurrentUser());
                                    }

                                     else{
                                        showMessage("User Already Have Account" + task.getException().getMessage());
                                        regBtn.setVisibility(View.VISIBLE);
                                        loadingProgress.setVisibility(View.INVISIBLE);
                                    }

                                }
                            });


                            }
                        else {

                            // user account failed

                        }
                    }
                });

    }


    // ************* update user name and photo  ************* //
    private void updateUserInfo(final String name, Uri pickedImgUri, final FirebaseUser currentUser) {

        StorageReference mStorage = FirebaseStorage.getInstance().getReference().child("users_photos");
        final StorageReference imageFilePath = mStorage.child(pickedImgUri.getLastPathSegment());
        imageFilePath.putFile(pickedImgUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                //image Uploaded Successfully
                //now we can get our image URL

                imageFilePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {

                        //uri contain user image URL
                        UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
                                .setDisplayName(name)
                                .setPhotoUri(uri)
                                .build();

                        currentUser.updateProfile(profileUpdate)
                                .addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if(task.isSuccessful()){


                                            // User Profile has updated successfully

                                            showMessage("Register Complete");
                                            updateUI();
                                        }


                                    }
                                });


                    }
                });


            }
        });


    }

    private void updateUI() {

        Intent editProfileActivity = new Intent(RegisterActivityUser.this,EditProfileActivity.class);
        startActivity(editProfileActivity);
        finish();


    }

    // ************* simple method to toast message  *************//
    private void showMessage(String message) {

        Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
    }

    //  ************* Upload Picture  *************//
    private void openGallery() {
        //TODO: open gallery intent and wait user to pick an image!
        Intent galleryIntent=new Intent(Intent.ACTION_GET_CONTENT);
        galleryIntent.setType("image/*");
        startActivityForResult(galleryIntent,REQUESTCODE);

    }
    private void checkAndRequestForPermission() {
        if (ContextCompat.checkSelfPermission(RegisterActivityUser.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(RegisterActivityUser.this,Manifest.permission.READ_EXTERNAL_STORAGE)){
                Toast.makeText(RegisterActivityUser.this, "Please accept for required Permission",Toast.LENGTH_SHORT).show();
            }
            else
            {
                ActivityCompat.requestPermissions(RegisterActivityUser.this,
                        new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
                        PReqCode);
            }
        }
        else
        {
            openGallery();

        }
    }

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

        if (resultCode==RESULT_OK && requestCode == REQUESTCODE && data !=null){
            //the user has success picked an image
            //we need to save its as reference to a Uri Variable
            pickedImgUri=data.getData();
            ImgUserPhoto.setImageURI(pickedImgUri);

        }
    }
}
`

This one edit profile activity: `private void updateUserInfo(final String weight, final String height, final FirebaseUser currentUser) {

        /*Glide.with(this).load(currentUser.getPhotoUrl()).into(userImage);*/



       mAuth.updateCurrentUser(currentUser).addOnCompleteListener(this, new OnCompleteListener<Void>() {
           @Override
           public void onComplete(@NonNull Task<Void> task) {

               UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
                       .build();

               currentUser.updateProfile(profileUpdate)
                       .addOnCompleteListener(new OnCompleteListener<Void>() {
                           @Override
                           public void onComplete(@NonNull Task<Void> task) {
                               if(task.isSuccessful()){

                                   UserProfile user = new UserProfile (
                                           weight,
                                           height
                                   );

                                   FirebaseDatabase.getInstance().getReference("Users Profile")
                                           .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                                           .setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
                                       @Override
                                       public void onComplete(@NonNull Task<Void> task) {
                                           //progressBar.setVisibility(View.GONE);
                                           if (task.isSuccessful()) {
                                               //acc successfully registered
                                               showMessage("Account Updated");}

                                           else{

                                           }

                                       }
                                   });



                               }


                           }
                       });

最佳答案

替换这个:

 UserProfile user = new UserProfile (
       weight,
       height
 );

 FirebaseDatabase.getInstance().getReference("Users Profile")
       .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
       .setValue(user)

与:

Map<String, Object> values = new HashMap<>();
values.put("height", height);
values.put("weight", weight);
FirebaseDatabase.getInstance().getReference("Users")
       .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
       .updateChildren(values)

相关变更:

  • 调用 updateChildren 而不是 setValue,因为 setValue 会替换您调用它的位置处的所有数据。
  • 获取对 /Users 的引用,而不是 /Users Profile

附加提示:考虑将高度和体重存储为数值,而不是字符串。否则,它们的排序/过滤将会变得困惑,因为 Firebase 对字符串使用字典顺序。

关于java - 如何将不同 Activity 的数据保存到同一个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56614709/

相关文章:

java - android pie 9.0 mobile:org.json.JSONException:类型为java.lang.String的值CLEARTEXT无法转换为JSONObject

java - 如何在Oozie中为多个工作流指定集中位置

java - 在 Firebase 数据库中添加不同的键时遇到问题

android - map 未显示

javascript - Redux Thunk函数后的回调: Uncaught TypeError: Cannot read property 'then' of undefined

iOS10、Swift 3 和 FCM 委托(delegate)错误

firebase - 在 firebase 中,如何保护特定 key 的同时允许其他人访问

java - 使用中间表(中间实体)与两个 ManyToOne 进行 JPA 映射

java - 如何使用 java api 列出 Neo4j 数据库中的所有标签?

java - struts 2 中第二次 Action 不再触发