12

我是安卓新手。我创建了一个包含 itemName、Price 和 image 的表。我正在尝试检索图像和名称字段并将它们显示在网格视图上

这是我的创建数据库语句:

 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;
 } 

在我的 Main Oncreate 中,我像这样填充我的数据库:

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);

我现在卡住了,请谁能帮我检索这张图片并将其显示在网格视图上?

4

2 回答 2

15

最有效(顺便说一句,最直接的方法)是将图像的字节数组保存在本地数据库中。为此,您只需要在数据库中使用 TEXT 数据类型。像这样:

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

有一种无缝的方法可以避免处理转换:只需在您的 setter 和 getter 中转换为 Bitmap 并返回 bytearray,这样您就不需要在整个开发周期中关心它。让我们举个例子。假设你有一个对象用户,它存储在你的 localDB 中,你有一个头像。

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);
    }

}

无论您在哪里从数据库中检索数据,添加类似的内容就足够了:

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

对于相反的方式(将drawable写入DB):

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

最后,您的 ImageUtils 中有两个简单的方法可以来回转换:

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));
}

你可以走了。

于 2012-09-11T20:31:12.717 回答
1

这取决于您要如何存储图像,因为您存储为字节数组,这里是如何检索它

  public Cursor fetchAll() {
            return databaseHelper.query(ITEMS_TABLE, new String[] { COLUMN_ITEM_ID,   COLUMN_ITEM_NAME, COLUMN_ITEM_SPECS,COLUMN_ITEM_PRICE, COLUMN_ITEM_IMAGE,COLUMN_ITEM_QTY},null, null, null, null, null);
        }
/*    this method will give you a cursor with all the records of your database table now you need to parse these records on to objects*/

private List<ItemsPojo> parse(Cursor cursor) {
     List<ItemsPojo> toReturn = null;
     toReturn = new ArrayList<SignImage>();
     ItemsPojo obj;
     if (cursor.moveToFirst()) {
          while (cursor.isAfterLast() == false) {
               obj = new ItemsPojo();
               obj.setId(cursor.getInt(0));
               obj.setItemName(cursor.getString(1));
               obj.setItemSpecs(cursor.getString(2));
               obj.setItemPrice(cursor.getDouble(3));
               obj.setItemImg(cursor.getBlob(4));
               obj.setItemQuantity(cursor.getInt(5));
               toReturn.add(obj);
               cursor.moveToNext();
               }
     }return toReturn;
}

现在您的数据库中有一个包含所有记录的列表,现在您需要做的是创建一个 ListActivity 并在其上显示您的所有对象,如果您不知道如何执行此操作,请在此处发表您的评论或者如果您有任何疑问关于上述程序

于 2012-09-10T12:40:47.900 回答