「Andorid」SQLiteデータベースを作成、画像を保存するコード

//DB作成
public class DBService extends SQLiteOpenHelper {

private final static int VERSION = 1;
private final static String DATABASE_NAME = “uniteqinfocher.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 [infocher]("
+ “[_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[infocher]");
} else {
return;
}
onCreate(db);
}
}

//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 infocher(photo) values(?)";
SQLiteDatabase db = mDBService.getWritableDatabase(); // DB取得
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
((BitmapDrawable) iv.getDrawable()).getBitmap().compress(
CompressFormat.PNG, 100, baos);//圧縮拡張
Object[] args = new Object[] {baos.toByteArray() };
db.execSQL(INSERT_SQL, args);
baos.close();
db.close();
} catch (Exception e) {
e.printStackTrace();
}

}

//DBから画像取得
public void getPhoto() {
String SELECT_SQL = “SELECT photo FROM infocher";
ImageView appIcon = (ImageView) v.findViewById(R.id.appicon);
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オブジェクトに画像を設定
}

}

Android

Posted by arkgame