如何在没有按钮android studio

时间:2018-01-22 09:07:04

标签: android firebase firebase-realtime-database firebase-storage

如何在没有"上传"的情况下上传图片按钮并自动将该新图像用作默认用户图片?我如何在我的代码中实现它。

mAuth = FirebaseAuth.getInstance();
    circlePic = findViewById(R.id.circleImageView);
    FirebaseUser user = mAuth.getCurrentUser();
    if (user != null) {
        Glide.with(this)
                .load(user.getPhotoUrl())
                .into(circlePic);

 public void Profile(View view) {
    Intent cpicview = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(cpicview, 1);
} 



@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageRIntent) {
    super.onActivityResult(requestCode, resultCode, imageRIntent);
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK)
        mProfileUri = imageRIntent.getData();
    Uri selectedImage = imageRIntent.getData();
    this.circlePic.setImageURI(selectedImage);

1 个答案:

答案 0 :(得分:0)

首先向您的imageview添加点击监听器,该监听器将打开活动以选择图像

profileImage.setOnClickListener(new View.OnClickListener() 
{
   @Override
   public void onClick(View v) {
       Intent intent = new Intent();
       intent.setType("image/*");
       intent.setAction(Intent.ACTION_GET_CONTENT);
       startActivityForResult(Intent.createChooser(intent, "Select Profile Image"), REQUEST_CODE);
   }        
});

然后实施将在选择图像时执行的 onActivityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == REQUEST_CODE) {
            InputStream inputStream = context.getContentResolver().openInputStream(data.getData());
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            uploadImage(bitmap);
    }
}

这是上传Bitmap的方法

private void uploadImage(Bitmap bitmap) 
{
    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReferenceFromUrl("Your url for storage");
    StorageReference mountainImagesRef = storageRef.child("images/" + chat_id + Utils.getCurrentTimeStamp() + ".jpg");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
    byte[] data = baos.toByteArray();
    UploadTask uploadTask = mountainImagesRef.putBytes(data);
    uploadTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle unsuccessful uploads
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            Uri downloadUrl = taskSnapshot.getDownloadUrl();
            Log.d(downloadUrl);
        }
    });
}

并且不要忘记在班级中声明 REQUEST_CODE

public static final int REQUEST_CODE = 1;

并且您可能需要在xml中为您的个人资料图片视图添加此行

android:clickable="true"