Tuesday, June 7, 2016

Capture Image Store Image in Folder and image Path in Database (SQLite)

 Jai Saraswati Maa"
Hi .... Dear All ....  Today I am uploading a superb example of Image with SQLite Database
In this example you can capture image from Camera and store image in your specified folder and path in  database as well as you can retrieve path from database and  image from folder.
I am using Android Studio 1.5.1
Minimun SDK API 19
Target SDK API 23
Please Like us & put your valuable suggestions in comment box
Special Thanks Dilip Singh 
@@@@ please add read write permission in manifest file like
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

A. Output will be like this  
      

B. XML file activity_main.xml is as

<?xml version="1.0" encoding="utf-8"?>

<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:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context="com.example.student.imagepathsqlite.MainActivity">

    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Capture Image"

        android:id="@+id/btnSelect"

        android:onClick="clickImage"

        android:layout_alignTop="@+id/btnUpload"

        android:layout_alignParentStart="true"/>

    <ImageView        android:layout_width="wrap_content"

        android:layout_height="150dp"

        android:id="@+id/imageView"

        android:src="@mipmap/ic_launcher"

        android:layout_below="@+id/btnUpload"

        android:layout_centerHorizontal="true" />
    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Save Image"

        android:id="@+id/btnUpload"

        android:onClick="sand"

        android:layout_marginTop="0dp"

        android:layout_alignParentTop="true"

        android:layout_alignParentEnd="true" />
    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Show Image"

        android:id="@+id/button"

        android:onClick="show"

        android:layout_below="@+id/imageView"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="67dp" />
    <ImageView        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/imageView1"

        android:src="@mipmap/ic_launcher"

        android:layout_alignParentBottom="true"

        android:layout_alignStart="@+id/imageView"

        android:layout_marginTop="300dp" />

</RelativeLayout>

C. Java Files are 

1. MainActivity.java

package com.example.student.imagepathsqlite;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {
    ImageView imgv1,imgv2;
    Bitmap bm =null;
    int REQUEST_CHECK = 0;
    String imgs;
    String s;
    File imgpath;
    private Cursor c=null;
    private  MyDataBase mdb=null;
    private SQLiteDatabase db=null;
    private static final String DB_NAME = "ImgDb.db";
    public static final int DB_VERSION = 3;


    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imgv1 = (ImageView) findViewById(R.id.imageView);
        imgv2 = (ImageView) findViewById(R.id.imageView1);
        mdb=new MyDataBase(getApplicationContext(), DB_NAME,null,

                DB_VERSION);
    }
    public void clickImage(View view)
    {

        //fire intent

        Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File fp = getFile();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(fp));
        startActivityForResult(intent, REQUEST_CHECK);

    }

    private File getFile() {
        File folder = new File("sdcard/attendence");
        if (!folder.exists()) {
            folder.mkdir();
        }
        imgpath = new File(folder, File.separator 
                               Calendar.getInstance().getTime() + ".jpg");


        return imgpath;
    }

    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {


        try{
            s = imgpath.toString();
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        }
        catch (Exception e){
            e.printStackTrace();

        }
        imgv1.setImageDrawable(Drawable.createFromPath(s));


    }
    public void sand(View view)
    {
        db=mdb.getWritableDatabase();
        ContentValues cv =new ContentValues();
        cv.put("path" ,s);
        db.insert("tableimage", null, cv);
        Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
    }
    public void show (View view) {
     String col[] = {"path"};
     db = mdb.getReadableDatabase();
     c = db.query("tableimage", col, null, null, null, null, null);

        c.moveToLast();

         imgs = c.getString(c.getColumnIndex("path"));


     imgv2.setImageDrawable(Drawable.createFromPath(imgs));
 }
}

2.  for Handling Database MyDataBase.java is as 
package com.example.student.imagepathsqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDataBase extends SQLiteOpenHelper {

    public MyDataBase(Context context, String dbname, 
                       SQLiteDatabase.CursorFactory factory, int dbversion) {
        super(context, dbname, factory, dbversion);
    }

    @Override    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table tableimage (path varchar(255))");

    }

    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

Monday, June 6, 2016

Capture Image from Camera and Store/Retrieve to/from SQLite Database

 Jai Saraswati Maa"
