Попробуйте получить все изображения с SDCard, чтобы показать в виде галереи

Я пытаюсь получить все изображения, которые хранятся в SDCard, чтобы показать в виде галереи с помощью кода ниже. Но когда я использую ImageFilter, ничего не появляется, просто пустой экран без каких-либо ошибок. Любое предложение?

public class Galmix extends Activity {
    /** Called when the activity is first created. */

    private Gallery g;
    private ImageView imv;

    private Uri[] mUrls;
    String[] mFiles=null;

    class ImageFilter implements FilenameFilter
    {
        public boolean accept(File dir, String name)
        {
            return (name.endsWith(".JPG"));
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        File images = new File("/sdcard/");
        File[] imagelist = images.listFiles(new ImageFilter());
//      File[] imagelist = images.listFiles();
//      File[] imagelist = images.listFiles(new FilenameFilter(){   
//          @Override  
//          public boolean accept(File dir, String name){   
//              return ((name.endsWith(".JPG")));   
//          }
//       });  

//      File images = new File(Environment.getExternalStorageDirectory().toString()); 
//      images.mkdirs();
//      File[] imagelist = images.listFiles();

        mFiles = new String[imagelist.length];

        for(int i= 0 ; i< imagelist.length; i++){
            mFiles[i] = imagelist[i].getAbsolutePath();
        }

        mUrls = new Uri[mFiles.length];

        for(int i=0; i < mFiles.length; i++){
            mUrls[i] = Uri.parse(mFiles[i]);   
        }

//      i = (ImageView)findViewById(R.id.ImageView01);  
//        i.setImageResource(mImageIds[0]);

        g = (Gallery) findViewById(R.id.gallery);
        g.setAdapter(new ImageAdapter(this));
        g.setFadingEdgeLength(40);  
//      g.setOnItemClickListener(new OnItemClickListener() {
//          public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//              imv.setImageURI(mUrls[position]);               
//          }
//      });
    }

    public class ImageAdapter extends BaseAdapter {
        int mGalleryItemBackground;
        private Context mContext;

        public ImageAdapter(Context c) {
            mContext = c;
            TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
            mGalleryItemBackground = a.getResourceId(R.styleable.HelloGallery_android_galleryItemBackground, 0);
            a.recycle();
        }

        public int getCount() {
            return mUrls.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(mContext);

            i.setImageURI(mUrls[position]);            
            i.setLayoutParams(new Gallery.LayoutParams(150, 100));
            i.setScaleType(ImageView.ScaleType.FIT_XY);
            i.setBackgroundResource(mGalleryItemBackground);

            return i;
        }
    }
}

3 ответа

Это может быть полезно:

Drawable mImage;
// you can use loop over here
mImage = Drawable.createFromPath("pathName");

//create one Imageview & set its resource mImage

Я хотел бы предложить вам использовать MediaStore. Также проверьте наличие разрешений в файле манифеста

Вы это проверяли? File images = new File("/sdcard/"); возвращает актуальную корневую папку SDCard? Попробуйте использовать File images = Environment.getExternalStorageDirectory(); вместо.

Также добавьте строку Log.d ("Galmix", mFiles[i]); после mFiles[i] = imagelist[i].getAbsolutePath(); так что вы знаете, получаете ли вы список файлов или нет.

Также попробуйте

return (name.toUpperCase().endsWith(".JPG"));
Другие вопросы по тегам