Android SQLite-将图像存储在数据库中

时间:2018-10-15 01:47:05

标签: android sqlite blob android-bitmap

我正在尝试将图像存储到我在android应用程序中创建的表中。该表有八列(整数id,字符串名称,字符串摘要,字符串imdb,字符串poster1Url,位图poster1,字符串poster2Url,位图poster2)。

这是我的表格代码:

public class Favorite {

        public static final String TABLE_NAME = "notes";

        public static final String COLUMN_ID = "id";
        public static final String COLUMN_NAME = "name";
        public static final String COLUMN_SUMMARY = "summary";
        public static final String COLUMN_IMDB = "imdb";
        public static final String COLUMN_POSTER_MEDIUM_URL = "posterMediumUrl";
        public static final String COLUMN_POSTER_MEDIUM = "posterMedium";
        public static final String COLUMN_POSTER_ORIGINAL_URL = "posterOriginalUrl";
        public static final String COLUMN_POSTER_ORIGINAL = "posterOriginal";

        private int id;
        private String name;
        private String summary;
        private String imdb;
        private String posterMediumUrl;
        private Bitmap posterMedium;
        private String posterOriginalUrl;
        private Bitmap posterOriginal;


        // Create table SQL query
        public static final String CREATE_TABLE =
                "CREATE TABLE " + TABLE_NAME + "("
                        + COLUMN_ID + " INTEGER PRIMARY KEY,"
                        + COLUMN_NAME + " TEXT,"
                        + COLUMN_SUMMARY + " TEXT,"
                        + COLUMN_IMDB + " TEXT,"
                        + COLUMN_POSTER_MEDIUM_URL + " TEXT,"
                        + COLUMN_POSTER_MEDIUM + " blob,"
                        + COLUMN_POSTER_ORIGINAL_URL + " TEXT,"
                        + COLUMN_POSTER_ORIGINAL + " blob"
                        + ")";

        public Favorite() {
        }

    public Favorite(int id, String name, String summary, String imdb, String posterMediumUrl, Bitmap posterMedium, String posterOriginalUrl, Bitmap posterOriginal) {
        this.id = id;
        this.name = name;
        this.summary = summary;
        this.imdb = imdb;
        this.posterMediumUrl = posterMediumUrl;
        this.posterMedium = posterMedium;
        this.posterOriginalUrl = posterOriginalUrl;
        this.posterOriginal = posterOriginal;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public String getImdb() {
        return imdb;
    }

    public void setImdb(String imdb) {
        this.imdb = imdb;
    }

    public String getPosterMediumUrl() {
        return posterMediumUrl;
    }

    public void setPosterMediumUrl(String posterMediumUrl) {
        this.posterMediumUrl = posterMediumUrl;
    }

    public Bitmap getPosterMedium() {
        return posterMedium;
    }

    public void setPosterMedium(Bitmap posterMedium) {
        this.posterMedium = posterMedium;
    }

    public String getPosterOriginalUrl() {
        return posterOriginalUrl;
    }

    public void setPosterOriginalUrl(String posterOriginalUrl) {
        this.posterOriginalUrl = posterOriginalUrl;
    }

    public Bitmap getPosterOriginal() {
        return posterOriginal;
    }

    public void setPosterOriginal(Bitmap posterOriginal) {
        this.posterOriginal = posterOriginal;
    }
}

这是我的DataBaseHelper:

public class DatabaseHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "favorites_db";


    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {

        // create favorites table
        db.execSQL(Favorite.CREATE_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + Favorite.TABLE_NAME);

        // Create tables again
        onCreate(db);
    }

    public long insertFavorite(Favorite favorite) {
        // get writable database as we want to write data
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(Favorite.COLUMN_ID, favorite.getId());
        values.put(Favorite.COLUMN_NAME, favorite.getName());
        values.put(Favorite.COLUMN_SUMMARY, favorite.getSummary());
        values.put(Favorite.COLUMN_IMDB, favorite.getImdb());
        values.put(Favorite.COLUMN_POSTER_MEDIUM_URL, favorite.getPosterMediumUrl());
        values.put(Favorite.COLUMN_POSTER_MEDIUM, Utility.getPictureByteOfArray(favorite.getPosterMedium()));
        values.put(Favorite.COLUMN_POSTER_ORIGINAL_URL, favorite.getPosterOriginalUrl());
        values.put(Favorite.COLUMN_POSTER_ORIGINAL, Utility.getPictureByteOfArray(favorite.getPosterOriginal()));

        // insert row
        long id = db.insert(Favorite.TABLE_NAME, null, values);

        // close db connection
        db.close();

        // return newly inserted row id
        return id;
    }