Hi .... Dear All ....  Today I am uploading a superb example of Image with SQLite Database
In this example you can capture image from Camera and store in database as well as you can retrieve image from database,
I am using Android Studio 1.5.1
Minimun SDK API 19
Target SDK API 23
Please Like us & put your valuable suggestions in comment box
Special Thanks Dilip Singh 
@@@@ please add read write permission in manifest file like
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

A. Output will be like this 

B. XML file activity_main.xml is as

<?xml version="1.0" encoding="utf-8"?>

<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:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context="com.example.student.imagesqlite.MainActivity">


    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Click Image"

        android:id="@+id/btnSelect"

        android:onClick="clickImage"

        android:layout_alignTop="@+id/btnUpload"

        android:layout_alignParentStart="true"/>

    <ImageView

        android:layout_width="wrap_content"

        android:layout_height="150dp"

        android:id="@+id/imageView"

        android:src="@mipmap/ic_launcher"

        android:layout_below="@+id/btnUpload"

        android:layout_centerHorizontal="true" />
    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Image Upload "

        android:id="@+id/btnUpload"

        android:onClick="sand"

        android:layout_marginTop="0dp"

        android:layout_alignParentTop="true"

        android:layout_alignParentEnd="true" />
    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Show Image"

        android:id="@+id/button"

        android:onClick="show"

        android:layout_below="@+id/imageView"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="67dp" />
    <ImageView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/imageView1"

        android:src="@mipmap/ic_launcher"

        android:layout_alignParentBottom="true"

        android:layout_alignStart="@+id/imageView"

        android:layout_marginTop="300dp" />

</RelativeLayout>

C. Java Files are 

1. MainActivity.java is as 

package com.example.student.imagesqlite;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;

public class MainActivity extends AppCompatActivity {
    ImageView imgv1,imgv2;
    Bitmap bm = null;
    int REQUEST_CHECK = 0;
    byte img[];
    private MyDataBase mdb=null;
    private SQLiteDatabase db=null;
    private Cursor c=null;
    private static final String DB_NAME = "ImgDb.db";
    public static final int DB_VERSION = 2;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imgv1 = (ImageView) findViewById(R.id.imageView);
        imgv2 = (ImageView) findViewById(R.id.imageView1);

        mdb=new MyDataBase(getApplicationContext(), DB_NAME,null,

                DB_VERSION);

    }
    public void clickImage(View view)
    {

        //fire intent

        Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        startActivityForResult(intent, REQUEST_CHECK);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CHECK)
            onCaptureImageResult(data);


    }

    private void onCaptureImageResult(Intent data) {

        bm = (Bitmap) data.getExtras().get("data");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
        img = bos.toByteArray();
        imgv1.setImageBitmap(bm);

    }



    public void sand(View view)
    {
        db=mdb.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("image", img);
        db.insert("tableimage", null, cv);

        Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();

    }
    public void show(View view)
    {
        String[] col={"image"};
        db=mdb.getReadableDatabase();
        c=db.query("tableimage", col, null, null, null, null, null);
        if(c!=null){
            c.moveToFirst();
            do{
                img=c.getBlob(c.getColumnIndex("image"));
            }while(c.moveToNext());
        }
        Bitmap b1= BitmapFactory.decodeByteArray(img, 0, img.length);

        imgv2.setImageBitmap(b1);
        Toast.makeText(this, "yes", Toast.LENGTH_SHORT).show();
    }
}
2. MyDataBase.java is as 

package com.example.student.imagesqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class MyDataBase extends SQLiteOpenHelper {

    public MyDataBase(Context context, String dbname,

                      SQLiteDatabase.CursorFactory factory, int dbversion) {
        super(context, dbname, factory, dbversion);
    }

    @Override    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table tableimage(image blob);");
    }

    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}
 


Saturday, June 4, 2016

Store your Location in DataBase (SQLite) using Google Map API V2

"Jai Saraswati  Maa"

Dear All This example will helps you to capture your Location and store in DataBase (SQLite).

Please be sure you know how add Google Map API Key in your App.
Suggestion Please read my previous post Google Map PArt I & II Carefully.
I am using Android Studio 1.5.1 with API23(Marshmallow).
Thanks ..
 
