TrinityTuts

Capturing images from camera and setting into listview in android

Last updated on January 8th, 2020 at 10:14 pm

In this post i explain you how to save camera capture image in ListView android. This code is very useful is you dynamically add image in ListView.

Step 1. Create new project in your android studio.

Step 2. Add read write permission in your manifest file.

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Step 3. I also add config change in activity to solve camera orientation issue mainly occur in Samsung phones (Screen orientate after save image and activity reload).

<activity
            android:name=".MainActivity"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize"
            android:label="@string/app_name"
            android:screenOrientation="locked"
            android:windowSoftInputMode="stateHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Step 4. Now open your activity_main.xml and add listview in it.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/captureList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></ListView>

</RelativeLayout>

Step 5. Now create a new layout file you need to inflate that view in your listview where we set clicked image.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:weightSum="3"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/imgPrv"
        android:layout_width="75dp"
        android:layout_weight=".4"
        android:layout_height="75dp" />

    <LinearLayout
        android:layout_marginLeft="@dimen/activity_horizontal_margin"
        android:paddingLeft="0dp"
        android:layout_weight="1.9"
        android:layout_width="wrap_content"
        android:orientation="vertical"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/parcelName"
            android:paddingTop="15px"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="label"
            android:textSize="18dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/imageFor"
            android:layout_marginTop="4dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="parcel#Id" />
    </LinearLayout>

    <ImageButton
        android:id="@+id/capture"
        android:layout_margin="@dimen/activity_horizontal_margin"
        android:layout_gravity="center_vertical"
        android:background="@null"
        android:src="@drawable/ic_action_photo_camera5"
        android:focusable="false"
        android:layout_weight=".5"
        android:layout_width="32dp"
        android:layout_height="32dp" />

    <ImageButton
        android:visibility="gone"
        android:id="@+id/cancel"
        android:layout_margin="@dimen/activity_horizontal_margin"
        android:focusable="false"
        android:layout_gravity="center_vertical"
        android:background="@null"
        android:src="@drawable/ic_action_cancel29"
        android:layout_weight=".5"
        android:layout_width="32dp"
        android:layout_height="32dp" />


</LinearLayout>

Step 6. Now create GetSet class.

package com.imagelistview.getset;

import android.graphics.Bitmap;

/**
 * Created by Aneh 3 on 25-06-2015.
 */
public class GetSet {
    String label;
    Bitmap image;

    public GetSet() {

    }


    String imageSrc;

    public void setUid(String uid) {
        this.uid = uid;
    }

    private String uid;

    public int getListItemPosition() {
        return listItemPosition;
    }

    public void setListItemPosition(int listItemPosition) {
        this.listItemPosition = listItemPosition;
    }

    int listItemPosition;

    public boolean isHaveImage() {
        return haveImage;
    }

    public void setHaveImage(boolean haveImage) {
        this.haveImage = haveImage;
    }

    boolean haveImage;

    public String getSubtext() {
        return subtext;
    }

    public void setSubtext(String subtext) {
        this.subtext = subtext;
    }

    String subtext;
    boolean status;

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public Bitmap getImage() {
        return image;
    }

    public void setImage(Bitmap image) {
        this.image = image;
    }

    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

}

Step 7. Now create a custom adapter for ListView android.

package com.imagelistview.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.imagelistview.MainActivity;
import com.imagelistview.R;
import com.imagelistview.getset.GetSet;

import java.util.List;

/**
 * Created by Aneh 3 on 25-06-2015.
 */
public class CustomImageAdapter extends BaseAdapter {

    List<GetSet> _data;
    Context _c;
    ViewHolder v;

    public CustomImageAdapter(List<GetSet> getData, Context context) {
        _data = getData;
        _c = context;
    }

    @Override
    public int getCount() {
        return _data.size();
    }

