使适配器更有效

时间:2016-05-09 15:49:46

标签: android gridview baseadapter

我试图制作一个自定义适配器,我做了功能,也许不是最好的方式,可能不是智能方式,所以我在这里问我能做些什么来使这个更有效率

public class MovieDataAdapter extends BaseAdapter implements FetchImage.AsyncResponse {
    private Context mContext;

    public MovieDataAdapter(Context context) {
        mContext = context;
    }


    @Override
    public int getCount() { // get coutn Method
        SQLiteDatabase db = new MvDBHelper(mContext).getReadableDatabase();
        Cursor cur = db.query(MovieContract.MovieEntry.TABLE_NAME, null, null, null, null, null, null);
        return cur.getCount();

    }

    @Override
    public Object getItem(int position) {
        return null;
    }//Not needed at the moment

    @Override
    public long getItemId(int position) {
        return 0;
    }// Not needed at the moment

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ImageView imageview;

        if (convertView != null) {
            imageview = (ImageView) convertView; //if used view just use ist again
        } else {//if new view set the fitting parameters
            imageview = new ImageView(mContext);
            imageview.setLayoutParams(new GridView.LayoutParams(getw('w'), getw('h')));
            imageview.setScaleType(ImageView.ScaleType.FIT_XY);

        }
        SQLiteDatabase picturedb = new MvDBHelper(mContext).getReadableDatabase();

        Cursor cur = picturedb.query(MovieContract.MovieEntry.TABLE_NAME,
                null, null, null, null, null, null
        );//get the entries from the db


        if (cur != null && cur.moveToFirst()) {

            cur.moveToPosition(position); // move to the appropriate position
            //defining nessesary Variables
            int index_PosterPath = cur.getColumnIndex(MovieContract.MovieEntry.COL_POSTERPATH);
            int index_FilePath = cur.getColumnIndex(MovieContract.MovieEntry.COL_FILE);
            int index_ortTitel = cur.getColumnIndex(MovieContract.MovieEntry.COL_ORTITEL);
            final String Filename = cur.getString(index_ortTitel) + ".jpg";
            final String selection = MovieContract.MovieEntry.COL_ORTITEL + " = ?";
            final String[] where = {cur.getString(index_ortTitel)};

            picturedb.close();// db not needed so is closed

            if (cur.isNull(index_FilePath)) {//if file not already saved in the storage save it there

                FetchImage getImage = new FetchImage(mContext, new FetchImage.AsyncResponse() {

                    @Override
                    public void processfinished(Bitmap output) { // get the image as an Bitmap in asynchronus task throug interface callback
                        FileOutputStream fos = null;
                        try {
                            fos = mContext.openFileOutput(Filename, Context.MODE_PRIVATE);
                            if (fos != null)
                                output.compress(Bitmap.CompressFormat.PNG, 100, fos); //put bitmap in file
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            if (fos != null) {
                                try {
                                    fos.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }

                            ContentValues values = new ContentValues();
                            values.put(MovieContract.MovieEntry.COL_FILE, Filename);
                            SQLiteDatabase picwr = new MvDBHelper(mContext).getWritableDatabase();
                            int updated = picwr.update(MovieContract.MovieEntry.TABLE_NAME, values, selection, where);
                            //put the filname in the db for later use
                            picwr.close();

                        }
                        BitmapDrawable draw = new BitmapDrawable(mContext.getResources(), output);
                        Drawable gridimag = draw;
                        imageview.setImageDrawable(gridimag); // set the drawable as an image
                    }
                });

                String[] ptg = {cur.getString(index_PosterPath)};
                getImage.execute(ptg);
            } else { // if pic already saved in the internal storage get it from there
                FileInputStream fis = null;
                try {
                    fis = mContext.openFileInput(Filename);
                    Bitmap pic = BitmapFactory.decodeStream(fis);
                    BitmapDrawable draw = new BitmapDrawable(mContext.getResources(), pic);
                    Drawable gridimag = draw;
                    imageview.setImageDrawable(gridimag);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }


            cur.close();
        }


        return imageview;
    }

    public int getw(char c) {

        int DisplayWidth = mContext.getResources().getDisplayMetrics().widthPixels;

        if (c == 'w') {
            return (int) (DisplayWidth / 2);
        } else {
            return DisplayWidth;
        }
    }

    public static float convertDpToPixel(float dp, Context context) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        float px = dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
        return px;
    }

    @Override
    public void processfinished(Bitmap output) {

    }
}

对于我能得到的每一个帮助都会感到高兴,即使它是一个完整的新方法因为目前网格视图不能流畅地工作

1 个答案:

答案 0 :(得分:0)

每次绘制单元格时都应避免关闭光标。只有在完成活动后才能关闭它。

此外,您还需要避免使用cur.moveToFirst()。因为您已经将光标移动到给定位置,为什么我要先移动它?

使用图像加载器库(Picasso是最好的之一)来加载异步和更快的另一个技巧。如果未显示视图,它还会处理停止线程。更优化。

每次需要新单元格时,都不需要找到coloumn的索引。找到他们一次,每次都使用它们:)

此外,您可以使用CursorAdapter类更好地实现它:)