简体   繁体   中英

android how to load images from internal memory in gridview

I follow this tutorial http://vikaskanani.wordpress.com/2011/07/20/android-custom-image-gallery-with-checkbox-in-grid-to-select-multiple/ below is my code which load images from application internal memory and display using simple adapter but now i want to ad checkbox i found this tutorial which llad images from gallery i want to customize this sample code to load image from file location what do i do how do i change this code to load image from file location or how to customize its adapter to load my files what do i do help plz

  <!-----------------this is my code------>
  GridView gridView;
  SimpleAdapter simpleAdapter;

  gridView =(GridView)findViewById(R.id.grid);
  gridView.setOnItemClickListener(new OnItemClickListener(){
    public void onItemClick(AdapterView<?> parent, View view, int  
                    position,long id) {


    if(currentFiles[position].isDirectory())
    {
        root = new File("/data/data/com.myexample/files 
            /"+FileName(currentFilePath[position])+"/");

        Log.e("Root first",root+ " ");

        currentFiles = root.listFiles();

        inflateListView(currentFiles);
    }
    else if(currentFiles[position].isFile())
    {
               inflateListView(currentFiles);
    } } });

     private void inflateListView(File[] files){

   List<Map<String,Object>> listItems = new ArrayList<Map<String,Object>>();

  for(int i=0;i<files.length;i++)
  {      
    Map<String, Object> listItem = new HashMap<String, Object>();

    if(files[i].isDirectory())
    {
        listItem.put("icon", R.drawable.folder);
    }
    else
    {
        listItem.put("icon",  files[i]);
    }

    listItem.put("fileName", files[i].getName());
    listItems.add(listItem);
   }

    simpleAdapter=new SimpleAdapter(this,listItems,R.layout.line,new String[] 
    {"icon","fileName"},new int[]{R.id.icon,R.id.file_name});
     gridView.setAdapter(simpleAdapter);




   <!--------this is sample code which load images from Gallery--------->>>>>>


  import android.widget.CheckBox;
  import android.widget.GridView;
  import android.widget.ImageView;
  import android.widget.Toast;

  public class AndroidCustomGalleryActivity extends Activity {
  private int count;
  private Bitmap[] thumbnails;
  private boolean[] thumbnailsselection;
  private String[] arrPath;
  private ImageAdapter imageAdapter;

   /** Called when the activity is first created. */
   @Override
  public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  final String[] columns = { MediaStore.Images.Media.DATA, 
   MediaStore.Images.Media._ID };
  final String orderBy = MediaStore.Images.Media._ID;
  Cursor imagecursor = managedQuery(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, 
   null,
        null, orderBy);
  int image_column_index =  
   imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
   this.count = imagecursor.getCount();
  this.thumbnails = new Bitmap[this.count];
  this.arrPath = new String[this.count];
  this.thumbnailsselection = new boolean[this.count];
  for (int i = 0; i < this.count; i++) {
    imagecursor.moveToPosition(i);
    int id = imagecursor.getInt(image_column_index);
    int dataColumnIndex = 
   imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
    thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
            getApplicationContext().getContentResolver(), id,
            MediaStore.Images.Thumbnails.MICRO_KIND, null);
    arrPath[i]= imagecursor.getString(dataColumnIndex);
  }
  GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
  imageAdapter = new ImageAdapter();
  imagegrid.setAdapter(imageAdapter);
  imagecursor.close();

  final Button selectBtn = (Button) findViewById(R.id.selectBtn);
  selectBtn.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub
        final int len = thumbnailsselection.length;
        int cnt = 0;
        String selectImages = "";
        for (int i =0; i<len; i++)
        {
            if (thumbnailsselection[i]){
                cnt++;
                selectImages = selectImages + arrPath[i] + 
 "|";
            }
        }
        if (cnt == 0){
            Toast.makeText(getApplicationContext(),
                    "Please select at least one image",
                    Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(),
                    "You've selected Total " + cnt +  
 "  
     image(s).",
                    Toast.LENGTH_LONG).show();
            Log.d("SelectedImages", selectImages);
        }
    }
    });
 }

  public class ImageAdapter extends BaseAdapter {
   private LayoutInflater mInflater;

   public ImageAdapter() {
    mInflater = (LayoutInflater) 
     getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  }

   public int getCount() {
    return count;
   }

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

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

     public View getView(int position, View convertView, ViewGroup parent) {
     ViewHolder holder;
        if (convertView == null) {
        holder = new ViewHolder();
        convertView = mInflater.inflate(
                R.layout.galleryitem, null);
        holder.imageview = (ImageView)  
    convertView.findViewById(R.id.thumbImage);
        holder.checkbox = (CheckBox)  
   convertView.findViewById(R.id.itemCheckBox);

        convertView.setTag(holder);
    }
    else {
        holder = (ViewHolder) convertView.getTag();
    }
    holder.checkbox.setId(position);
    holder.imageview.setId(position);
    holder.checkbox.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            CheckBox cb = (CheckBox) v;
            int id = cb.getId();
            if (thumbnailsselection[id]){
                cb.setChecked(false);
                thumbnailsselection[id] = false;
            } else {
                cb.setChecked(true);
                thumbnailsselection[id] = true;
            }
        }
    });
    holder.imageview.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            int id = v.getId();
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse("file://" + 
  arrPath[id]), "image/*");
            startActivity(intent);
        }
    });
    holder.imageview.setImageBitmap(thumbnails[position]);
    holder.checkbox.setChecked(thumbnailsselection[position]);
    holder.id = position;
    return convertView;
 }
 }
  class ViewHolder {
ImageView imageview;
CheckBox checkbox;
int id;
   }
 }

generally speaking you should create some collection of images files and than use BitmapFactory to load them like this:

    public static Bitmap getBitmapFromFile(File bitmapFile, int sideSizeLimit){
      if (bitmapFile==null || !bitmapFile.exists() || !bitmapFile.canRead())
          return null;
      int maxWidth = 0, maxHeight = 0;
      if (sideSizeLimit>0){
          maxWidth = sideSizeLimit;
          maxHeight = sideSizeLimit;
      }

      try {
          //decode image size
          BitmapFactory.Options bmfOtions = new BitmapFactory.Options();
          bmfOtions.inJustDecodeBounds = true;
          BitmapFactory.decodeStream(new FileInputStream(bitmapFile),null,bmfOtions);

          //Find the correct scale value. It should be the power of 2.
          //final int REQUIRED_SIZE=70;
          int width_tmp=bmfOtions.outWidth, height_tmp=bmfOtions.outHeight;
          int scale=1;
          while(width_tmp > maxWidth || height_tmp > maxHeight){
              width_tmp/=2;
              height_tmp/=2;
              scale++;
          }
          bmfOtions.inSampleSize = scale;
          bmfOtions.inJustDecodeBounds = false;

          //decode with inSampleSize
          //BitmapFactory.Options o2 = new BitmapFactory.Options();
          return BitmapFactory.decodeStream(new FileInputStream(bitmapFile), null, bmfOtions);
      } catch (FileNotFoundException e) {}
      return null;
  }

also you should read this http://developer.android.com/training/displaying-bitmaps/index.html ah, I found some example to start from (collecting files):

public static boolean clearImagesCache(){

    // depends on isExternalStorageAvailable()
    final File cacheDir= getCacheDir(); //new File(Environment.getExternalStorageDirectory() + SD_CACHE_PATH);

    if( !cacheDir.exists() )
        return false;

    final File[] files = cacheDir.listFiles();
    File file2delete;
    for(int i=0; i<files.length; i++) {
        file2delete = files[i]; 
       if(!file2delete.isDirectory() && file2delete.canWrite()) 
           file2delete.delete();
    }

    return true;
}

this code however deletes all of files in given directory but you have to collect them into some collection.

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