从目录中读取图像

时间:2016-08-01 15:20:27

标签: android

我正在尝试从指定路径中的目录加载所有图像。使用if语句检查被调用的路径不会发出任何错误,也没有显示任何结果。我不介意去了解我的错误代码。

public class Edit extends Activity {

    // File representing the folder that you select using a FileChooser
    static final File dir = new File("/data/data/faceemoji.alexcz.yourfaceemoji/app_imageDir/");

    // array of supported extensions (use a List if you prefer)
    static final String[] EXTENSIONS = new String[]{
            "png" // and other formats you need
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);

        LinearLayout linearLayout = (LinearLayout)findViewById(R.id.linearlayout);

        Log.d("loadfilepath", dir.getAbsolutePath());
        if (dir.isDirectory()) { // make sure it's a directory
            System.out.println("yes");
            for (File f : dir.listFiles(IMAGE_FILTER)) {

                Log.d("fak", "file found");
                Bitmap myBitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
                ImageView myImage = new ImageView(this);
                myImage.setImageBitmap(myBitmap);
                linearLayout.addView(myImage);
            }
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_edit, menu);
        return true;
    }

    static final FilenameFilter IMAGE_FILTER = new FilenameFilter() {

        @Override
        public boolean accept(final File dir, final String name) {
            for (String ext : EXTENSIONS) {
                if (name.endsWith("." + ext)) {
                    return (true);
                }
            }
            return (false);
        }
    };
}

1 个答案:

答案 0 :(得分:1)

您应该使用Context.getFilesDir()进行内部存储,使用Environment.getExternalStorageDirectory()进行外部存储,如果您还想要编写文件,则必须使用最后一个添加WRITE_EXTERNAL_STORAGE

在你的情况下,我猜你应该这样做:

static final File dir = new File(Context.getFilesDir()+"/app_imageDir/");

即使你把一个日志检查目录是否正确