@L_404_0@ 代码如下:
//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创建数据库(SQLite)保存图片示例全部内容,希望文章能够帮你解决android创建数据库(SQLite)保存图片示例所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)