提问人:Pavlos Katsioulis 提问时间:2/2/2023 最后编辑:Sujith KumarPavlos Katsioulis 更新时间:2/3/2023 访问量:77
使用 activityResultLauncher 上传图片,将 URI 转换为位图
Uploading an image using activityResultLauncher , convert URI into bitmap
问:
我对此非常陌生,我正在努力将这些碎片放在一起,以便我得到我想要的结果。我真的不明白我做错了什么。问题是当我尝试放置个人资料照片时,当我按下所选照片以显示在图像视图上时,应用程序崩溃了,并且我收到一条消息,例如“URI 不能为空”。
public class Profile extends AppCompatActivity {
private ImageView ProfileImg;
private String Tag;
private Uri imagePath = null;
private Uri imageUriPath;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
progressBar = findViewById(R.id.progressBar);
Button btnUpload = findViewById(R.id.btnUploadPhoto);
Button btnLogOut = findViewById(R.id.btnLogOut);
ProfileImg = findViewById(R.id.profile_img);
/* START ACTIVITY FOR RESULT*/
btnLogOut.setOnClickListener(view -> {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(Profile.this,MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP));
finish();
});
ProfileImg.setOnClickListener(view -> {
Intent photoIntent = new Intent(Intent.ACTION_PICK);
photoIntent.setType("image/*");
NewStartActivityForResult.launch(photoIntent);
});
btnUpload.setOnClickListener(view -> {
uploadImage();
});
/*Select photo from device*/
}
private ActivityResultLauncher<Intent> NewStartActivityForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if (result.getResultCode() == Activity.RESULT_OK){
Intent GotResults = result.getData();
if(GotResults == null)
{
Log.d(Tag,"InitializedActivityLaunchers: intent data is null");
return;
}
Uri imageUriPath = GotResults.getData();
GetImageInView();
}
});
private void uploadImage() {
FirebaseStorage.getInstance().getReference("images/" + UUID.randomUUID().toString()).putFile(imagePath).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful())
{
Toast.makeText(Profile.this, "Image Uploaded!",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(Profile.this, "Something went Wrong!", Toast.LENGTH_SHORT).show();
}
}
});
}
private void GetImageInView(){
Bitmap bitmap = null;
try{
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUriPath);
}catch (IOException e){
e.printStackTrace();
}
}
我首先遇到了 startOnActivityResult 的问题,其中我通过命令有一行说已弃用,而 MediaStore.Images.Media.getBitmap 中有相同的“错误”,在 getBitmap 上已弃用,我尝试使用新方法观看教程和其他论坛,但我认为我无法将 activityResultLauncher 与 Bitmap 连接,因为 activityResultLauncher 的输出是 Intent,而 Bitmap 需要 URI。
答:
0赞
jayesh gurudayalani
2/2/2023
#1
在 中,只需按如下所述管理代码即可NewStartActivityForResult
从
Uri imageUriPath = GotResults.getData();
自
imageUriPath = GotResults.getData();
您正在声明和启动变量,而不仅仅是初始化
评论