如何从sqlite数据库插入和检索图像?

时间:2016-06-22 09:18:35

标签: android android-sqlite

我正在开发一个Android应用程序,其中的数据将从sqlite中获取,这里我能够插入和检索字符串值,但现在我想插入并检索图像?任何人都可以帮助我。

这是我的DBAdapter类,我在其中创建数据库,列并在其中插入数据。

public class DBAdapter {

    public static final String KEY_ROWID = "_id";
    public static final String Product = "product";
    public static final String Price = "price";
    public static final String InStock = "instock";
    public static final String OutOfStock = "outofstock";
    //public static final String imgs = "img";
    private static final String TAG = "CountriesDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private static final String DATABASE_NAME = "World";
    private static final String SQLITE_TABLE = "Country";
    private static final int DATABASE_VERSION = 1;

    private final Context mCtx;

    private static final String DATABASE_CREATE =
            "CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
                    KEY_ROWID + " integer PRIMARY KEY autoincrement," +
                    Product + "," +
                    Price + "," +
                    InStock + "," +
                    OutOfStock + "," +
                    " UNIQUE (" + Product +"));";

    private static class DatabaseHelper extends SQLiteOpenHelper {

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


        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.w(TAG, DATABASE_CREATE);
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
            onCreate(db);
        }
    }

    public DBAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    public DBAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;

    }

    public void close() {
        if (mDbHelper != null) {
            mDbHelper.close();
        }
    }

    public long createCountry(String product, String price,
                              String instock, String outofstock) {

        ContentValues initialValues = new ContentValues();
        initialValues.put(Product, product);
        initialValues.put(Price, price);
        initialValues.put(InStock, instock);
        initialValues.put(OutOfStock, outofstock);
//        initialValues.put(imgs,img);
        return mDb.insert(SQLITE_TABLE, null, initialValues);
    }

    public boolean deleteAllCountries() {

        int doneDelete = 0;
        doneDelete = mDb.delete(SQLITE_TABLE, null , null);
        Log.w(TAG, Integer.toString(doneDelete));
        return doneDelete > 0;

    }

   /* public Cursor fetchCountriesByName(String inputText) throws SQLException {
        Log.w(TAG, inputText);
        Cursor mCursor = null;
        if (inputText == null  ||  inputText.length () == 0)  {
            mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
                            Product, Price, InStock, OutOfStock},
                    null, null, null, null, null);

        }
        else {
            mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
                            Product, Price, InStock, OutOfStock},
                    Product + " like '%" + inputText + "%'", null,
                    null, null, null, null);
        }
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }*/

    public Cursor fetchAllCountries() {

        Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
                        Product, Price, InStock, OutOfStock},
                null, null, null, null, null);

        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    public void insertSomeCountries() {

        createCountry("NOKIA X201","10,000","InStock","OutOfStock");
        createCountry("SAMSUNG Galaxy Note","30,000","OutOfStock","InStock");
        createCountry("IPHONE 6S+","65,000","InStock","OutOfStock");
        createCountry("MOTO G2","12,999","InStock","OutOfStock");
        createCountry("IBALL ANDY", "11,000", "OutOfStock", "InStock");
        createCountry("MOTO G4", "13,999", "InStock", "OutOfStock");
        createCountry("SONY XPERIA", "8,000", "OutOfStock", "InStock");

    }

}

3 个答案:

答案 0 :(得分:0)

试试这个,

在数据库

中插入image作为byte array
public void addImage( String name, byte[] image) throws SQLiteException{
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues cv = new  ContentValues();
    cv.put(KEY_NAME,    name);
    cv.put(KEY_IMAGE,   image);
    database.insert( DB_TABLE, null, cv );
}

检索图片

 byte[] image = cursor.getBlob(1);

注意:

  1. 在插入数据库之前,您需要先将Bitmap图像转换为字节数组,然后使用数据库查询应用它。

  2. 从数据库中检索时,您肯定有一个图像字节数组,您需要做的是将字节数组转换回原始图像。因此,您必须使用BitmapFactory来解码

答案 1 :(得分:0)

我的建议是避免将图像存储在数据库中。将映像存储在磁盘上并在数据库中写入路径会快得多。

但是如果您仍想将图像写入数据库,可以在此处找到解决方案:writing image to dbwritting image to db2

您必须使用BLOB(二进制大对象)将图像存储在sqlite数据库中。

答案 2 :(得分:0)

使用

将Bitmap图像转换为byteArray
  

将位图转换为ByteArray。

Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.myImage);
ByteArrayOutputStream opstream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, opstream);
byte[] bytArray = opstream.toByteArray();

然后将其存储到数据库中。

然后使用

接收byteArray
byte[] imageArray = cursor.getBlob(YOUR_COLUMN_POSITION);

之后使用

将byte []转换为Bitmap
  

将ByteArray转换为位图。

Bitmap bitmap = BitmapFactory.decodeByteArray(bytArray, 0, bytArray.length);
ImageView img = (ImageView) findViewById(R.id.imgv1);
img.setImageBitmap(bitmap);

这可能对你有帮助。