数据库初始化:
private final static String DBNAME = "Auction";
private final static int DBVERSION = 2;
SQLiteDatabase mDB5;
public final static String TBL_AUCTION = "Auction";
public final static String COL_AUCTION_ID = BaseColumns._ID;
public final static String COL_AUCTION_NAME = "name";
public final static String COL_AUCTION_DESCRIPTION = "description";
public final static String COL_AUCTION_PRICE = "price";
public final static String COL_AUCTION_DURATION = "duration";
public final static String COL_AUCTION_IMAGE = "image";
private String crt_tbl_auction = "CREATE TABLE IF NOT EXISTS " + TBL_AUCTION + "(" +
COL_AUCTION_ID + " INTEGER PRIMARY KEY, " +
COL_AUCTION_NAME + " TEXT, " +
COL_AUCTION_DESCRIPTION + " TEXT, " +
COL_AUCTION_PRICE + " TEXT, " +
COL_AUCTION_DURATION + " TEXT, " +
COL_AUCTION_IMAGE + " BLOB " +
")";
public DatabaseHelper5(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB5 = this.getWritableDatabase();
}
insertData:
public long insertData(String name, String description, String price, String duration,byte[] image) {
ContentValues cv = new ContentValues();
cv.put(COL_AUCTION_NAME, name);
cv.put(COL_AUCTION_DESCRIPTION, description);
cv.put(COL_AUCTION_PRICE, price);
cv.put(COL_AUCTION_DURATION, duration);
cv.put(COL_AUCTION_IMAGE,String.valueOf(image));
return mDB5.insert(TBL_AUCTION, null, cv);
}
getData:
public Cursor getDataV2() {
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {
COL_AUCTION_ID,
COL_AUCTION_IMAGE,
COL_AUCTION_NAME
};
return db.query(
TBL_AUCTION, // The table to query
projection, // The array of columns to return (pass null to get all)
null, null, null, null, BaseColumns._ID + " DESC"
);
}
MainActivity:
gridView = (GridView)findViewById(R.id.gridView);
list = new ArrayList<>();
adapter = new AuctionAdapter(this,R.layout.auction_items,list);
gridView.setAdapter(adapter);
myDB5 = new DatabaseHelper5(this);
wholegrid = myDB5.getDataV2();
if (sma == null) {
sma = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,wholegrid,
new String[]{DatabaseHelper5.COL_AUCTION_IMAGE, DatabaseHelper5.COL_AUCTION_NAME},
new int[]{android.R.id.text1,android.R.id.text2},
0
);
gridView.setAdapter(sma);
}
adapter.notifyDataSetChanged();
}
我无法将字符串图像转换回图像并显示在GridView
上。我将其转换为字符串的原因是,如果没有String.valueOf
,我的应用程序将崩溃,并显示错误消息,提示它无法将BLOB转换为字符串。我有什么办法可以最少地编辑代码来解决此问题?我只希望它能够检索图像数据并将图像显示到GridView
,仅此而已。欢迎任何方法。谢谢!