6

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); } } } 
2
  • Bitmaps shouldn't be saved directly in database, but on sd-card. In database you can save just reference to bitmap. Saving bitmap directly in database will have huge influence to performance. Commented Jul 9, 2015 at 22:43
  • i am extending the BaseAdapter for Listview in that what should be the code for onActivityResult() method? Commented Apr 12, 2017 at 13:35

3 Answers 3

7

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. enter image description here enter image description here

Sign up to request clarification or add additional context in comments.

Comments

3

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

5 Comments

@Xylian You can get thumbnail of the captured pic from Media. Check this SO answer
you shouldn't save bitmap in SQLite database.. Never.. Just reference to image should be stored in db..
@Ewoks Read the question buddy, I answered it, you said best practice
@Abhi "buddy" should not give bad advice if somebody ask better question just for sake of formality.. Quite opposite, if somebody has a problem and it is asking for help, but going in a wrong direction, you should at least mention that it is wrong direction and bad solution..That will help him and others who read this not to waste time.. Of course, if you know that is wrong..
@Ewoks i really appreciate you, if you write comment on below the question
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.