    public Favorite getFavorite(long id) {
        // get readable database as we are not inserting anything
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(Favorite.TABLE_NAME,
                new String[]{Favorite.COLUMN_ID, Favorite.COLUMN_NAME, Favorite.COLUMN_SUMMARY, Favorite.COLUMN_IMDB, Favorite.COLUMN_POSTER_MEDIUM_URL, Favorite.COLUMN_POSTER_MEDIUM, Favorite.COLUMN_POSTER_ORIGINAL_URL, Favorite.COLUMN_POSTER_ORIGINAL},
                Favorite.COLUMN_ID + "=?",
                new String[]{String.valueOf(id)}, null, null, null, null);

        Favorite favorite = null;

        if (cursor != null && cursor.moveToFirst()) {
            // prepare favorite object
            favorite = new Favorite(
                    cursor.getInt(cursor.getColumnIndex(Favorite.COLUMN_ID)),
                    cursor.getString(cursor.getColumnIndex(Favorite.COLUMN_NAME)),
                    cursor.getString(cursor.getColumnIndex(Favorite.COLUMN_SUMMARY)),
                    cursor.getString(cursor.getColumnIndex(Favorite.COLUMN_IMDB)),
                    cursor.getString(cursor.getColumnIndex(Favorite.COLUMN_POSTER_MEDIUM_URL)),
                    //null,
                    Utility.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex(Favorite.COLUMN_POSTER_MEDIUM))),
                    cursor.getString(cursor.getColumnIndex(Favorite.COLUMN_POSTER_ORIGINAL_URL)),
                    Utility.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex(Favorite.COLUMN_POSTER_ORIGINAL))));
                    //null);
            // close the db connection
            cursor.close();
        }
        return favorite;
    }

    public List<Favorite> getAllFavorites() {
        List<Favorite> favorites = new ArrayList<>();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + Favorite.TABLE_NAME;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Favorite favorite = new Favorite();
                favorite.setId(cursor.getInt(cursor.getColumnIndex(Favorite.COLUMN_ID)));
                favorite.setName(cursor.getString(cursor.getColumnIndex(Favorite.COLUMN_NAME)));
                favorite.setSummary(cursor.getString(cursor.getColumnIndex(Favorite.COLUMN_SUMMARY)));
                favorite.setImdb(cursor.getString(cursor.getColumnIndex(Favorite.COLUMN_IMDB)));
                favorite.setPosterMediumUrl(cursor.getString(cursor.getColumnIndex(Favorite.COLUMN_POSTER_MEDIUM_URL)));
                favorite.setPosterMedium(Utility.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex(Favorite.COLUMN_NAME))));
                favorite.setPosterOriginalUrl(cursor.getString(cursor.getColumnIndex(Favorite.COLUMN_POSTER_ORIGINAL_URL)));
                favorite.setPosterOriginal(Utility.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex(Favorite.COLUMN_NAME))));

                favorites.add(favorite);
            } while (cursor.moveToNext());
        }

        // close db connection
        db.close();

        // return favorites list
        return favorites;
    }

    public int getFavoritesCount() {
        String countQuery = "SELECT  * FROM " + Favorite.TABLE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);

        int count = cursor.getCount();
        cursor.close();


        // return count
        return count;
    }

    public void deleteFavorites(Favorite favorite) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(Favorite.TABLE_NAME, Favorite.COLUMN_ID + " = ?",
                new String[]{String.valueOf(favorite.getId())});
        db.close();
    }
}

在我的适配器中,我将此AsyncTask命名为从URL获取图像,转换为Bitmap并插入到我的表中:

public class SaveIntoDatabase extends AsyncTask<Favorite,Void,Void> {
        // can use UI thread here
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        // automatically done on worker thread (separate from UI thread)
        @Override
        protected Void doInBackground(Favorite... params) {
            Favorite favorite = params[0];
            System.out.println("Inicio");
            try {
                InputStream inputStream = new URL(favorite.getPosterMediumUrl()).openStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                //set bitmap value to Picture
                favorite.setPosterMedium(bitmap);
                System.out.println(bitmap);

            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                InputStream inputStream = new URL(favorite.getPosterOriginalUrl()).openStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                //set bitmap value to Picture
                favorite.setPosterOriginal(bitmap);
                System.out.println(bitmap);
                //add data to database
                db.insertFavorite(favorite);

            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Fim");
            return null;
        }
    }

然后我使用以下代码调用该异步任务:

TvShow tvShow = tvShowList.get(position);
                    SaveIntoDatabase task = new SaveIntoDatabase();
                    task.execute(new Favorite(Integer.parseInt(tvShow.getId()), tvShow.getName(), tvShow.getSummary(), tvShow.getTvShowExternals().getImdb(), tvShow.getTvShowImage().getMedium(), null, tvShow.getTvShowImage().getOriginal(), null));

这是将blob转换为位图的方法:

public static Bitmap getBitmapFromByte(byte[] image) {
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }

这是将位图转换为blob的方式:

public static byte[] getPictureByteOfArray(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
    return byteArrayOutputStream.toByteArray();
} 

对我来说,一切似乎都很好,但是当我尝试从表的结果中访问图片时,两张图片都显示“ null”。

0 个答案:

没有答案