android创建数据库(SQLite)保存图片示例
//1.创建数据库
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);
}
}
//保存图片到数据库
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显示的就是之前保存到数据库中的图片
}
上一篇: 您知道血糖高吃什么好吗
下一篇: 详细介绍Android中回调函数机制