2

我正在尝试解决一个有点棘手的问题。我有一个通过自定义 BaseAdapter 从远程服务器获取图像的网格视图。相关代码如下。

//The gridview
pictureAdapter = new PictureAdapter(cont, document, thumbWidth);

GridView gridview = (GridView) findViewById(R.id.pictures_gridview);
gridview.setColumnWidth(thumbWidth);
gridview.setAdapter(pictureAdapter);

网格视图的定义非常简单......

//The adapter
public class PictureAdapter extends BaseAdapter {
    private Context mContext;
    private JSONArray mPics;
    private List<String> mThumbs;
    private List<String> mViews;
    private List<Integer> mIds;
    private int thumbWidth;
    private SparseArray<Bitmap> imageData;
    private boolean isFlinging;


    public PictureAdapter(Context c, JSONArray pics, int thumbWidth) {
        mContext = c;
        mPics = pics;
        this.thumbWidth = thumbWidth;
        setPicThumbs();
        imageData = new SparseArray<Bitmap>();

    }

    public void setFlinging(boolean isFlinging) {
        this.isFlinging=isFlinging;
    }

    public boolean getFlinging() {
        return this.isFlinging;
    }

    private void setPicThumbs() {
        mThumbs = new Vector<String>();
        mViews = new Vector<String>();
        mIds = new Vector<Integer>();
        for(int i=0; i<mPics.length(); i++) {
            JSONObject row;
            try {
                row = mPics.getJSONObject(i);
                mThumbs.add(row.getString("thumb"));
                mViews.add(row.getString("view"));
                mIds.add(row.getInt("id"));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

    public int getCount() {
        return mThumbs.size();
    }

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

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

    public void setThumbWidth(int width) {
        thumbWidth = width;
    }

    public List<String> getViews() {
        return mViews;
    }


    public View getView(final int position, final View convertView, ViewGroup parent) {
        final PycsellImageView imageView;
        String imageUrlDirty = mThumbs.get(position);
        String imageUrlClean = imageUrlDirty.split("\\?")[0];

        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new PycsellImageView(mContext, mIds.get(position));
            imageView.setLayoutParams(new GridView.LayoutParams(thumbWidth+3, thumbWidth+3));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(0, 0, 0, 0);
            //imageView.setVisibility(View.INVISIBLE);
        } else {
            imageView = (PycsellImageView) convertView;
            imageView.setPicId(mIds.get(position));
            if(imageView.getCurrentDrawable() != mThumbs.get(position) || isFlinging == true) {
                imageView.setImageDrawable(null);
                imageView.setCurrentDrawable("");
            }

           // imageView.setVisibility(View.INVISIBLE);
        }


        if(imageData.get(position) != null) {
            if (imageView.getDrawable() == null) {
                imageView.startFade();
            }
            imageView.setImageBitmap(imageData.get(position));
            imageView.setCurrentDrawable(mThumbs.get(position));
        } 

        else if (isFlinging == false) {
            //Log.d("Picture Adapter", "Getting album thumb: "+imageUrlClean);

            DownloadHelper downloadHelper = new DownloadHelper() {

                public void OnFailure(String response) {
                    Log.e("Picture Adapter", response);
                }

                public void OnSucess(Bitmap bitmap) {
                    if (imageView.getDrawable() == null) {
                        imageView.setImageBitmap(bitmap);
                        imageView.setCurrentDrawable(mThumbs.get(position));
                        imageView.startFade();
                    }
                    imageData.put(position, bitmap);
                }
            };

            new ImageTask(mContext, downloadHelper, imageUrlClean).execute();
        }

        return imageView;
    }

}

适配器中的大部分代码与此无关,但我将其完整呈现。您会注意到请求图像是通过 DownloadHelper AsyncTask 下载的,并放置在本地 SparseArray 中。如果必须再次显示图像,它将从此数组中获取,而不是重新下载。

显然,这是非常糟糕的,因为可能存在大量图像。这只是一个占位符解决方案。我显然想实现更强大的图像缓存,因为这些图像在下载后也必须离线可用。问题是……我不知道怎么做。

我已经实现了一个数据库......

public class PycsellDatabase extends SQLiteOpenHelper {
    private static final int DB_VERSION = 1;
    private static final String DB_NAME = "pycsell_data";

    public static final String TABLE_ALBUMS_IMAGES = "albums_and_images";
    public static final String ID="_id";
    public static final String COL_TYPE="type";
    public static final String COL_PYCID="pycsell_id";
    public static final String COL_THUMB="thumb";
    public static final String COL_VIEW="view";
    public static final String COL_ALBUM="album";
    public static final String COL_TITLE="title";
    public static final String COL_PICNUM="picnum";
    private static final String CREATE_TABLE_ALBUMS_IMAGES = "create table" + TABLE_ALBUMS_IMAGES + "("
            + ID + "integer primary key autoincrement"
            + COL_TYPE + "integer not null"
            + COL_PYCID + "integer not null"
            + COL_THUMB + "text not null"
            + COL_VIEW + "text"
            + COL_ALBUM +"integer"
            + COL_TITLE + "text"
            + COL_PICNUM + "integer);";

    private static final String DB_SCHEMA = CREATE_TABLE_ALBUMS_IMAGES;

    public PycsellDatabase(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DB_SCHEMA);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_ALBUMS_IMAGES);
        onCreate(db);
    }
}

