简体   繁体   中英

Cordova Android - Getting all images from the device

Hi I want to make a gallery APP on Cordova 6.1.1

and I need to get all images from the device

I did this on my app's iOS version with "File" and "AssetsLib" plugins

https://github.com/glowmar/phonegap-plugin-assetslib

But I don't know how to do that on Android

Your problem can be divide into 2 sub problem

Problem 1 :- get all images on SD card

Solution :- Make a cordova Plugin or embed this method in one of your existing plugins . Call this method by using your custom cordova plugin action(say fetchAllImages) it will return path of all images in sd card. Hers is a cordova plugin I have made I have not tested it may work or you will get an idea :-

import java.util.ArrayList;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;

public class GalleryPlugin extends CordovaPlugin {

    private static final String ACTION_GET_ALL_IMAGES = "getAllImages";

    @Override
    public boolean execute(String action, CordovaArgs args,
            final CallbackContext callbackContext) throws JSONException {
        try {

            // if action is getAllImages
            if (ACTION_GET_ALL_IMAGES.equals(action)) {

                // DO operation in thread pool to avoid cordova thread blocking
                cordova.getThreadPool().equals(new Runnable() {
                    public void run() {

                        // Return list of images in JSON Array
                        callbackContext.success(new JSONArray(
                                getAllShownImagesPath(cordova.getActivity())));

                    }
                });

            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return super.execute(action, args, callbackContext);
    }

    /**
     * Getting All Images Path.
     *
     * @param activity
     *            the activity
     * @return ArrayList with images Path
     */
    private ArrayList<String> getAllShownImagesPath(Activity activity) {
        Uri uri;
        Cursor cursor;
        int column_index_data, column_index_folder_name;
        ArrayList<String> listOfAllImages = new ArrayList<String>();
        String absolutePathOfImage = null;
        uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

        String[] projection = { MediaColumns.DATA,
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME };

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

        column_index_data = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
        column_index_folder_name = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
        while (cursor.moveToNext()) {
            absolutePathOfImage = cursor.getString(column_index_data);

            listOfAllImages.add(absolutePathOfImage);
        }
        return listOfAllImages;
    }
}

problem 2 :- Now you have all image path in js side, you need to display images in cordova webView

Solution :- you can refer this post Load the image saved in sdcard in webview

Alternative :- You can implement your own gallery app and embed it in your cordova app.

I have created an Android Gallery Project which fetch and display all Images and folders in a Grid View -

https://github.com/hiteshsahu/AwesomeAndroid-Gallery

在此处输入图片说明

This function return Map of Image folders with folder name as Key and ArrayList of images as Value

public static Map<String, ArrayList<ImageDataModel>> getImageFolderMap(
            Activity activity) {

        imageFolderMap.clear();

        Uri uri;
        Cursor cursor;
        int column_index_data, column_index_folder_name;

        String absolutePathOfImage = null, folderName;
        uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

        String[] projection = { MediaColumns.DATA,
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME };

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

        column_index_data = cursor.getColumnIndexOrThrow(MediaColumns.DATA);

        column_index_folder_name = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);

        while (cursor.moveToNext()) {

            absolutePathOfImage = cursor.getString(column_index_data);

            folderName = cursor.getString(column_index_folder_name);

            ImageDataModel imDataModel = new ImageDataModel(folderName,
                    absolutePathOfImage);

            if (imageFolderMap.containsKey(folderName)) {

                imageFolderMap.get(folderName).add(imDataModel);

            } else {

                ArrayList<ImageDataModel> listOfAllImages = new ArrayList<ImageDataModel>();

                listOfAllImages.add(imDataModel);

                imageFolderMap.put(folderName, listOfAllImages);
            }
        }

        // Get all Internal images
        uri = android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI;

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

        column_index_data = cursor.getColumnIndexOrThrow(MediaColumns.DATA);

        column_index_folder_name = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);

        while (cursor.moveToNext()) {

            absolutePathOfImage = cursor.getString(column_index_data);

            folderName = cursor.getString(column_index_folder_name);

            ImageDataModel imDataModel = new ImageDataModel(folderName,
                    absolutePathOfImage);

            if (imageFolderMap.containsKey(folderName)) {

                imageFolderMap.get(folderName).add(imDataModel);
            } else {

                ArrayList<ImageDataModel> listOfAllImages = new ArrayList<ImageDataModel>();

                listOfAllImages.add(imDataModel);

                imageFolderMap.put(folderName, listOfAllImages);
            }

        }

        keyList = new ArrayList(imageFolderMap.keySet());

        return imageFolderMap;
    }

