从模拟器SD卡文件夹-Android中读取图像

时间:2014-08-05 09:55:48

标签: android gridview android-emulator android-sdcard

我尝试在我的应用程序中读取sdcard文件夹中的图像。但是,在平板电脑设备上完成没有任何错误的任务,它列出了Gridview中文件夹中的所有图像,但是在模拟器中,只显示空的Gridview列表,尽管文件夹和图片存在于Emulator SD卡上,如下图所示?!

enter image description here

用于创建文件夹和读取图片的类:

实用程序代码:

package com.example.imageslider.helper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;

import com.example.classes.DBItems;
import com.example.classes.ProjectEngine;
import com.example.diwansalesorder.MainScreen;
import com.example.diwansalesorder.R;
import com.example.imageslider.GridViewActivity;

public class Utils {

    private final Context _context;
    ArrayList<String> allData = new ArrayList<String>();
    // Progress Dialog
    private ProgressDialog pDialog;
    ArrayList<String> filePaths;
    File sdCard, directory;
    File[] listFiles;

    // constructor
    public Utils(Context context) {
        this._context = context;
    }

    /*
     * Reading file paths from SDCard
     */
    public ArrayList<String> getFilePaths() {
        filePaths = new ArrayList<String>();
        boolean success = true; // to check if directory created ot not
        readAllItems();
        sdCard = Environment.getExternalStorageDirectory();
        directory = new File(sdCard.getAbsolutePath() + "/DiwanAppPictures");

        if (!directory.exists()) {
            success = directory.mkdirs();
        }
        if (success) {
            // check for directory
            if (directory.isDirectory()) {
                // getting list of file paths
                listFiles = directory.listFiles();
                // Check for count
                if (listFiles.length > 0) {
                    new LoadAllPictures().execute();

                } else {
                    new LoadAllPictures2().execute();

                }

            } else {
                AlertDialog.Builder alert = new AlertDialog.Builder(_context);
                alert.setTitle("Error!");
                alert.setMessage(AppConstant.PHOTO_ALBUM
                        + " directory path is not valid! Please set the image directory name AppConstant.java class");
                alert.setPositiveButton("OK", null);
                alert.show();

            }

        } else {
            Toast.makeText(_context,
                    " can't create " + AppConstant.PHOTO_ALBUM + " folder !!",
                    Toast.LENGTH_LONG).show();
            Intent prevIntent = new Intent(_context, MainScreen.class);
            _context.startActivity(prevIntent);

        }
        return filePaths;
    }

    /*
     * Check supported file extensions
     * 
     * @returns boolean
     */
    private boolean IsSupportedFile(String filePath) {
        String ext = filePath.substring((filePath.lastIndexOf(".") + 1),
                filePath.length());

        if (AppConstant.FILE_EXTN
                .contains(ext.toLowerCase(Locale.getDefault())))
            return true;
        else
            return false;

    }

    /*
     * getting screen width
     */
    @SuppressLint("NewApi")
    public int getScreenWidth() {
        int columnWidth;
        WindowManager wm = (WindowManager) _context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();

        final Point point = new Point();
        try {
            display.getSize(point);
        } catch (java.lang.NoSuchMethodError ignore) { // Older device
            point.x = display.getWidth();
            point.y = display.getHeight();
        }
        columnWidth = point.x;
        return columnWidth;
    }

    // Function to read all items from data base
    private void readAllItems() {
        final DBItems dbI = new DBItems(_context);

        try {
            dbI.open();
            Cursor allTitles = dbI.getAllAccounts();
            allTitles.moveToFirst();

            do {
                String Item = allTitles.getString(1);
                String Name = allTitles.getString(2);
                String Cprice = allTitles.getString(3);
                String Ccurr = allTitles.getString(4);
                String Sprice = allTitles.getString(5);
                String Scurr = allTitles.getString(6);
                String Qnty = allTitles.getString(7);
                String IncVat = allTitles.getString(8);
                String StQnty = allTitles.getString(9);
                String MinQnty = allTitles.getString(10);
                String MaxQnty = allTitles.getString(11);
                String Class = allTitles.getString(12);
                String StkLoc = allTitles.getString(13);
                String currQnty = allTitles.getString(14);
                String VatDate = allTitles.getString(15);
                String Ttime = allTitles.getString(16);

                allData.add(Item + "!" + Name + "!" + Cprice + "!" + Ccurr
                        + "!" + Sprice + "!" + Scurr + "!" + Qnty + "!"
                        + IncVat + "!" + StQnty + "!" + MinQnty + "!" + MaxQnty
                        + "!" + Class + "!" + StkLoc + "!" + currQnty + "!"
                        + VatDate + "!" + Ttime + "");

            } while (allTitles.moveToNext());

            dbI.close();

        } catch (Exception e) {
            e.printStackTrace();
            dbI.close();

        }
    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllPictures2 extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(_context);
            pDialog.setMessage(ProjectEngine.fillDataMsg);
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        @Override
        protected String doInBackground(String... args) {
            // Load Image from res
            try {
                for (int i = 0; i < allData.size(); i++) {
                    OutputStream fOut = null;
                    File file = new File(directory,
                            allData.get(i).split("!")[0].toString() + ".jpeg");

                    if (file.exists())
                        file.delete();

                    file.createNewFile();
                    fOut = new FileOutputStream(file);
                    Drawable ditemp = _context.getResources().getDrawable(
                            R.drawable.nopicture);
                    Bitmap image = ((BitmapDrawable) ditemp).getBitmap();
                    image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
                    fOut.flush();
                    fOut.close();
                }

            } catch (Exception e) {
                // Log.e("saveToExternalStorage()", e.getMessage());
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            try {
                Thread.sleep(1000);

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Intent prevIntent = new Intent(_context, GridViewActivity.class);
            _context.startActivity(prevIntent);
            pDialog.dismiss();
        }
    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllPictures extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(_context);
            pDialog.setMessage(ProjectEngine.fillDataMsg);
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        @Override
        protected String doInBackground(String... args) {
            // loop through all files
            for (int i = 0; i < listFiles.length; i++) {
                // get file path
                String filePath = listFiles[i].getAbsolutePath();

                // check for supported file extension
                if (IsSupportedFile(filePath)) {
                    // Add image path to array list
                    filePaths.add(filePath);
                }
            }
            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {

            pDialog.dismiss();
        }
    }
}

请任何帮助将被挪用,

1 个答案:

答案 0 :(得分:0)

很可能是保存图片的目录路径存在问题。请将手机上 Environment.getExternalStorageDirectory()方法返回的值与模拟器上返回的值进行比较。它们可能不同,因此您可能需要相应地移动图像。