//1.建立數據庫sql
public class DBService extends SQLiteOpenHelper { 數據庫
private final static int VERSION = 1;app
private final static String DATABASE_NAME = "uniteqlauncher.db"; ide
public DBService(Context context) {this
this(context, DATABASE_NAME, null, VERSION);orm
} 對象
public DBService(Context context, String name, CursorFactory factory,圖片
int version) {get
super(context, name, factory, version);it
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE [launcher]("
+ "[_id] INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "[photo] BINARY)"; //保存爲binary格式
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion > oldVersion){
db.execSQL("DROP TABLE IF EXISTS[launcher]");
} else {
return;
}
onCreate(db);
}
}
//保存圖片到數據庫
public void savePhoto(Drawable appIcon, Context mContext){
LayoutInflater mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.app_view, null);
ImageView iv = (ImageView) v.findViewById(R.id.appicon);
iv.setImageDrawable(appIcon);
String INSERT_SQL = "INSERT INTO launcher(photo) values(?)";
SQLiteDatabase db = mDBService.getWritableDatabase(); // 獲得數據庫
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
((BitmapDrawable) iv.getDrawable()).getBitmap().compress(
CompressFormat.PNG, 100, baos);//壓縮爲PNG格式,100表示跟原圖大小同樣
Object[] args = new Object[] {baos.toByteArray() };
db.execSQL(INSERT_SQL, args);
baos.close();
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//3.從數據庫中取圖片
public void getPhoto() {
String SELECT_SQL = "SELECT photo FROM launcher";
ImageView appIcon = (ImageView) v.findViewById(R.id.appicon);//v是我在類中定義的一個view對象,跟前面保存圖片同樣
byte[] photo = null;
mDBService = new DBService(getContext());
SQLiteDatabase db = mDBService.getReadableDatabase();
Cursor mCursor = db.rawQuery(SELECT_SQL, null);
if (mCursor != null) {
if (mCursor.moveToFirst()) {//just need to query one time
photo = mCursor.getBlob(mCursor.getColumnIndex("photo"));//取出圖片
}
}
if (mCursor != null) {
mCursor.close();
}
db.close();
ByteArrayInputStream bais = null;
if (photo != null) {
bais = new ByteArrayInputStream(photo);
appIcon.setImageDrawable(Drawable.createFromStream(bais, "photo"));//把圖片設置到ImageView對象中
}
//appIcon顯示的就是以前保存到數據庫中的圖片
}