You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何我的Activity中出现java.lang.NullPointerException: uriString错误?

问题分析与修复方案

核心错误点

  • 初始化空指针异常:在onCreate开头直接执行String path = null; filepath = Uri.parse(path);,Uri.parse()不接受null参数,直接触发java.lang.NullPointerException: uriString错误。
  • filepath未更新:后续从Intent获取到正确图片路径path后,没有将其转为Uri赋值给filepath,导致调用uploadImage()时,filepath仍是初始化的错误值,上传功能失效。

修复后的完整代码

private Uri filepath;
FirebaseStorage storage;
StorageReference storageReference;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image_viewer);
    ImageView imageView = findViewById(R.id.imageView);
    storage = FirebaseStorage.getInstance();
    storageReference = storage.getReference();
    Intent intent = getIntent();
    String path = null;
    if (intent != null) {
        path = intent.getStringExtra("image");
        Glide.with(ImageViewerActivity.this).load(path).placeholder(R.drawable.ic_baseline_broken_image_24).into(imageView);
        // 从Intent获取路径后,转为Uri赋值给filepath
        if (path != null) {
            filepath = Uri.parse(path);
        }
    }
    ImageButton uploadClicks = findViewById(R.id.UploadClicks);
    uploadClicks.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            uploadImage();
        }
    });

    ImageButton share = findViewById(R.id.shareImage);
    String finalPath = path;
    share.setOnClickListener(v -> {
        if (finalPath != null) {
            new ShareCompat.IntentBuilder(ImageViewerActivity.this)
                    .setStream(Uri.parse(finalPath))
                    .setType("image/*")
                    .setChooserTitle("Share Image")
                    .startChooser();
        } else {
            Toast.makeText(ImageViewerActivity.this, "图片路径为空", Toast.LENGTH_SHORT).show();
        }
    });

    ImageButton delete = findViewById(R.id.deleteImage);
    delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (finalPath == null) {
                Toast.makeText(ImageViewerActivity.this, "图片路径为空,无法删除", Toast.LENGTH_SHORT).show();
                return;
            }
            MaterialAlertDialogBuilder alertDialogBuilder = new MaterialAlertDialogBuilder(ImageViewerActivity.this);
            alertDialogBuilder.setMessage("Are you sure you want to delete this image ?");
            alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String[] projection = new String[]{MediaStore.Images.Media._ID};
                    String selection = MediaStore.Images.Media.DATA + " = ?";
                    String[] selectionArgs = new String[]{new File(finalPath).getAbsolutePath()};
                    Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    ContentResolver contentResolver = getContentResolver();
                    Cursor cursor = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
                    if (cursor != null && cursor.moveToFirst()) {
                        long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
                        Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
                        try {
                            contentResolver.delete(deleteUri, null, null);
                            boolean delete1 = new File(finalPath).delete();
                            Log.e("TAG", delete1 + "");
                            Toast.makeText(ImageViewerActivity.this, "Deleted Successfully", Toast.LENGTH_SHORT).show();
                            finish();
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(ImageViewerActivity.this, "Error Deleting Video", Toast.LENGTH_SHORT).show();
                        }
                        cursor.close();
                    } else {
                        Toast.makeText(ImageViewerActivity.this, "File Not Find", Toast.LENGTH_SHORT).show();
                        if (cursor != null) {
                            cursor.close();
                        }
                    }
                }
            });
            alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            alertDialogBuilder.show();
        }
    });
}

private void uploadImage() {
    if (filepath != null) {
        ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading...");
        progressDialog.show();

        StorageReference ref = storageReference.child("images/" + UUID.randomUUID().toString());

        ref.putFile(filepath)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        progressDialog.dismiss();
                        Toast.makeText(ImageViewerActivity.this, "Image Uploaded!!", Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        progressDialog.dismiss();
                        Toast.makeText(ImageViewerActivity.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
                        progressDialog.setMessage("Uploaded " + (int) progress + "%");
                    }
                });
    } else {
        Toast.makeText(this, "图片路径为空,无法上传", Toast.LENGTH_SHORT).show();
    }
}

额外优化

  • 在分享、删除功能中增加路径为空的判断,避免潜在空指针异常。
  • 对Cursor增加非空校验,防止关闭时出现空指针。

内容的提问来源于stack exchange,提问作者user19697344

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 22:36:20