我正在尝试将存储在“图片”目录中的图像显示为listView。在MainActivity中,我创建了如下变量:
//declare variables required for ListView
private String[] FilePathStrings; //holds file path of the images captured.
private String[] FileNameStrings; //holds name of the images captured.
private File[] listImage; //holds the images.
ListView list;
ListViewAdapter adapter;
File file;
然后在onCreate方法中,我调用populateListArray()来填充String和File数组。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Populate the list array with image and file name
populateListArray();
//create ListAdapter and bind it to ListView
createListAdapter();
}
和PopulateListArray()如下:
void populateListArray(){
// Check whether SD Card exists
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
.show();
} else {
// Locate the image folder in your SD Card
file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Pictures"); //'Pictures' is the folder where google cam
// stores pictures.
Log.i(MYTAG, "file = " +file); // file = /storage/sdcard0/Pictures
Log.i(MYTAG, "file.isDirectory = " +file.isDirectory()); // file.isDirectory() is always returning false
}
//If 'Pictures' directory exists then populate the corresponding arrays
if (file.isDirectory()) // following code is never executed as file.isDirectory() is always false.
{
listImage = file.listFiles();
Log.i(MYTAG, "listImage = " +listImage);
// Create a String array for FilePathStrings
FilePathStrings = new String[listImage.length];
Log.i(MYTAG, "FilePathStrings = " +listImage.length);
// Create a String array for FileNameStrings
FileNameStrings = new String[listImage.length];
for (int i = 0; i < listImage.length; i++) {
// Get the path of the image file
FilePathStrings[i] = listImage[i].getAbsolutePath();
// Get the name image file
FileNameStrings[i] = listImage[i].getName();
}
} //endif
}
以下是生成的调试代码:
07-24 23:07:30.417 26364-26364/com.example.lib.dailyselfie I/Lab-Selfie﹕ file = /storage/sdcard0/Pictures
07-24 23:07:30.417 26364-26364/com.example.lib.dailyselfie I/Lab-Selfie﹕ file.isDirectory = false
07-24 23:07:30.587 26364-26364/com.example.lib.dailyselfie D/libEGL﹕ loaded /system/lib/egl/libEGL_adreno200.so
07-24 23:07:30.647 26364-26364/com.example.lib.dailyselfie D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_adreno200.so
07-24 23:07:30.657 26364-26364/com.example.lib.dailyselfie D/libEGL﹕ loaded /system/lib/egl/libGLESv2_adreno200.so
我不明白为什么尽管'Pictures'是一个目录,file.isDirectory()仍然返回'false'?请帮忙。
答案 0 :(得分:0)
确保您拥有访问&#39;图片&#39;所需的权限。目录。 将以下内容添加到AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>