...和(部分)内容提供者...

public class BitmapProvider extends ContentProvider {
    private PycsellDatabase pDB;
    private static final String AUTHORITY = "com.atlantbh.pycsell.db.BitmapProvider";
    public static final int ALBUMS=100;
    public static final int IMAGES=110;
    public static final int SINGLE_IMAGE=120;
    private static final String ALBUMS_IMAGES_BASE_PATH = "albums_images";
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + ALBUMS_IMAGES_BASE_PATH);
    public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE+"/album_image";
    public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE+"/album_image";

    private static final UriMatcher sURIMatcher = new UriMatcher(
            UriMatcher.NO_MATCH);
    static {
        sURIMatcher.addURI(AUTHORITY, ALBUMS_IMAGES_BASE_PATH, ALBUMS);
        sURIMatcher.addURI(AUTHORITY, ALBUMS_IMAGES_BASE_PATH + "/#", IMAGES);
        sURIMatcher.addURI(AUTHORITY, ALBUMS_IMAGES_BASE_PATH + "/#/#", SINGLE_IMAGE);
    }

    @Override
    public boolean onCreate() {
        pDB = new PycsellDatabase(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
        queryBuilder.setTables(PycsellDatabase.TABLE_ALBUMS_IMAGES);
        int uriType = sURIMatcher.match(uri);
        switch (uriType) {
        //1 = albums, 2 = images
        case ALBUMS:
            queryBuilder.appendWhere(PycsellDatabase.COL_TYPE+"= 1");
            break;

        case IMAGES: 
            queryBuilder.appendWhere(PycsellDatabase.COL_TYPE+"= 2");
            queryBuilder.appendWhere(PycsellDatabase.COL_ALBUM+"="+uri.getLastPathSegment());
            break;

        case SINGLE_IMAGE:
            List<String> segments = uri.getPathSegments();
            queryBuilder.appendWhere(PycsellDatabase.COL_TYPE+"= 2");
            queryBuilder.appendWhere(PycsellDatabase.COL_ALBUM+"="+segments.get(0));
            queryBuilder.appendWhere(PycsellDatabase.COL_PYCID+"="+segments.get(1));
            break;
        }

        Cursor cursor = queryBuilder.query(pDB.getReadableDatabase(), projection, selection, selectionArgs, null, null, sortOrder);
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public String getType(Uri uri) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }
}

而且我相当确定我可以自己处理这些……我遇到的问题是实际的适配器。我知道如何实现游标适配器,但是我只能检查数据库,而不是执行“先下载,稍后从数据库获取”。我想逻辑是这样的:

  • 通过提供者查询图片
  • 将返回的光标传递给适配器
  • 如果光标为空(即该图像在数据库中没有条目),则下载并将其放入数据库

但是,我不是 100% 确定这是这样做的方法。任何帮助将不胜感激。

最好的问候,达米尔 H。

4

1 回答 1

0

我强烈建议使用Universal Image Loader库来下载和缓存图像

您可以将库作为 JAR 文件下载,该文件可以轻松包含到任何 Android 项目中

来自官方页面的功能:

  • 多线程图像加载
  • 可以广泛调整 ImageLoader 的配置(线程池大小、HTTP 选项、内存和磁盘缓存、显示图像选项等)
  • 在内存和/或设备的文件系统(或 SD 卡)中缓存图像的可能性
  • “听”加载过程的可能性
  • 可以使用单独的选项自定义每个显示图像调用
  • 小部件支持
于 2012-10-16T14:15:50.523 回答