A. Output will be like this
 ******* When you click on a particular location it will show you a default marker and store this location to DataBase like this .... It will show you a Toast Also....


B. Java Codes

1. DataBase Handler class    LocationsDB.java is as 

package com.exam.ravi.googlemapex1;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class LocationsDB extends SQLiteOpenHelper {

       private static String DBNAME = "locationDB";

      private static int VERSION = 1;


    public static final String ROW_ID = "_id";


    public static final String LAT = "lat";
      public static final String LNG = "lng";
    public static final String ZOOM = "zom";

    private static final String DB_TABLE = "loc";

    private SQLiteDatabase mDB;
    public LocationsDB(Context context) {
        super(context, DBNAME, null, VERSION);
        this.mDB = getWritableDatabase();
    }
    @Override    public void onCreate(SQLiteDatabase db) {
        String sql =     "create table " + DB_TABLE + " ( " +
                ROW_ID + " integer primary key autoincrement , " +
                LNG + " double , " +
                LAT + " double , " +
                ZOOM + " text " +
                " ) ";
        db.execSQL(sql);
    }

   
    public long insert(ContentValues contentValues){
        long rowID = mDB.insert(DB_TABLE, null, contentValues);
        return rowID;
    }

    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

}

2.  MainActivity is as   named as AddLoc.java

package com.exam.ravi.googlemapex1;

import android.content.ContentValues;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;


public class AddLoc extends AppCompatActivity  implements OnMapReadyCallback  {

        GoogleMap gMap;
        Context cob = this;
        @Override        protected void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
            SupportMapFragment mapFragment = (SupportMapFragment) 
                     getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);

    }
    @Override    public void onMapReady(GoogleMap googleMap)
    {
        gMap = googleMap;
        LatLng jaipur = new LatLng(26.923952,75.826743);
        CameraPosition cameraPosition = CameraPosition.builder()
         .zoom(17).tilt(20).bearing(90).target(jaipur).build();
         gMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            gMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override            public void onMapClick(LatLng point) {

                drawMarker(point);   // Draw marker

                 ContentValues contentValues = new ContentValues();
                // get  & set with contentvalues

                 contentValues.put(LocationsDB.LAT, point.latitude);
                contentValues.put(LocationsDB.LNG, point.longitude);
                contentValues.put(LocationsDB.ZOOM, gMap.getCameraPosition().zoom);
                LocationsDB lb = new LocationsDB(cob);
                // Storing the latitude, longitude and zoom level to SQLite database

                long row = lb.insert(contentValues);
                if(row>0)
                Toast.makeText(cob, "Your Location Inserted Successfully...." , 
                                               Toast.LENGTH_SHORT).show();
                else

             Toast.makeText(cob, "Something Wrong...", Toast.LENGTH_SHORT).show();

            }
        });
    }
    private void drawMarker(LatLng point){
               MarkerOptions markerOptions = new MarkerOptions();
                 markerOptions.position(point);
                gMap.addMarker(markerOptions);
    }

}

C. XML files

1. MainLayout file is as

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:map="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context="com.exam.ravi.googlemapex1.MapsActivity" >
    <fragment        android:id="@+id/map"

        android:name="com.google.android.gms.maps.SupportMapFragment"

        android:layout_width="match_parent"

        android:layout_height="match_parent"></fragment>
    </LinearLayout>

2. Manifest File is as

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.exam.ravi.googlemapex1">

    <!--         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use

         Google Maps Android API v2, but you must specify either coarse or fine

         location permissions for the 'MyLocation' functionality.     -->

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">

        <!--             The API key for Google Maps-based APIs is defined as a string resource.

             (See the file "res/values/google_maps_api.xml").

             Note that the API key is linked to the encryption key used to sign the APK.

             You need a different API key for each encryption key, including the release
             key that is used to sign the APK for publishing.

             You can define the keys for the debug and release targets in src/debug/ 
              and src/release/.         -->

        <meta-data            android:name="com.google.android.geo.API_KEY"

            android:value="@string/google_maps_key" />

        <activity            android:name=".AddLoc"

            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

    </application>

</manifest>