Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android How to save camera images in database and display another activity in list view?

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

        }       
    }
}
like image 507
NagarjunaReddy Avatar asked Mar 30 '12 10:03

NagarjunaReddy


People also ask

How do I add an image to list view?

Instead of String Array You have to use Integer array & Put your drawable images in it. fetch your images in your ImageView like this: imgview. setImageResource(arr[position]);

How do you get an image from a camera or a gallery and save it in Android?

Run the application on an Android phone. Selecting "Take photo" will open your camera. Finally, the image clicked will be displayed in the ImageView. Selecting "Choose from Gallery" will open your gallery (note that the image captured earlier has been added to the phone gallery).

What is camera API in Android?

This package is the primary API for controlling device cameras. It can be used to take pictures or videos when you are building a camera application. Camera. This class is the older deprecated API for controlling device cameras.


1 Answers

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

like image 72
sachin pangare Avatar answered Sep 29 '22 04:09

sachin pangare