0

I need to open gallery to show images in a specific directory,after a search I follow this How to open gallery to show images in a specific directory

but the file.list returns me a null String[] on android 4.4 Than I write some test code:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listDirectory("ExternalStorageRoot",
            Environment.getExternalStorageDirectory());
    listDirectory(
            "DCIM",
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
    writeFileTest();

}

private void writeFileTest() {
    String tag = "WriteTest";
    String path = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES).getAbsolutePath();
    path = path + "/testFile.txt";
    Log.d(tag, "path : " + path);

    File file=new File(path);

    FileOutputStream fileOutputStream;
    try {
        fileOutputStream = new FileOutputStream(file);      
        fileOutputStream.write("THIS IS A TEST LINE".getBytes());
        fileOutputStream.flush();
        fileOutputStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }


}

private void listDirectory(String tag, File f) {
    Log.d(tag, "absolute path " + f.getAbsolutePath());
    Log.d(tag, "is dir " + f.isDirectory());
    Log.d(tag, "can read " + f.canRead());
    Log.d(tag, "can write " + f.canWrite());

    String[] fileNames = f.list();

    Log.d(tag, fileNames == null ? "fileNames is null"
            : "fileNames is not null");

    if (fileNames != null) {
        for (String string : fileNames) {
            Log.d(tag, "file -- " + string);
        }
    }
}

I also add these lines in AndroidManifest.xml

<permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<permission android:name="android.permission.WRITE_MEDIA_STORAGE" />
TO:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

EDIT: I mess up the permission.It's Now every thing works fine!

Community
  • 1
  • 1

1 Answers1

2

4.4 changed the file permissions for the sd card. You can't write outside of your personal directory anymore. See also: http://www.androidcentral.com/kitkat-sdcard-changes

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • I need to read image files from a specific folder and show these pictures.But now I can't read(without modify it) – Wooberlong Jul 09 '14 at 02:22
  • 1
    There's a lot of complaints about this change to 4.4. They really didn't handle it well. But you should be able to read files that are in common directories, its writing that should be banned, as I understand it. – Gabe Sechan Jul 09 '14 at 02:24