Creating custom plugin :- You can merge this function in Cordova Plugin

      /*
         * 
         * This Cordova plugin help to fetch all folders with images
         */

        public class ImageGalleryPlugin extends CordovaPlugin {

            priva

te static final String FETCH_ALL_IMAGES_ACTION = "fetchAllImages";
        private CallbackContext mCallbackContext;

        @Override
        public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) {

            this.mCallbackContext = callbackContext;

            if (FETCH_ALL_IMAGES_ACTION.equals(action)) {

                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {

                        mCallbackContext.success(new JSONObject(getImageFolderMap(cordova.getActivity())));

                    }
                });

                return true;
            }
            return false;

        }

        /*
         * Returns an Map of image folder with key = "folder name" and value =
         * "List Of Images in that Folder"
         * 
         * Retrieve image from folder Map by
         * 
         * 1) fetching all folder keys from Map :-
         * 
         * ArrayList<String> folderKeyList = new ArrayList(imageFolderMap.keySet());
         * 
         * 2) Retrive images in a folder by its index in folderKeyMap
         * 
         * ArrayList<ImageDataModel> imageList =
         * imageFolderMap.get(folderKeyList.get(indexOfFolder)) ;
         * 
         */
        public static Map<String, ArrayList<ImageDataModel>> getImageFolderMap(Activity activity) {

            String folderNameKey;

            // Map to store list of images with folder name as Key Value
            Map<String, ArrayList<ImageDataModel>> imageFolderMap = new HashMap<String, ArrayList<ImageDataModel>>();

            // Clear Map to avoid duplication of images
            imageFolderMap.clear();

            int columnIndexData, columnIndexFolderName, columnIndexImageName;

            // GET ALL EXTERNAL STORAGE IMAGES
            Uri uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

            // Query image path,name and folder name
            String[] projection = { MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
                    MediaStore.Images.Media.DISPLAY_NAME };

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

            columnIndexImageName = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);

            columnIndexData = cursor.getColumnIndexOrThrow(MediaColumns.DATA);

            columnIndexFolderName = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);

            // Iterate over all cursor data
            while (cursor.moveToNext()) {

                // Get folder Name of image
                folderNameKey = cursor.getString(columnIndexFolderName);

                // Fill data in image data Model
                ImageDataModel imDataModel = new ImageDataModel(
                        cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)),
                        cursor.getString(columnIndexFolderName), cursor.getString(columnIndexData));

                // If folder is already added in Map
                if (imageFolderMap.containsKey(folderNameKey)) {

                    // Add Image into Existing Arraylist of images in Map
                    imageFolderMap.get(folderNameKey).add(imDataModel);

                } else {

                    // If folder was not added add image into array list with folder
                    // name as key
                    ArrayList<ImageDataModel> listOfAllImages = new ArrayList<ImageDataModel>();

                    // Add image into array list
                    listOfAllImages.add(imDataModel);

                    // put array list into map with folder name
                    imageFolderMap.put(folderNameKey, listOfAllImages);
                }
            }

            // GET ALL INTERNALK STORAGE IMAGES
            uri = android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI;

            // Query image path,name and folder name
            cursor = activity.getContentResolver().query(uri, projection, null, null, null);

            while (cursor.moveToNext()) {

                folderNameKey = cursor.getString(columnIndexFolderName);

                ImageDataModel imDataModel = new ImageDataModel(cursor.getString(columnIndexImageName),
                        cursor.getString(columnIndexFolderName), cursor.getString(columnIndexData));

                // If folder is already added in Map
                if (imageFolderMap.containsKey(folderNameKey)) {

                    // Add image to Arraylist
                    imageFolderMap.get(folderNameKey).add(imDataModel);
                } else {

                    ArrayList<ImageDataModel> listOfImagesInFolder = new ArrayList<ImageDataModel>();

                    listOfImagesInFolder.add(imDataModel);

                    imageFolderMap.put(folderNameKey, listOfImagesInFolder);
                }

            }

            return imageFolderMap;
        }

    }

Add Model class to hold Data

Public class ImageDataModel {

    private String imageTitle, imagePath, imageFolder;

    public String getImageFolder() {
        return imageFolder;
    }

    public void setImageFolder(String imageFolder) {
        this.imageFolder = imageFolder;
    }

    /**
     * @return the imageTitle
     */
    public String getImageTitle() {
        return imageTitle;
    }

    /**
     * @param imageTitle
     *            the imageTitle to set
     */
    public void setImageTitle(String imageTitle) {
        this.imageTitle = imageTitle;
    }

    /**
     * @return the imagePath
     */
    public String getImagePath() {
        return imagePath;
    }

    /**
     * @param imagePath
     *            the imagePath to set
     */
    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }

    public ImageDataModel(String imageTitle, String imageFolder, String absolutePathOfImage) {
        this.imageTitle = imageTitle;
        this.imageFolder = imageFolder;
        this.imagePath = absolutePathOfImage;
    }

}
  • Usage :- You can then use this plugin like this

getAllImages: function(success,error,args){ 'use strict'; cordova.exec(success,error, "ImageGalleryPlugin", "fetchAllImages", args); },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM