繁体   English   中英

使用 Firebase 在应用程序(Android Studio)中上传个人资料图片

[英]Uploading profile picture in app (Android Studio) using Firebase

我正在尝试制作一个功能,用户必须在注册时上传他们的个人资料图片。 但我的应用程序不断停止,既不上传详细信息,也不上传个人资料图片。 但如果我删除上传图片的代码,它工作正常。 所以图片上传有问题。 请帮我解决它-

public class SelectRegistrationActivity extends AppCompatActivity {

private TextView back;
private TextView fullName,email,phone,password,regButton,gender,age;
String flag="False";
private CircleImageView dp;
//private Uri result;
private Uri filePath;

// request code
private final int PICK_IMAGE_REQUEST = 22;
FirebaseAuth mAuth;
DatabaseReference userDatabaseRef;
ProgressDialog loader;
FirebaseDatabase database= FirebaseDatabase.getInstance();
String currentUserId;
FirebaseStorage storage;
StorageReference storageReference;

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

    back = findViewById(R.id.back);//inside bracket is id given to sign in button in activity_select_registration.xml
    //the other back are just variable names

    fullName = findViewById(R.id.fullName);
    email = findViewById(R.id.email);
    phone = findViewById(R.id.phone);
    password = findViewById(R.id.password);
    regButton = findViewById(R.id.regButton);
    gender = findViewById(R.id.gender);
    age = findViewById(R.id.age);
    dp = findViewById(R.id.dp);

    loader = new ProgressDialog(this);
    mAuth = FirebaseAuth.getInstance();

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

    FirebaseUser user = mAuth.getInstance().getCurrentUser();
    userDatabaseRef = database.getReference().child("All Users");

    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(SelectRegistrationActivity.this, AccountSelectionActivity.class);
            startActivity(intent);
        }
    });

    dp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        
            flag="True";
            SelectImage();
        }
    });

    regButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Email,Password etc are variables
            final String Email = email.getText().toString().trim();
            final String Password = password.getText().toString().trim();
            final String FullName = fullName.getText().toString().trim();
            final String Phone = phone.getText().toString().trim();
            final String Gender = gender.getText().toString().trim();
            final String Age = age.getText().toString().trim();


            if (TextUtils.isEmpty(Email)) {
                email.setError("Email is required!");
                return;
            }

            if (TextUtils.isEmpty(Password)) {
                password.setError("Password is required!");
                return;

            }

            if (TextUtils.isEmpty(FullName)) {
                fullName.setError("Name is required!");
                return;

            }

            if (TextUtils.isEmpty(Phone)) {
                phone.setError("Phone number is required!");
                return;

            }

            if (TextUtils.isEmpty(Gender)) {
                gender.setError("Gender is required!");
                return;

            }

            if (TextUtils.isEmpty(Age)) {
                age.setError("Age is required!");
                return;

            }

            if (flag.equals("False")) {
                Toast.makeText(SelectRegistrationActivity.this, "Upload profile picture!", Toast.LENGTH_SHORT).show();
                return;
            }
            else {
                loader.setMessage("Registration in process....");
                loader.setCanceledOnTouchOutside(false);
                loader.show();

                mAuth.createUserWithEmailAndPassword(Email, Password)
                        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                if (!task.isSuccessful()) {
                                    String error = task.getException().toString();
                                    Toast.makeText(SelectRegistrationActivity.this,
                                            "Error occurred:" + error, Toast.LENGTH_SHORT).show();
                                } else {
                                    String currentUserId = mAuth.getCurrentUser().getUid();
                                    userDatabaseRef = database.getReference().child("All Users").child(currentUserId);
                                    //HashMap userInfo = new HashMap();
                                    HashMap userInfo = new HashMap();
                                    userInfo.put("Name", FullName);
                                    userInfo.put("Email", Email);
                                    userInfo.put("Age", Age);
                                    userInfo.put("Gender", Gender);
                                    userInfo.put("Phone", Phone);
                                    userInfo.put("Password", Password);
                                    userInfo.put("Type", "Patient");

                                    //userDatabaseRef.setValue(userInfo);

                                   
                                    uploadImage();

                                    userDatabaseRef.updateChildren(userInfo).addOnCompleteListener(new OnCompleteListener() {
                                        @Override
                                        public void onComplete(@NonNull Task task) {
                                            if (task.isSuccessful()) {
                                                Toast.makeText(SelectRegistrationActivity.this, "Details set Successful", Toast.LENGTH_SHORT).show();

                                            } else {
                                                Toast.makeText(SelectRegistrationActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();

                                            }

                                        }
                                    });

   

                                }

                            }
                        });

                finish();//takes user to screen 1
                loader.dismiss();
            }

        }
    });
}

// Select Image method
private void SelectImage()
{

    // Defining Implicit Intent to mobile gallery
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Image from here..."), PICK_IMAGE_REQUEST);
}

// Override onActivityResult method
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        // Get the Uri of data
        filePath = data.getData();
        try {

            // Setting image on image view using Bitmap
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            dp.setImageBitmap(bitmap);
        }

        catch (IOException e) {
            // Log the exception
            e.printStackTrace();
        }
    }
}

// UploadImage method
private void uploadImage()
{
    if (filePath != null) {

        // Defining the child of storageReference
        StorageReference ref = storageReference.child("Patient/"+currentUserId);

        // adding listeners on upload
        // or failure of image
        ref.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(SelectRegistrationActivity.this, "Image Uploaded!!", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

}

这是logcat-

2022-08-24 18:07:09.903 12588-12588/? E/.example.hisss: Unknown bits set in runtime_flags: 0x800000
2022-08-24 18:07:11.013 12588-12651/com.example.hissss E/LB: fail to open file: No such file or directory

在 storageReference.child 之前使用 New 关键字并运行代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM