更新用户个人资料后,我应该再次重新认证用户吗? Firebase Android

时间:2019-08-27 08:59:03

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

我使用Firebase身份验证创建了登录功能,并在Firebase实时数据库上注册了存储的用户。当我编辑配置文件时,数据库和身份验证已在表上成功更新,但是我发现的问题是应用程序。应用程序要求用户在更新配置文件后重新验证帐户。逻辑流程是当用户在编辑配置文件菜单上更新配置文件时,数据应存储到Firebase,然后存储到配置文件页面。

有些代码,我已经尝试过了。

编辑配置文件类Java

package co.id.roni.usertestapp;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.EmailAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;

public class EditProfileActivity extends AppCompatActivity implements View.OnClickListener {
    ImageView photoEditProfile;
    EditText namaEditProfile, passwordEditProfile, emailEditProfile;
    ImageButton btnSaveImageProfile;

    Uri photo_location;
    Integer photo_max = 1;

    DatabaseReference referenceEdit;
    StorageReference storageEdit;
    FirebaseAuth firebaseAuthEdit;
    FirebaseUser firebaseUserEdit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile);
        Button btnSaveEditProfile = findViewById(R.id.btn_save_edit);
        btnSaveImageProfile = findViewById(R.id.img_btn_upload_new_photo);
        btnSaveEditProfile.setOnClickListener(this);
        btnSaveImageProfile.setOnClickListener(this);

        photoEditProfile = findViewById(R.id.img_profil_edit);
        namaEditProfile = findViewById(R.id.edit_nama);
        emailEditProfile = findViewById(R.id.edt_email_profile);
        passwordEditProfile = findViewById(R.id.edt_pass_profile);

        firebaseAuthEdit = FirebaseAuth.getInstance();
        firebaseUserEdit = firebaseAuthEdit.getCurrentUser();
        referenceEdit = FirebaseDatabase.getInstance().getReference().child("Users").child(firebaseUserEdit.getUid());
        storageEdit = FirebaseStorage.getInstance().getReference().child("PhotoUsers").child(firebaseUserEdit.getUid());

        referenceEdit.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                namaEditProfile.setText(dataSnapshot.child("nama").getValue().toString());
                emailEditProfile.setText(dataSnapshot.child("email").getValue().toString());
                passwordEditProfile.setText(dataSnapshot.child("pass").getValue().toString());
                Picasso.get().load(dataSnapshot.child("url_photo_user").getValue().toString()).into(photoEditProfile);
            }

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

            }
        });

    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_save_edit) {
            saveEditProfile();
        }
        if (view.getId() == R.id.img_btn_upload_new_photo) {
            findPhoto();
        }
    }

    private void saveEditProfile() {
        final String email = emailEditProfile.getText().toString();
        final String pass = passwordEditProfile.getText().toString();

        firebaseUserEdit.updateEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    referenceEdit.getRef().child("email").setValue(emailEditProfile.getText().toString());
                }
                else{
                    Log.d("Pesan Error", "Gagal Update : "+task.getException());
                }
            }
        });
        firebaseUserEdit.updatePassword(pass).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    referenceEdit.getRef().child("pass").setValue(passwordEditProfile.getText().toString());
                }
                else{
                    Log.d("Pesan Error", "Gagal Update : "+task.getException());
                }
            }
        });
        referenceEdit.getRef().child("nama").setValue(namaEditProfile.getText().toString());
        if (photo_location != null) {
            StorageReference storageReference1 = storageEdit.child(System.currentTimeMillis() + "." + getFileExtension(photo_location));
            storageReference1.putFile(photo_location).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Task<Uri> task = taskSnapshot.getMetadata().getReference().getDownloadUrl();
                    task.addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            String uri_photo = uri.toString();
                            referenceEdit.getRef().child("url_photo_user").setValue(uri_photo);
                        }
                    });

                }
            }).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                    //pindah ke Profile
                    Bundle bundle = new Bundle();
                    bundle.putString("userId", firebaseUserEdit.getUid());
                    startActivity(new Intent(EditProfileActivity.this, ProfilUserActivity.class).putExtras(bundle));

                }
            });
        }
    }

    String getFileExtension(Uri uri) {
        ContentResolver contentResolver = getContentResolver();
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
    }

    public void findPhoto() {
        Intent pic = new Intent();
        pic.setType("image/*");
        pic.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(pic, photo_max);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == photo_max && resultCode == RESULT_OK && data != null && data.getData() != null) {
            photo_location = data.getData();
            Picasso.get().load(photo_location).centerCrop().fit().into(photoEditProfile);
        }
    }
}

剖析页面类Java

package co.id.roni.usertestapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;

public class ProfilUserActivity extends AppCompatActivity implements View.OnClickListener {
    TextView namaProfile, emailProfile;
    ImageView photoImageProfile;
    FirebaseAuth firebaseAuthMain;
    FirebaseUser user;
    DatabaseReference profileDb;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profil_user);
        Button btnEditProfile = findViewById(R.id.btn_edit_profile);
        Button btnSignOut = findViewById(R.id.btn_sign_out);
        namaProfile = findViewById(R.id.tv_nama_profil);
        emailProfile = findViewById(R.id.tv_email_profil_page);
        photoImageProfile = findViewById(R.id.img_profile_page);

        firebaseAuthMain = FirebaseAuth.getInstance();
        user = firebaseAuthMain.getCurrentUser();

        showProfile();

        btnEditProfile.setOnClickListener(this);
        btnSignOut.setOnClickListener(this);
    }

    private void showProfile() {
        profileDb = FirebaseDatabase.getInstance().getReference().child("Users").child(user.getUid());
        profileDb.getRef().addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                namaProfile.setText(dataSnapshot.child("nama").getValue().toString());
                emailProfile.setText(dataSnapshot.child("email").getValue().toString());
                Picasso.get().load(dataSnapshot.child("url_photo_user").getValue().toString()).centerCrop().fit().into(photoImageProfile);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.e("Pesan", "Gagal Load"+databaseError.getMessage());
            }
        });

    }

    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.btn_edit_profile){
            startActivity(new Intent(ProfilUserActivity.this, EditProfileActivity.class));
            finish();
        }
        if(view.getId() == R.id.btn_sign_out){
            startActivity(new Intent(ProfilUserActivity.this, UserMainActivity.class));
            finish();
        }

    }
}

我希望结果是应用程序可以在更新配置文件后意图对页面进行配置。我想感谢您的帮助。预先感谢

0 个答案:

没有答案