欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android创建数据库(SQLite)保存图片示例

程序员文章站 2022-06-29 09:42:29
复制代码 代码如下://1.创建数据库public class dbservice extends sqliteopenhelper { private final st...

复制代码 代码如下:

//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显示的就是之前保存到数据库中的图片
}