[英]how to insert byte array in database?
我在插入android数据库的byte []时遇到问题。 我有两个名为DB.java和DBAdapter.java的类,如下所示。 我收到以下错误。 “错误插入图像= [B @ 43d1b7b8””基本上,我在进行某些操作时仍然无法使用。 希望有人能帮忙。
public class DB extends Activity{
private final String imageInSD = "/sdcard/e5.jpg";
Bitmap bitmap;
byte[] buf =null;
/** Called when the activity is first created. */
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DBAdapter db = new DBAdapter(this);
BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();
BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;
bitmap = BitmapFactory.decodeFile(imageInSD, BitmapFactoryOptionsbfo);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos );
buf = bos.toByteArray();
db.open();
long id;
id = db.insertTitle(buf);
db.close();
System.out.println("ID:"+id);
}
}
public class DBAdapter
{
public static final String KEY_IMAGE = "image";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "books";
private static final String DATABASE_TABLE = "photo";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table photo (image blob not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS titles");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
public long insertTitle(byte[] buf)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_IMAGE, buf);
return db.insert(DATABASE_TABLE, null, initialValues);
}
}
我建议您将图像文件保存在sdcard上,并将其路径保存在数据库中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.