android creates the database of SQLite to save the image example

  • 2020-05-19 05:54:48
  • OfStack


//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(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)"; // 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 the image to the 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, 100, baos);// Compressed into PNG format ,100 Represents the size of the original image 1 sample 
Object[] args = new Object[] {baos.toByteArray() };
db.execSQL(INSERT_SQL, args);
baos.close();
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//3. Take a picture from the database 
public void getPhoto() {
String SELECT_SQL = "SELECT photo FROM launcher";
ImageView appIcon = (ImageView) v.findViewById(R.id.appicon);//v I defined it in the class 1 a view Object, save the image with the previous 1 sample 
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"));// Take out the pictures 
}
}
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 image to ImageView In the object 
} 
    //appIcon The image that was saved to the database is displayed 
}


Related articles: