How to retrieve random pic of gallery from android SQLite database and display it in another Activity with name and price? When I click on "profile" button my app crashes but data is added successfully.
My code is:
MainActivity class:
public class MainActivity extends AppCompatActivity {
EditText edtName, edtPrice;
Button btnChoose, btnAdd, btnList;
ImageView imageView;
Uri imageuri;
final int REQUEST_CODE_GALLERY = 999;
private static final int pick_image = 100;
public static SQLiteHelper sqLiteHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtName = (EditText) findViewById(R.id.edtName);
edtPrice = (EditText) findViewById(R.id.edtPrice);
btnChoose = (Button) findViewById(R.id.btnChoose);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnList = (Button) findViewById(R.id.btnList);
imageView = (ImageView) findViewById(R.id.imageView);
sqLiteHelper = new SQLiteHelper(this, "FoodDB.sqlite", null, 1);
sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS FOOD(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, price VARCHAR, image BLOB)");
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery,pick_image);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
sqLiteHelper.insertData(
edtName.getText().toString().trim(),
edtPrice.getText().toString().trim(),
imageViewToByte(imageView)
);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
// edtName.setText("");
//edtPrice.setText("");
// imageView.setImageResource(R.mipmap.ic_launcher);
String s = "iqra"; //why we take string whrn we take only next button,is it necessary to take the string?
Intent i = new Intent(MainActivity.this, foodprofile.class);
Bundle bun = new Bundle();
bun.putString("name", s);
i.putExtras(bun);
startActivity(i);
}
catch (Exception e){
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == pick_image){
imageuri = data.getData();
imageView.setImageURI(imageuri);
}
}
public static byte[] imageViewToByte(ImageView image) {
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == REQUEST_CODE_GALLERY){
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE_GALLERY);
}
else {
Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
SQLitehelper class:
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public void queryData(String sql){
SQLiteDatabase database = getWritableDatabase();
database.execSQL(sql);
}
public void insertData(String name, String price, byte[] image){
SQLiteDatabase database = getWritableDatabase();
String sql = "INSERT INTO FOOD VALUES (NULL, ?, ?, ?)";
SQLiteStatement statement = database.compileStatement(sql);
statement.clearBindings();
statement.bindString(1, name);
statement.bindString(2, price);
statement.bindBlob(3, image);
statement.executeInsert();
}
public void updateData(String name, String price, byte[] image, int id) {
SQLiteDatabase database = getWritableDatabase();
String sql = "UPDATE FOOD SET name = ?, price = ?, image = ? WHERE id = ?";
SQLiteStatement statement = database.compileStatement(sql);
statement.bindString(1, name);
statement.bindString(2, price);
statement.bindBlob(3, image);
statement.bindDouble(4, (double)id);
statement.execute();
database.close();
}
public void deleteData(int id) {
SQLiteDatabase database = getWritableDatabase();
String sql = "DELETE FROM FOOD WHERE id = ?";
SQLiteStatement statement = database.compileStatement(sql);
statement.clearBindings();
statement.bindDouble(1, (double)id);
statement.execute();
database.close();
}
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("Select * from food ",null);
return res;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
foodprofile
public class foodprofile extends AppCompatActivity {
SQLiteHelper sqLiteHelper;
Button profile;
TextView txtresult1,txtresult2,txtresult6;
ImageView imgvresult;
Uri imageuri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foodprofile);
txtresult1 = (TextView) findViewById(R.id.name);
txtresult2 = (TextView) findViewById(R.id.price);
imgvresult = (ImageView) findViewById(R.id.image) ;
profile = (Button) findViewById(R.id.btnprofile);
}
public void profile(View v) {
if(v.getId()==R.id.btnprofile) {
Cursor res = sqLiteHelper.getData();
StringBuffer stringbuffer = new StringBuffer();
Toast pass = Toast.makeText(foodprofile.this,"inserted successfully", Toast.LENGTH_SHORT);
pass.show();
txtresult1.setText(" " + res.getString(0) );
txtresult2.setText(" " + res.getString(1) );
imgvresult.setImageURI(imageuri);
// imgvresult.setImageResource(res.getString(2),R.mipmap.ic_launcher);
//imgvresult.setImageResource(res.getBlob(0x2));
txtresult6.setText("-------------------------" + "\n");
//txtresult.setText(stringbuffer.toString());
Toast pass1= Toast.makeText(foodprofile.this, "retrieve successfully", Toast.LENGTH_SHORT);
pass1.show();
}
}
}
foodprofile.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff" >
<Button
android:id="#+id/btnprofile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="profile"
android:background="#color/colorPrimaryDark"
android:onClick="profile"/>
<ImageView
android:id="#+id/image"
android:layout_marginTop="55dp"
android:layout_width="match_parent"
android:layout_height="200dp" />
<TextView
android:id="#+id/name"
android:textColor="#000"
android:textStyle="bold"
android:textSize="30dp"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_marginTop="300dp"/>
<TextView
android:id="#+id/price"
android:textColor="#000"
android:textStyle="bold"
android:textSize="30dp"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_marginTop="350dp"/>
</RelativeLayout>
</ScrollView>
You need to :-
a) get a byte array via the getBlob() and then
b) convert the byte array to a Bitmap and then
c) set the ImageView using the Bitmap
Something along the lines of :-
public void profile(View v) {
if(v.getId()==R.id.btnprofile) {
Cursor res = sqLiteHelper.getData();
StringBuffer stringbuffer = new StringBuffer();
Toast pass = Toast.makeText(foodprofile.this,"inserted successfully", Toast.LENGTH_SHORT);
pass.show();
txtresult1.setText(" " + res.getString(0) );
txtresult2.setText(" " + res.getString(1) );
// get the Blob
byte[] my_bytearray = res.getBlob(2);
// convert byte array into a bitmap
Bitmap bmp = BitmapFactory.decodeByteArray(my_bytearray, 0, my_bytearray.length);
// apply the image to the image view
imgvresult.setImageBitmap(Bitmap.createScaledBitmap(bmp, image.getWidth(),
image.getHeight(), false)));
Toast pass1= Toast.makeText(foodprofile.this, "retrieve successfully", Toast.LENGTH_SHORT);
pass1.show();
}
}
Notes
Storing images can be problematic and inefficient. If the images are greater than about 100k it is advisable to store the images as files and to then store the path to the image in the database.
The above codes is in-principle it has not been tested and may therefore have typing errors.
Related
I'm new to android and I'm coding an app, and I want to get an image from my database and send it to the gallery I know how to do the opposite but this I have no idea what to do or how to start.
Here's the code I wrote:
public class ImageStorageActivity extends AppCompatActivity {
// DATABASE
public static DatabaseManager databaseManager;
final int REQUEST_CODE_GALLERY = 999;
ImageView imageView;
// grid view
GridView gridView;
ArrayList<Photo> list;
Photoadapter adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_storage);
imageView = findViewById(R.id.imageView);
CreateDatabase(); // create the database
gridView();
}
public void CreateDatabase() {
databaseManager = new DatabaseManager(this, "Image.db", null, 1);
databaseManager.queryData("CREATE TABLE IF NOT EXISTS Image(Id INTEGER PRIMARY KEY AUTOINCREMENT, image BLOB)");
Log.d("DATABASE", "Database was created");
}
private void update() {
// get all data from sqlite
Cursor cursor = ImageStorageActivity.databaseManager.getData("SELECT * FROM Image");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
byte[] image = cursor.getBlob(1);
list.add(new Photo(id, image));
}
adapter.notifyDataSetChanged();
}
public void gridView(){
gridView = findViewById(R.id.gridView);
list = new ArrayList<>();
adapter = new Photoadapter(this, R.layout.photo_list, list);
gridView.setAdapter(adapter);
gridView.setBackgroundColor(Color.BLACK);
gridView.setPadding(5,5,5,5);
Log.d("gridView", "gridView is working");
// get all data from sqlite
final Cursor cursor = ImageStorageActivity.databaseManager.getData("SELECT * FROM Image");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
byte[] image = cursor.getBlob(1);
list.add(new Photo( id,image));
}
adapter.notifyDataSetChanged();
Log.d("data", "get all data from sqlite");
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
CharSequence[] items = {"Delete"};
AlertDialog.Builder dialog = new AlertDialog.Builder(ImageStorageActivity.this);
dialog.setTitle("Choose an action");
dialog.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
// delete
Cursor c = ImageStorageActivity.databaseManager.getData("SELECT id FROM Image");
ArrayList<Integer> arrID = new ArrayList<>();
while (c.moveToNext()) {
arrID.add(c.getInt(0));
}
showDialogDelete(arrID.get(position));
}
}
});
dialog.show();
return true;
}
});
}
private void showDialogDelete(final int idImage) {
final AlertDialog.Builder dialogDelete = new AlertDialog.Builder(ImageStorageActivity.this);
dialogDelete.setTitle("Warning!!");
dialogDelete.setMessage("Are you sure you want to this delete?");
dialogDelete.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
ImageStorageActivity.databaseManager.fetch(idImage);
ImageStorageActivity.databaseManager.deleteData(idImage);
Toast.makeText(getApplicationContext(), "Delete successfully!!!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e("error", e.getMessage());
}
update();
}
});
dialogDelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialogDelete.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_image, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
RelativeLayout Main_view = findViewById(R.id.main_view);
switch (item.getItemId()) {
case R.id.add: {
try{
ActivityCompat.requestPermissions(
ImageStorageActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_GALLERY);
}
catch (Exception e){
e.printStackTrace();
}
break;
}
default:
return super.onOptionsItemSelected(item);
}
return false;
}
public static byte[] imageViewToByte(ImageView image) {
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == REQUEST_CODE_GALLERY){
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE_GALLERY);
}
else {
Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
databaseManager.insertData(imageViewToByte(imageView));
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
imageView.setImageResource(R.mipmap.ic_launcher);
getContentResolver().delete(uri,null,null);
update();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Here's my database
public class DatabaseManager extends SQLiteOpenHelper{
public DatabaseManager(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public void queryData(String sql){
SQLiteDatabase database = getWritableDatabase();
database.execSQL(sql);
}
public void insertData( byte[] image ) {
SQLiteDatabase database = getWritableDatabase();
String sql = "INSERT INTO IMAGE VALUES (NULL,? ,?)";
SQLiteStatement statement = database.compileStatement(sql);
statement.clearBindings();
statement.bindBlob(1,image);
statement.executeInsert();
}
public void updateData(byte[] image , int id ){
SQLiteDatabase database = getWritableDatabase();
String sql ="UPDATE IMAGE SET image = ? WHERE id = ? ";
SQLiteStatement statement = database.compileStatement(sql);
statement.bindBlob(1,image);
statement.bindDouble(2,(double)id);
statement.execute();
database.close();
}
public void deleteData(int id) {
SQLiteDatabase database = getWritableDatabase();
String sql = "DELETE FROM IMAGE WHERE id = ?";
SQLiteStatement statement = database.compileStatement(sql);
statement.clearBindings();
statement.bindDouble(1, (double)id);
statement.execute();
database.close();
}
public Cursor getData(String sql){
SQLiteDatabase database = getWritableDatabase();
return database.rawQuery(sql,null);
}
public Cursor fetch(int id){
SQLiteDatabase database = getWritableDatabase();
String sql = "SELECT FROM IMAGE WHERE id = ? ";
Cursor c = database.rawQuery(sql,null);
return c ;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
You can try below code to convert from blob to byte array and then use that byte array to create bitmap which you can show in imageview.
byte[] byteArray = DBcursor.getBlob(columnIndex);
Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0 ,byteArray.length);
This post is a continuance of my previous question about saving an image to SQLite. I am getting cannot convert Blob to String error at FoodList activity startup with crash. I am using SQLite Helper and an adapter. My Main Activity code is as follows:
public static SQLiteHelper sqLiteHelper;
final int REQUEST_CODE_GALLERY = 999;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
sqLiteHelper = new SQLiteHelper(this, "FoodDB.sqlite", null, 1);
sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS FOOD (name TEXT, price TEXT, image BLOB)");
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(
MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_GALLERY
);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
sqLiteHelper.insertData(
edtName.getText().toString().trim(),
edtPrice.getText().toString().trim(),
imageViewToByte(imageView)
);
Toast.makeText(getApplicationContext(), "Entry Added", Toast.LENGTH_LONG).show();
edtName.setText("");
edtPrice.setText("");
imageView.setImageResource(R.mipmap.ic_launcher);
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
btnList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, FoodList.class);
startActivity(intent);
}
});
}
private byte[] imageViewToByte(ImageView image) {
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == REQUEST_CODE_GALLERY) {
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE_GALLERY);
}
else {
Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_LONG).show();
}
//return;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void init() {
edtName = findViewById(R.id.edtName);
edtPrice = findViewById(R.id.edtPrice);
btnChoose = findViewById(R.id.btnChoose);
btnAdd = findViewById(R.id.btnAdd);
btnList = findViewById(R.id.btnList);
imageView = findViewById(R.id.imageView);
}
}
Then my SQLite Helper class is as follows:
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public void queryData(String sql) {
SQLiteDatabase database = getWritableDatabase();
database.execSQL(sql);
}
public void insertData(String name, String price, byte[] image) {
SQLiteDatabase database = getWritableDatabase();
String sql = "INSERT INTO FOOD VALUES (?, ?, ?)";
SQLiteStatement statement = database.compileStatement(sql);
statement.clearBindings();
statement.bindString(1, name);
statement.bindString(2, price);
statement.bindBlob(3, image);
statement.executeInsert();
}
public Cursor getData(String sql) {
SQLiteDatabase database = getReadableDatabase();
return database.rawQuery(sql, null);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
My food list adapter code is this:
public class FoodListAdapter extends BaseAdapter {
private Context context;
private int layout;
private ArrayList<Food> foodsList;
public FoodListAdapter(Context context, int layout, ArrayList<Food> foodsList) {
this.context = context;
this.layout = layout;
this.foodsList = foodsList;
}
#Override
public int getCount() {
return foodsList.size();
}
#Override
public Object getItem(int position) {
return foodsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
ImageView imageView;
TextView txtName, txtPrice;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View row = view;
ViewHolder holder = new ViewHolder();
if(row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
holder.txtName = (TextView) row.findViewById(R.id.txtName);
holder.txtPrice = (TextView) row.findViewById(R.id.txtPrice);
holder.imageView = (ImageView) row.findViewById(R.id.imgFood);
row.setTag(holder);
}
else {
holder = (ViewHolder) row.getTag();
}
Food food = foodsList.get(position);
holder.txtName.setText(food.getName());
holder.txtPrice.setText(food.getPrice());
byte[] foodImage = food.getImage();
Bitmap bitmap = BitmapFactory.decodeByteArray(foodImage, 0, foodImage.length);
holder.imageView.setImageBitmap(bitmap);
return row;
}
}
I also have a class called Food that code is also as follows:
public class Food {
private String name;
private String price;
private byte[] image;
public Food(String name, String price, byte[] image) {
this.name = name;
this.price = price;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
}
And last but not least, here is the code for the activity that crashes upon initialization FoodList:
public class FoodList extends AppCompatActivity {
GridView gridView;
ArrayList<Food> list;
FoodListAdapter adapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.food_list_activity);
gridView = findViewById(R.id.gridView);
list = new ArrayList<>();
adapter = new FoodListAdapter(this, R.layout.food_items, list);
gridView.setAdapter(adapter);
Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM FOOD");
list.clear();
while (cursor.moveToNext()) {
String name = cursor.getString(1);
String price = cursor.getString(2);
byte[] image = cursor.getBlob(3);
list.add(new Food(name, price, image));
}
adapter.notifyDataSetChanged();
}
}
I have no clue what is causing this error. hopefully someone can shed some light on my issue...
Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM FOOD");
Will return a Cursor that has 3 columns, name, price and image as such you will have columns with offsets 0 (name), 1 (price) and 2 (image).
Therefore, getString(2) is trying to get the image column which is a BLOB, but as a String, hence the error trying to convert the BLOB to a String.
If it hand't of failed then you would have got another failure with an index error with getBlob(3) as there is no column with an offset of 3.
It is best to not use offsets normally, but rather use the getColumnIndex(column_name) method which returns the column offset(index) according to the given column name.
As such, you could use the following, which would fix the issue :-
String name = cursor.getString(getColumnIndex("name"));
String price = cursor.getString(getColumnIndex("price"));
byte[] image = cursor.getBlob(getColumnIndex("image"));
I am trying to create an app where the user can select their profile picture from gallery. I decided to save their profile picture to my Database as Blob. I am able to save the image and even retrieve it. The thing is, I am not able to replace it, or whenever I click it again, the application stops working and when I check my table where I store the image it says "Too much data returned..."
public class AccountFragment extends Fragment implements OnClickListener {
private LoginDataBaseAdapter loginDataBaseAdapter;
Bitmap image;
Bitmap bitmap;
String picture_location;
TextView textTargetUri;
ImageView targetImage;
public static final String MyPREFERENCES = "MyPrefs" ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// create a instance of SQLite Database
loginDataBaseAdapter = new LoginDataBaseAdapter(getActivity());
loginDataBaseAdapter=loginDataBaseAdapter.open();
//intialize variables
textTargetUri = (TextView) rootView.findViewById(R.id.targeturi);
targetImage=(ImageView) rootView.findViewById(R.id.profpic);
targetImage.setOnClickListener(new ImageView.OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}});
showpic();
return rootView;
}
#Override
public void onActivityResult( int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
Uri targetUri = data.getData();
picture_location = targetUri.toString();
textTargetUri.setText(targetUri.toString());
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(targetUri));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
loginDataBaseAdapter.insertPhoto(byteArray);
showpic();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
public void showpic() {
Cursor cursor = loginDataBaseAdapter.fetchProfileImageFromDatabase();
if(cursor != null)
{
cursor.moveToFirst();
byte[] data = cursor.getBlob(cursor.getColumnIndex("Path"));
ByteArrayInputStream imageStream = new ByteArrayInputStream(data);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
targetImage.setImageBitmap(theImage);
}
cursor.close();
}
}
and my database handler:
//IMAGE
public static final String Profpic_TABLE = "ProfilePic";
public static final String KEY_ProfpicID = "_id";
public static final String KEY_ProfPic = "Path";
//ProfilePic-Table
static final String DATABASE_ProfPic =
"create table " + Profpic_TABLE + " ("
+ KEY_ProfpicID + " integer primary key DEFAULT 1, "
+ KEY_ProfPic + " BLOB);";
public long insertPhoto(byte[] EImage) {
db.execSQL("delete from "+ Profpic_TABLE);
try {
System.out.println("Function call : ");
ContentValues values = new ContentValues();
values.put(KEY_ProfPic, EImage);
return db.insert(Profpic_TABLE, null, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public Cursor fetchProfileImageFromDatabase()
{
return db.rawQuery("SELECT Path FROM ProfilePic where _id = 1 " , null);
}
}
I was able to finally solve it. Turns out I have to do it this way instead:
public void showpic() {
LoginDataBaseAdapter db = loginDataBaseAdapter.open();
boolean emptytab = false;
boolean empty = db.checkPic(null, emptytab);
//Cursor cursor = loginDataBaseAdapter.fetchProfileImageFromDatabase();
if(empty==false)
{
Cursor cursor = loginDataBaseAdapter.fetchProfileImageFromDatabase();
cursor.moveToFirst();
byte[] data = cursor.getBlob(cursor.getColumnIndex("Path"));
ByteArrayInputStream imageStream = new ByteArrayInputStream(data);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
targetImage.setImageBitmap(theImage);
cursor.close();
}
}
and on my db adapter I added this:
public boolean checkPic(String count, Object object) {
boolean empty = false;
Cursor cursor = db.rawQuery("SELECT count(*) FROM ProfilePic", null);
if(cursor != null)
{
cursor.moveToFirst();
if(cursor.getInt(0)== 0)
{
empty = true; //rows not null;
}
else
{
empty = false; // rows null;
}
}
return empty;
}
I created an app for scanning barcodes and QR code using the ZXing library. I also implemented a database that stores the scanned products. I need to implement a listview to display the stored products. any ideas?
here are classes:
BarCodeActivity
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spot_pay);
Button addButton = (Button) findViewById (R.id.addMenuButton);
addButton.setOnClickListener (new OnClickListener(){
public void onClick (View v){
startActivity(new Intent(CodiceBarreActivity.this, AggiungiCodiceActivity.class));
}
});
}
static final class ProductData {
String barcode;
String format;
String title;
BigDecimal price;
}
}
ProductDatabase:
private SQLiteDatabase db;
private static class ProductDatabaseHelper extends SQLiteOpenHelper {
public ProductDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
StringBuilder sql = new StringBuilder();
sql.append("create table ").append(PRODUCT_TABLE)
.append("( ")
.append(" _id integer primary key,")
.append(" barcode text,")
.append(" format text,")
.append(" title text,")
.append(" price currency")
.append(") ");
db.execSQL(sql.toString());
Log.d(TAG, PRODUCT_TABLE + "table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + PRODUCT_TABLE);
Log.d(TAG, PRODUCT_TABLE + "table dropped");
onCreate(db);
}
}
public CodiciDatabase(Context context) {
ProductDatabaseHelper helper = new ProductDatabaseHelper(context);
db = helper.getWritableDatabase();
}
public boolean insert(ProductData product) {
ContentValues vals = new ContentValues();
vals.put("barcode", product.barcode);
vals.put("format", product.format);
vals.put("title", product.title);
vals.put("price", product.price.multiply(ONE_HUNDRED).longValue());
return db.insert(PRODUCT_TABLE, null, vals) != -1;
}
}
AddProduct
private static final int REQUEST_BARCODE = 0;
private static final ProductData mProductData = new ProductData();
private EditText mBarcodeEdit;
private EditText mFormatEdit;
private EditText mTitleEdit;
private EditText mPriceEdit;
private Button mScanButton;
private Button mAddButton;
private CodiciDatabase mProductDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
mBarcodeEdit = (EditText) findViewById(R.id.barcodeEdit);
mFormatEdit = (EditText) findViewById(R.id.codeFormatEdit);
mTitleEdit = (EditText) findViewById(R.id.titleEdit);
mPriceEdit = (EditText) findViewById(R.id.priceEdit);
mScanButton = (Button) findViewById(R.id.scanButton);
mScanButton.setOnClickListener(this);
mAddButton = (Button) findViewById(R.id.addButton);
mAddButton.setOnClickListener(this);
mProductDb = new CodiciDatabase(this); // not yet shown
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.scanButton:
Intent intent = new Intent ("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
startActivityForResult(intent, REQUEST_BARCODE);
break;
case R.id.addButton:
String barcode = mBarcodeEdit.getText().toString();
String format = mFormatEdit.getText().toString();
String title = mTitleEdit.getText().toString();
String price = mPriceEdit.getText().toString();
String errors = validateFields(barcode, format, title, price);
if (errors.length() > 0) {
showInfoDialog(this, "Please fix errors", errors);
} else {
mProductData.barcode = barcode;
mProductData.format = format;
mProductData.title = title;
mProductData.price = new BigDecimal(price);
mProductDb.insert(mProductData);
showInfoDialog(this, "Success", "Product saved successfully");
resetForm();
}
break;
}
}
}
private void resetForm() {
mBarcodeEdit.getText().clear();
mFormatEdit.getText().clear();
mTitleEdit.getText().clear();
mPriceEdit.getText().clear();
}
private void showInfoDialog(Context context, String title, String information) {
new AlertDialog.Builder (context)
.setMessage(information)
.setTitle(title)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent){
if (requestCode == REQUEST_BARCODE){
if (resultCode == RESULT_OK) {
String barcode = intent.getStringExtra("SCAN_RESULT");
mBarcodeEdit.setText(barcode);
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
mFormatEdit.setText(format);
} else if (resultCode == RESULT_CANCELED){
finish();
}
}
}
}
private static String validateFields(String barcode, String format,
String title, String price) {
StringBuilder errors = new StringBuilder();
if (barcode.matches("^\\s*$")) {
errors.append("Barcode required\n");
}
if (format.matches("^\\s*$")) {
errors.append("Format required\n");
}
if (title.matches("^\\s*$")) {
errors.append("Title required\n");
}
if (!price.matches("^-?\\d+(.\\d+)?$")) {
errors.append("Need numeric price\n");
}
return errors.toString();
}
}
Overview of what you need to do:
Run a query on your database that will return a Cursor to you. Once you've got that you'll have to make make a CursorAdapter and override its getView() method to inflate and populate the row Views. After that you can use the ListView.setAdapter() method passing in an instance of your adapter. It will handle updating the list on the screen for you whenever there is new data.
I suggest instead of trying to tackle this in your own project you take a break from that and go do this Notepad tutorial from the developer docs. It is very small and simple but once you are complete you will have some sample code to use when you are working on doing this for your barcode application.
i am using camera to take photos and want to store in database(SQLite). Stored photos have to be displayed in the another activity with list view like this list view images and this iam using this code take photo but how to store the photo in database and display in another activity any idea please help .....
thank you....
this is the code for taking photos
public class PhotoActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
public ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photoactivity);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button B = (Button) this.findViewById(R.id.camera);
B.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
Hey friends I got the solution of above problem.Here I post my full source code so that others can use this solution.
1.Create one acyivity i.e CameraPictureActivity.
public class CameraPictureActivity extends Activity {
Button addImage;
ArrayList<Contact> imageArry = new ArrayList<Contact>();
ContactImageAdapter imageAdapter;
private static final int CAMERA_REQUEST = 1;
ListView dataList;
byte[] imageName;
int imageId;
Bitmap theImage;
DataBaseHandler db;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dataList = (ListView) findViewById(R.id.list);
/**
* create DatabaseHandler object
*/
db = new DataBaseHandler(this);
/**
* Reading and getting all records from database
*/
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "ID:" + cn.getID() + " Name: " + cn.getName()
+ " ,Image: " + cn.getImage();
// Writing Contacts to log
Log.d("Result: ", log);
// add contacts data in arrayList
imageArry.add(cn);
}
/**
* Set Data base Item into listview
*/
imageAdapter = new ContactImageAdapter(this, R.layout.screen_list,
imageArry);
dataList.setAdapter(imageAdapter);
/**
* open dialog for choose camera
*/
final String[] option = new String[] {"Take from Camera"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, option);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Option");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.e("Selected Item", String.valueOf(which));
if (which == 0) {
callCamera();
}
}
});
final AlertDialog dialog = builder.create();
addImage = (Button) findViewById(R.id.btnAdd);
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});
}
/**
* On activity result
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap yourImage = extras.getParcelable("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Android", imageInByte));
Intent i = new Intent(CameraPictureActivity.this,
CameraPictureActivity.class);
startActivity(i);
finish();
}
break;
}
}
/**
* open camera method
*/
public void callCamera()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 250);
intent.putExtra("outputY", 200);
}
}
2.Create class DataBaseHandler.
public class DataBaseHandler extends SQLiteOpenHelper
{
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = " Camera_imagedb";
// Contacts table name
private static final String TABLE_CONTACTS = " Camera_contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_IMAGE = "image";
public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read) Operations
*/
public// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact._name); // Contact Name
values.put(KEY_IMAGE, contact._image); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_IMAGE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getBlob(1));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM contacts ORDER BY name";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setImage(cursor.getBlob(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// close inserting data from database
db.close();
// return contact list
return contactList;
}
}
3.create another class Contact
public class Contact
{
// private variables
int _id;
String _name;
byte[] _image;
// Empty constructor
public Contact() {
}
// constructor
public Contact(int keyId, String name, byte[] image) {
this._id = keyId;
this._name = name;
this._image = image;
}
public Contact(String name, byte[] image) {
this._name = name;
this._image = image;
}
public Contact(int keyId) {
this._id = keyId;
}
// getting ID
public int getID() {
return this._id;
}
// setting id
public void setID(int keyId) {
this._id = keyId;
}
// getting name
public String getName() {
return this._name;
}
// setting name
public void setName(String name) {
this._name = name;
}
// getting phone number
public byte[] getImage() {
return this._image;
}
// setting phone number
public void setImage(byte[] image) {
this._image = image;
}
}
4.create one adapter i.e ContactImageAdapter
public class ContactImageAdapter extends ArrayAdapter<Contact>{
Context context;
int layoutResourceId;
// BcardImage data[] = null;
ArrayList<Contact> data=new ArrayList<Contact>();
public ContactImageAdapter(Context context, int layoutResourceId, ArrayList<Contact> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ImageHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ImageHolder();
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
row.setTag(holder);
}
else
{
holder = (ImageHolder)row.getTag();
}
Contact picture = data.get(position);
holder.txtTitle.setText(picture._name);
//convert byte to bitmap take from contact class
byte[] outImage=picture._image;
ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
holder.imgIcon.setImageBitmap(theImage);
return row;
}
static class ImageHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
5.Finally create the xml files main and screen_list .
5.1 main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:orientation="vertical" >
<Button
android:id="#+id/btnAdd"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:text="Add Image" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.55"
android:cacheColorHint="#00000000" >
</ListView>
</LinearLayout>
5.2 screen_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:padding="10dp" >
<ImageView
android:id="#+id/imgIcon"
android:layout_width="200dp"
android:layout_height="200dp"
android:scaleType="fitXY"
android:gravity="center_vertical" />
<TextView
android:id="#+id/txtTitle"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textSize="14dp"
android:text="#string/hello"
android:textColor="#000000"
android:layout_marginLeft="7dp" />
</LinearLayout>
6.Output like this.
Create DataBase helper class like this..
On Capturing the image insert the image by converting into bytes:
Imagehelper help=new Imagehelper(this);
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
help.insert(byteArray);
}
To retrieve Form the Database:
Imagehelper help=new Imagehelper(this);
Cursor c= help.getAll();
int i=0;
if(c.getCount()>0)
{
Bitmap[] array=new Bitmap[c.getCount()];
c.moveToFirst();
while(c.isAfterLast()==false)
{
byte[] bytes=c.getBlob(c.getColumnIndex("imageblob"));
array[i]=BitmapFactory.decodeByteArray(bytes, 0, 0);
c.moveToNext();
i++;
}
Log.e("Bitmap length",""+array.length);
}
Pass this Bitmap array to ListView
I am not convinced to save the bitmap itself in a sqlite database.
But it is possible when using Blob. A blob needs a byte[].
You could get a byte array by saving the Bitmap (with compress) and reading the file again.
http://developer.android.com/reference/android/graphics/Bitmap.html
Bitmap b;
File f = new File (...);
FileOutputStream fs = new FileOutputStream (f);
b.compress(JPEG, 85, fs);
fs.close ();
// Reread the file f into a byte []
or
Bitmap b;
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
b.compress(JPEG, 85, baos);
baos.close ();
byte[] blob = baos.toByteArray ();
b.compress(JPEG, 85, baos)
Or you could serialize the Bitmap into ByteArrayOutputStream (using ObjectOutputStream)
Bitmap b;
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
ObjectOutputStream oos = new ObjectOutputStream (baos);
oos.write (b);
oos.close ();
baos.close ();
byte[] blob = baos.toByteArray ();
However, probably it make sense to save the Bitmap as files (JPG or PNG) because they may become larger in size. The database will only hold the path info about that image.