Copy Code code as follows:
1. Create a database
public class Dbservice extends Sqliteopenhelper {
Private final static int VERSION = 1;
Private final static String database_name = "UNITEQLAUNCHER.DB";
Public Dbservice {
This is (context, database_name, NULL, VERSION);
}
Public Dbservice (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)"; Save As binary format
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);
}
}
Save pictures to Database
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 (); Get the database
try {
Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
((bitmapdrawable) iv.getdrawable ()). Getbitmap (). Compress (
Compressformat.png, BAOs);/compressed to PNG format, 100 indicates the same size as the original
object[] args = new object[] {Baos.tobytearray ()};
Db.execsql (Insert_sql, args);
Baos.close ();
Db.close ();
catch (Exception e) {
E.printstacktrace ();
}
}
3. Take pictures from the database
public void Getphoto () {
String select_sql = "Select photo from Launcher";
ImageView AppIcon = (imageview) V.findviewbyid (R.id.appicon);//v is a view object that I defined in the class, just like the previous save picture
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"))//Remove picture
}
}
if (mcursor!= null) {
Mcursor.close ();
}
Db.close ();
Bytearrayinputstream Bais = null;
if (photo!= null) {
Bais = new Bytearrayinputstream (photo);
Appicon.setimagedrawable (Drawable.createfromstream (Bais, "photo"))//Set the picture to the ImageView object
}
AppIcon shows the pictures that were saved to the database
}