【问题标题】:Cannot open image file stored in sdcard无法打开存储在 sdcard 中的图像文件
【发布时间】:2012-01-23 16:52:49
【问题描述】:

在我的应用程序中,我将 tableLayout 的内容保存为文件夹中的图像。为了允许用户从保存的图像中打开文件,我创建了一个包含这些文件名称的文本文件。这些文件名稍后将加载到一个数组(文件)中。用户单击“打开”以查看文件名列表并选择他要打开的文件名。我正在使用以下代码打开文件。

final String imageInSD = extStorageDirectory+"/myFolder/"+files[which];
//where 'files' is an array of strings and contains the names of files.
//and 'which' is the index of the selected element in the list  
Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);  
ImageView ivv=(ImageView) findViewById(R.id.imageView);
ivv.setImageBitmap(bitmap);

当我尝试它时没有任何反应,所以我尝试了以下

final String imageInSD = extStorageDirectory+"/myFolder/myFile.PNG";
Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);  
ImageView ivv=(ImageView) findViewById(R.id.imageView);
ivv.setImageBitmap(bitmap);

它会显示名为 myFile 的图像。 我已经检查过我是否获得了正确的文件名和路径,并且它似乎是正确的。 (当我单击列表中的 myFile.PNG 并显示我得到“/mnt/sdcard/myFolder/myFile.PNG”的路径时)。

为什么我使用第一个代码时它不起作用?

【问题讨论】:

    标签: android image sd-card


    【解决方案1】:

    字符串连接不是组合路径的好方法。最好使用File constructor

    File directory = new File(extStorageDirectory, "myFolder");
    File fileInDirectory = new File(directory, files[which]);
    Bitmap bitmap = BitmapFactory.decodeFile(fileInDirectory.getAbsolutePath());
    

    【讨论】:

    • 你的问题在别处,因为你的代码现在是正确的。确保files[which] 中没有多余的空格或其他不需要的字符(如换行符)。
    • 它工作!我不敢相信我花了 2 个小时寻找问题,因为它是如此明显。我的文件名中有“\n”:s。再次非常感谢。
    猜你喜欢
    • 2021-05-06
    • 1970-01-01
    • 2014-04-08
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    相关资源
    最近更新 更多