    @Override
    public Object getItem(int position) {
        return _data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;

        if (view == null) {
            LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = li.inflate(R.layout.parcel_images, null);
        } else {
            view = convertView;
        }

        v = new ViewHolder();
        v.clickImage = (ImageButton) view.findViewById(R.id.capture);
        v.removeImage = (ImageButton) view.findViewById(R.id.cancel);
        v.parcelName = (TextView) view.findViewById(R.id.parcelName);
        v.label = (TextView) view.findViewById(R.id.imageFor);
        v.imageView = (ImageView) view.findViewById(R.id.imgPrv);

        // Set data in listView
        final GetSet dataSet = (GetSet) _data.get(position);

        dataSet.setListItemPosition(position);

        if (!dataSet.isHaveImage()) {
            Bitmap icon = BitmapFactory.decodeResource(_c.getResources(), R.mipmap.ic_launcher);
            v.imageView.setImageBitmap(icon);
        } else {
            v.imageView.setImageBitmap(dataSet.getImage());
        }
        v.parcelName.setText(dataSet.getLabel());
        v.label.setText(dataSet.getSubtext());
        if (dataSet.isStatus()) {
            v.clickImage.setVisibility(View.VISIBLE);
            v.removeImage.setVisibility(View.GONE);
        } else {
            v.removeImage.setVisibility(View.VISIBLE);
            v.clickImage.setVisibility(View.GONE);
        }

        v.clickImage.setFocusable(false);
        v.removeImage.setFocusable(false);


        v.clickImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Call parent method of activity to click image
                ((MainActivity) _c).captureImage(dataSet.getListItemPosition(), dataSet.getLabel() + "" + dataSet.getSubtext());
            }
        });

        v.removeImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataSet.setStatus(true);
                dataSet.setHaveImage(false);
                notifyDataSetChanged();
            }
        });


        return view;
    }

    /**
     * @param position Get position of of object
     * @param imageSrc set image in imageView
     */
    public void setImageInItem(int position, Bitmap imageSrc, String imagePath) {
        GetSet dataSet = (GetSet) _data.get(position);
        dataSet.setImage(imageSrc);
        dataSet.setStatus(false);
        dataSet.setHaveImage(true);
        notifyDataSetChanged();
    }

    static class ViewHolder {
        ImageView imageView;
        TextView label, parcelName;
        ImageButton clickImage, removeImage;
    }

}

Step 8. Now open your MainActivity.java and paste this code.

package com.imagelistview;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.widget.ListView;

import com.imagelistview.adapter.CustomImageAdapter;
import com.imagelistview.getset.GetSet;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;


public class MainActivity extends ActionBarActivity {

    CustomImageAdapter customImageAdapter;
    ArrayList<GetSet> getSets;
    ListView listView;

    // Temp save listItem position
    int position;

    int imageCount;
    String imageTempName;
    String[] imageFor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.captureList);
        getSets = new ArrayList<GetSet>();
        imageFor = getResources().getStringArray(R.array.imageFor);
        for (int i = 0; i < 3; i++) {

            GetSet inflate = new GetSet();
            // Global Values
            inflate.setUid(String.valueOf(i));

            inflate.setLabel("Image");
            inflate.setHaveImage(false);
            inflate.setSubtext(imageFor[i]);
            inflate.setStatus(true);

            getSets.add(inflate);
        }
        customImageAdapter = new CustomImageAdapter(getSets, MainActivity.this);
        listView.setAdapter(customImageAdapter);
    }


    /**
     * Capture Image and save into database
     */

    public void captureImage(int pos, String imageName) {
        position = pos;
        imageTempName = imageName;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 100);
    }

    /**
     * Set capture image to database and set to image preview
     *
     * @param data
     */
    private void onCaptureImageResult(Intent data) {

        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");

        // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
        Uri tempUri = getImageUri(getApplicationContext(), imageBitmap, imageTempName);
        String picturePath = getRealPathFromURI(tempUri);
        customImageAdapter.setImageInItem(position, imageBitmap, picturePath);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_CANCELED) {
            if (requestCode == 100) {
                onCaptureImageResult(data);
            }
        }
    }

    public Uri getImageUri(Context inContext, Bitmap inImage, String imageName) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, imageName, null);
        return Uri.parse(path);
    }

    public String getRealPathFromURI(Uri uri) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(idx);
    }

    public Bitmap convertSrcToBitmap(String imageSrc) {
        Bitmap myBitmap = null;
        File imgFile = new File(imageSrc);
        if (imgFile.exists()) {
            myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
        }
        return myBitmap;
    }

}

Hope this help you 🙂