What is required to serve as an adapter with setAdapter()?

177 views Asked by At

AdapterView in question is GridView. I'm wondering what is exactly meant by "The setAdapter() method then sets a custom adapter (ImageAdapter) as the source for all items to be displayed in the grid." in this android official guide. Is it the getView() method?

My objective, is to create a gridview that gets inputs from a SD card directory, and not the resource folder. So instead of working with resources' ID's, i will work with absolute paths.

I am trying to set something like:

    adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);        
    gridview.setAdapter(new ImageAdapter(this, mImgFilenames));

With the image adapter being:

public class ImageAdapter extends BaseAdapter {
private Context mContext;
private List<String> mPaths;

// Store the list of image IDs
public ImageAdapter(Context c, List<String> paths) {
    mContext = c;
    this.mPaths = paths;
}

// Return the number of items in the Adapter
@Override
public int getCount() {
    return mPaths.size();
}

// Return the data item at position
@Override
public Object getItem(int position) {
    return mPaths.get(position);
}

// Will get called to provide the ID that
// is passed to OnItemClickListener.onItemClick()
@Override
public long getItemId(int position) {
    return 0;
}

// Return an ImageView for each item referenced by the Adapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ImageView imageView = (ImageView) convertView;
    if (imageView == null) {
     //typical code for new view
    }

    //load the image    
    Bitmap bmImg = BitmapFactory.decodeFile((String) getItem(position));
    imageView.setImageBitmap(bmImg);
    return imageView;
}

}

So I am not talking about what are the mandatory methods to implement, but rather what is required of the adapter's infrastructure to serve as one. Speaking of which though, i have no idea what getItemId should return.

1

There are 1 answers

4
CommonsWare On BEST ANSWER

Your ImageAdapter should extend ArrayAdapter, not BaseAdapter. Then, you only really have to worry about getView() and nothing else.

And then override the constructor to load all the files from absolutes paths?

Please load the images asynchronously, using a library like Picasso. Do not do disk I/O on the main application thread. You can do that in getView() itself, as the images are needed.

how to add the paths manually to the actual array?

You already have an array of paths. It's called paths (as the constructor parameter to your current ImageAdapter) and mPaths (as the data member of your current ImageAdapter).