如何从Android设备INTERNAL Storage获取所有照片

时间:2015-05-27 02:14:12

标签: android

我是Android编程新手。我试图获取所有照片(或图像的路径)驻留在Android设备内部存储。我写了这样的函数 -

public static ArrayList<String> getImagesPath(Activity activity) {
    Uri uri;
    ArrayList<String> listOfAllImages = new ArrayList<String>();
    Cursor cursor;
    int column_index_data;
    String PathOfImage = null;
    uri = android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI;

    String[] projection = {MediaStore.MediaColumns.DATA};

    cursor = activity.getContentResolver().query(uri, projection, null, null, null);

    column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
    while (cursor.moveToNext()) {
        PathOfImage = cursor.getString(column_index_data);
        listOfAllImages.add(PathOfImage);
    }
    return listOfAllImages;
}

2 个答案:

答案 0 :(得分:2)

试试这个,希望它能为你效用

public ArrayList<String> getFilePaths()
{


    Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    String[] projection = {MediaStore.Images.ImageColumns.DATA};
    Cursor c = null;
    SortedSet<String> dirList = new TreeSet<String>();
    ArrayList<String> resultIAV = new ArrayList<String>();

    String[] directories = null;
    if (u != null)
    {
        c = managedQuery(u, projection, null, null, null);
    }

    if ((c != null) && (c.moveToFirst()))
    {
        do
        {
            String tempDir = c.getString(0);
            tempDir = tempDir.substring(0, tempDir.lastIndexOf("/"));
            try{
                dirList.add(tempDir);
            }
            catch(Exception e)
            {

            }
        }
        while (c.moveToNext());
        directories = new String[dirList.size()];
        dirList.toArray(directories);

    }

    for(int i=0;i<dirList.size();i++)
    {
        File imageDir = new File(directories[i]);
        File[] imageList = imageDir.listFiles();
        if(imageList == null)
            continue;
        for (File imagePath : imageList) {
            try {

                if(imagePath.isDirectory())
                {
                    imageList = imagePath.listFiles();

                }
                if ( imagePath.getName().contains(".jpg")|| imagePath.getName().contains(".JPG")
                        || imagePath.getName().contains(".jpeg")|| imagePath.getName().contains(".JPEG")
                        || imagePath.getName().contains(".png") || imagePath.getName().contains(".PNG")
                        )
                {



                    String path= imagePath.getAbsolutePath();
                    resultIAV.add(path);

                }
            }
            //  }
            catch (Exception e) {
                e.printStackTrace();
                FirebaseCrash.report(e);
            }
        }
    }

    return resultIAV;

}

您可以添加任何扩展程序以获取文件

答案 1 :(得分:0)

它返回null,因为cursor == null or cursor.getCount() == 0。这意味着您的内部存储空间中没有照片。

PS:使用后应释放光标。