如何存储和检索的Andr​​oid SQLite数据库的图像和一个GridView显示出来图像、数据库、oid、Andr

2023-09-04 23:09:58 作者:一场空梦

我是新来的机器人。我创建了一个具有了itemname,价格和图像的表。我想检索图像和名称场和一个GridView显示出来。

I am new to android. I created a table that has an itemName,Price and image. I am trying to retrieve the image and name fields and display them on a gridview

下面是我的CREATE DATABASE语句:

Here is my create Database statement:

 DBAdapter class onCreate()
 db.execSQL("CREATE TABLE "+ITEMS_TABLE+" ( "+ COLUMN_ITEM_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_ITEM_NAME +" TEXT, "+ COLUMN_ITEM_SPECS +" TEXT, " + COLUMN_ITEM_PRICE +
" NUMBER, " + COLUMN_ITEM_IMAGE + " BLOB, " + COLUMN_ITEM_QTY +" NUMBER)");

void AddItems(ItemsPojo itemsObj) 

{ 
     Log.i("in here", "item fields");           
     SQLiteDatabase db= DBHelper.getWritableDatabase(); 

    if (db==null) 
    { 
        Log.i("nulll", "mnllllsg"); 
    } 
    ContentValues cv=new ContentValues(); 
    cv.put(COLUMN_ITEM_NAME, itemsObj.getItemName()); 
    cv.put(COLUMN_ITEM_SPECS, itemsObj.getItemSpecs());
    cv.put(COLUMN_ITEM_PRICE, itemsObj.getItemPrice());
    cv.put(COLUMN_ITEM_QTY, itemsObj.getItemQty());
    cv.put(COLUMN_ITEM_IMAGE, itemsObj.getItemImg()); 




 long affectedColumnId = db.insert(ITEMS_TABLE, null, cv);
    db.close(); 

} 

public Bitmap  getAllImages() 
 { 
     SQLiteDatabase db=DBHelper.getWritableDatabase(); 




  //Cursor cur= db.rawQuery("Select "+colID+" as _id , "+colName+", "+colAge+" from "+employeeTable, new String [] {}); 
     Cursor cur= db.rawQuery("SELECT * FROM "+ITEMS_TABLE,null); 
     //if(cur.getCount() > 0){
         //Cursor c = mDb.query(" ... "); 
         cur.moveToFirst(); 




 ByteArrayInputStream inputStream = new ByteArrayInputStream(cur.getBlob(cur.getColumnIndex(COLUMN_ITEM_IMAGE))); 
         Bitmap b = BitmapFactory.decodeStream(inputStream); 
    // }
 return b;
 } 

在我的主要的onCreate我填充我的数据库是这样的:

In my Main Oncreate I populate my Database like this:

Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.red_bn);       
        ByteArrayOutputStream out = new ByteArrayOutputStream();      
        image.compress(Bitmap.CompressFormat.PNG, 100, out); 

        byte[] b = out.toByteArray();   
        String name; 
        name="QUEEN_BED1"; 
        String specs = "blaBlaBla";
        double price = 5420;
        int qty = 10;
        ItemsPojo itemsObj = new ItemsPojo(name,specs,price,b,qty); 




    db.AddItems(itemsObj);

我现在卡住,请谁能帮我找回这幅画和一个GridView显示呢?

I am now stuck, please can anyone help me to retrieve this picture and display it on a gridview?

推荐答案

最有效(和BTW,最直接的方法)是保存图像的字节组在本地数据库中。对于你只需要使用文本数据类型在数据库中。像这样的:

The most efficient (and btw, most straight forward approach) is to save a bytearray of the image in your local database. For that you'll just need to use a TEXT datatype in your database. Like this:

CREATE TABLE IF NOT EXISTS Your_table ( id INTEGER PRIMARY KEY NOT NULL UNIQUE, someOtherField TEXT, pictureData TEXT);

还有一个无缝的方式,以避免处理转换:只是转换为位图,并回到你的getter和setter方法​​,以字节组中,你并不需要关心,在整个开发周期的这样一种方式。 让我们去的例子。比方说,你已经存储在你的LocalDB您拥有一个化身对象的用户。

There's one seamless way to avoid dealing with conversions: Just convert to Bitmap and back to bytearray in your setters and getters in such a way that you don't need to care about that in the whole dev cycle. Let's go for an example. Let's say you have an object user which is stored in your localDB for which you have an avatar.

public class User {

    private String email;
    private String name;
    private Drawable pictureDataDrawable;

    public User() {}

    public void setPictureData(byte[] pictureData) {
        pictureDataDrawable = ImageUtils.byteToDrawable(pictureData);
    }

    public byte[] getPictureData(){
        return ImageUtils.drawableToByteArray(pictureDataDrawable);
    }

}

和无论你从数据库检索数据这将是足以与添加类似的东西:

And wherever you retrieve your data from DB it'll be enough with adding something like that:

user.setPictureData(cursor.getBlob(cursor.getColumnIndexOrThrow(DB_PICTURE_DATA_KEY)));

有关相反的方向(写绘制到DB):

For the opposite way (writing the drawable to DB):

ContentValues c = new ContentValues();
c.put(DB_PICTURE_DATA_KEY, user.getPictureData());
...

最后两个简单的方法,你ImageUtils到来回转换:

Finally two easy methods in your ImageUtils to convert back and forth:

public static byte[] drawableToByteArray(Drawable d) {

    if (d != null) {
        Bitmap imageBitmap = ((BitmapDrawable) d).getBitmap();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] byteData = baos.toByteArray();

        return byteData;
    } else
        return null;

}


public static Drawable byteToDrawable(byte[] data) {

    if (data == null)
        return null;
    else
        return new BitmapDrawable(BitmapFactory.decodeByteArray(data, 0, data.length));
}

和你去好。