Adsense Ad

Tuesday 30 January 2018

Android: How to set and insert image in Image view and in db from camera or gallery

In this article we go through with android sample code in which we first get image from DB and set it into ImageView on activity create.
Then we click from camera or select image from gallery and set it into ImageView on activity result.
In last, we save image into sqlite DB table having blob column.

Sample Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.user.dailybook.ProfileActivity">

<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:id="@+id/img"
                android:src="@drawable/noimage"
                android:layout_gravity="center_horizontal"
                android:onClick="CatchImage"
                android:clickable="true"
                />
<Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Save"
                android:textSize="20sp"
                android:textColor="#fff"
                android:textStyle="bold"
                android:background="@color/colorPrimaryDark"
                android:id="@+id/btn_save"
                android:textAllCaps="false"
                android:layout_marginRight="5dp"
                android:layout_gravity="right"
                />

</LinearLayout>

</RelativeLayout>



//Database Handler Java Class
public class DatabaseHandler extends SQLiteOpenHelper {
    public static String Globalid="";
    SQLiteDatabase sqLiteDatabase=getWritableDatabase();
    private static final String dbname="mydatabase.db";
    private static final int dbver=1;
    public DatabaseHandler(Context context) {
        super(context, dbname, null, dbver);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    String CreateTableQry="Create Table if not exists UBAG(" +
            "id integer primary key autoincrement not null, " +
            "pic  blob  )";

            db.execSQL(CreateTableQry);
            Log.e("","UBAG Table Created...");
    }

    public long insert(ContentValues values,String TableName){
        return (long) sqLiteDatabase.insert(TableName,null,values);
    }
public Cursor getData(String query){
        Cursor cursor=null;
        try {
            cursor = sqLiteDatabase.rawQuery(query, null);
        }catch (Exception e){
            Log.e("GD","DB Helper Found Error " + query);
        }
        cursor.moveToFirst();
        return cursor;
    }
}


//Java Class for Activity

public class ProfileActivity extends AppCompatActivity {
    ImageView imgvu;
DatabaseHandler dbhandler;
Bitmap help1;
Uri file;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        dbhandler = new DatabaseHandler(this);
        imgvu = (ImageView) findViewById(R.id.img);
       save = (Button) findViewById(R.id.btn_save);
Cursor cursor=null;
//On activity creation you can set image into imageview from db
        String query="select * from ubag where id='"+id+"'";
        cursor=dbhandler.getData(query);
        if (cursor!=null) {
            if (cursor.getCount() > 0) {
                while (!cursor.isAfterLast()) {
          
                    try {
                        byte[] image = cursor.getBlob(cursor.getColumnIndex("pic"));
                        Bitmap bmp = BitmapFactory.decodeByteArray(image, 0, image.length);
                        imgvu.setImageBitmap(bmp);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    cursor.moveToNext();
                }
            }
        }
save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    ContentValues cvs= new ContentValues();
                    Bitmap bitmap = ((BitmapDrawable)imgvu.getDrawable()).getBitmap();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos);
                    byte [] img = baos.toByteArray();
                    cvs.put("pic",img);
                    long ins =0;
                    ins = dbhandler.insert(cvs,"UBAG","id='"+id+"'");
                    if(ins==0){
                        Toast.makeText(ProfileActivity.this,"Data Not Saved",Toast.LENGTH_LONG).show();
                    }else{
                        Toast.makeText(ProfileActivity.this,"Data Updated",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

public void CatchImage(View v){
// use one method at a time for image saving and comment other one
        camerOpenForPic();  // Method use to save image from camera click
       // getPicFromGallery(); // Method use to save image from gallery
    }

@TargetApi(Build.VERSION_CODES.M)
    private boolean checkPermission(){
        if (ContextCompat.checkSelfPermission(this
                , Manifest.permission.WRITE_EXTERNAL_STORAGE) + ContextCompat
                .checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            },33);
            return  false;
        }else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==33){
            if (grantResults.length>0){
                boolean camerpermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                boolean readexternalfile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean writeExternalfile = grantResults[2] == PackageManager.PERMISSION_GRANTED;
                if (camerpermission && readexternalfile && writeExternalfile){
                    camerOpenForPic();
                }else{
                    Toast.makeText(this,"Unable to collect pic",Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    private void camerOpenForPic() {
        if (checkPermission()){
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent,1);
        }
    }

    public void getPicFromGallery(){
        if (checkPermission()){
            Intent intent=new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.INTERNAL_CONTENT_URI);
            intent.setType("image/*");
            intent.putExtra("crop","true");
            intent.putExtra("scale",true);
            intent.putExtra("outputX",256);
            intent.putExtra("outputY",256);
            intent.putExtra("aspectX",1);
            intent.putExtra("aspectY",1);
            intent.putExtra("return-data",true);
            //startActivityForResult(Intent.createChooser(intent,"Select Picture"),113);
            startActivityForResult(intent,113);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1){
            if (resultCode== Activity.RESULT_OK){
                try {
                    Bitmap bitmap= (Bitmap) data.getExtras().get("data");
                    imgvu.setImageBitmap(bitmap);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }else if (requestCode==113){
            if (resultCode==Activity.RESULT_OK){
                try {
                    final Bundle extras = data.getExtras();
                    help1 = extras.getParcelable("data");
                    imgvu.setImageBitmap(help1);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

}

No comments: