首页 > 解决方案 > 无法在 android studio 中以编程方式从外部存储中删除图像

问题描述

我是 Android Studio 的初学者 我只想帮助从文件夹中删除图像 这是我的代码 我已经添加了图像并添加了一个按钮以将其保存在外部文件夹中并且只想删除它

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button)findViewById(R.id.button1);
    imageview = (ImageView)findViewById(R.id.imageView1);
    bytearrayoutputstream = new ByteArrayOutputStream();

    button.setOnClickListener(new View.OnClickListener() {


        public void onClick(View v) {
            // TODO Auto-generated method stub


            Drawable drawable = getResources().getDrawable(R.drawable.barcode);

            Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();

            bitmap.compress(Bitmap.CompressFormat.PNG, 60, bytearrayoutputstream);

            file = new File( Environment.getExternalStorageDirectory() + "/SampleImage.png");

            try

            {
                file.createNewFile();

                fileoutputstream = new FileOutputStream(file);

                fileoutputstream.write(bytearrayoutputstream.toByteArray());

                fileoutputstream.close();

            }

            catch (Exception e)

            {

                e.printStackTrace();

            }


            Toast.makeText(MainActivity.this, "Image Saved Successfully", Toast.LENGTH_LONG).show();

        }
    });
}

如果您支持我获取知识,那将非常有帮助

标签: javaandroidfile

解决方案


final String where = MediaStore.MediaColumns.DATA + "=?";
final String[] selectionArgs = new String[]{
        f.getAbsolutePath()
};
final ContentResolver contentResolver = getContentResolver();
final Uri filesUri = MediaStore.Files.getContentUri("external");
contentResolver.delete(filesUri, where, selectionArgs);
// if (f.exists()) {
//     contentResolver.delete(filesUri, where, selectionArgs);
//     f.delete();
// }

推荐阅读