当前位置: 动力学知识库 > 问答 > 编程问答 >

java - how to insert byte array in database?

问题描述:

I have problem about inserting byte[] of android database.

I have two class called DB.java and DBAdapter.java as below.

I get the following error. "Error insert image=[[email protected]"

Basically, i followed on some tut, but still can't work. Hope someone can help.

DB.java:

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);

}

}

DBAdapter.java

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);

}

}

网友答案:

I wiil suggest you to save your image file on sdcard and save its path in database.

分享给朋友:
您可能感兴趣的文章:
随机阅读: