国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Android > 正文

android創(chuàng)建數(shù)據(jù)庫(SQLite)保存圖片示例

2020-04-11 11:57:21
字體:
供稿:網(wǎng)友

復制代碼 代碼如下:

//1.創(chuàng)建數(shù)據(jù)庫
public class DBService extends SQLiteOpenHelper {

private final static int VERSION = 1;
private final static String DATABASE_NAME = "uniteqlauncher.db";

public DBService(Context context) {
    this(context, DATABASE_NAME, null, VERSION);
}

public DBService(Context context, String name, CursorFactory factory,
        int version) {
    super(context, name, factory, version);
}

@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);
}
}
//保存圖片到數(shù)據(jù)庫
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(); // 得到數(shù)據(jù)庫
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.從數(shù)據(jù)庫中取圖片
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顯示的就是之前保存到數(shù)據(jù)庫中的圖片
}

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 辉县市| 富宁县| 彭泽县| 佛山市| 时尚| 威宁| 西乌珠穆沁旗| 盘山县| 仙游县| 台湾省| 玉田县| 滕州市| 宣威市| 奉新县| 广汉市| 兴仁县| 大理市| 东源县| 南溪县| 咸丰县| 河南省| 新余市| 额尔古纳市| 曲周县| 大田县| 鄂托克前旗| 双辽市| 扎兰屯市| 江陵县| 顺昌县| 大名县| 泌阳县| 湾仔区| 涟水县| 柘城县| 郴州市| 罗源县| 翁牛特旗| 台州市| 卢湾区| SHOW|