1

Here is my code: Here Is how i select image from gallery or capture it. Please tell me How i can save it.

     private void selectImage() {
    final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
    AlertDialog.Builder builder = new AlertDialog.Builder(Enrolement.this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, REQUEST_CAMERA);
            } else if (items[item].equals("Choose from Library")) {
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(
                        Intent.createChooser(intent, "Select File"),
                        SELECT_FILE);
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_FILE)
            onSelectFromGalleryResult(data);
        else if (requestCode == REQUEST_CAMERA)
            onCaptureImageResult(data);
    }
}

For Capture

private void onCaptureImageResult(Intent data) {
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");

    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ivImage.setImageBitmap(thumbnail);
}

For Gallery i am using this

@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
    Uri selectedImageUri = data.getData();
    String[] projection = { MediaStore.MediaColumns.DATA };
    Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
            null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
    cursor.moveToFirst();

    String selectedImagePath = cursor.getString(column_index);

    Bitmap bm;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(selectedImagePath, options);
    final int REQUIRED_SIZE = 200;
    int scale = 1;
    while (options.outWidth / scale / 2 >= REQUIRED_SIZE
            && options.outHeight / scale / 2 >= REQUIRED_SIZE)
        scale *= 2;
    options.inSampleSize = scale;
    options.inJustDecodeBounds = false;
    bm = BitmapFactory.decodeFile(selectedImagePath, options);

    ivImage.setImageBitmap(bm);
}

after This i want to retrieve Image in a List View. This time i am able to fetch only other info except image. Thanks

My DataBase class extending SQLiteOpenHelper

   public class MyDBHandler extends SQLiteOpenHelper {


private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "employee.db";
public static final String TABLE_EMPLOYEE = "employeeData";
public static final String COLUMN_ID = "id";

public static final String COLUMN_NAME = "name";
public static final String COLUMN_DOB  = "dob";
public static final String COLUMN_ADDRESS = "address";
public static final String COLUMN_OCCUPATION = "Occupation";
//public static final String COLUMN_IMAGE_PATH = "image_path";
public static final String KEY_IMAGE = "image_data";

public MyDBHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("DROP TABLE IF EXISTS TABLE_EMPLOYEE");

    String query = "CREATE TABLE " + TABLE_EMPLOYEE + " ( " +

            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , " +
            COLUMN_NAME + " TEXT ," +
            COLUMN_DOB + " TEXT ," +
            COLUMN_ADDRESS + " TEXT ," +
            KEY_IMAGE + "BLOB ," +
            // COLUMN_IMAGE_PATH + " TEXT ," +
            COLUMN_OCCUPATION + " TEXT " +
            ");";

    db.execSQL(query);

}

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

    db.execSQL("DROP TABLE IF EXISTS" + TABLE_EMPLOYEE);

    onCreate(db);

}

// Add a new row to the databse
public boolean addemplyee(Employee employee) {
    ContentValues values = new ContentValues();
    //values.put(COLUMN_ID, employee.get_id());
    values.put(COLUMN_NAME, employee.get_name());
    values.put(COLUMN_DOB, employee.get_dob());
    values.put(COLUMN_ADDRESS, employee.get_address());
    values.put(COLUMN_OCCUPATION, employee.get_occupation());
    values.put(KEY_IMAGE, employee.get_image());
    //values.put(COLUMN_IMAGE_PATH, employee.get_occupation());

    SQLiteDatabase db = getWritableDatabase();
    Log.i("", "isinsert===" + db.insert(TABLE_EMPLOYEE, null, values));
    db.close();
    return true;
}

public Cursor getAllEmployees() {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res = db.rawQuery("SELECT * FROM " + TABLE_EMPLOYEE, null);
    return res;
 }
 }

Please check this one ::

Gaurav Setia
  • 274
  • 3
  • 7
  • 1
    You can save the path in database as String and copy the image into your app's data directory. Thats a good way.Less code easy to manage. – SRB Bans Nov 17 '15 at 08:39
  • Where is the database code? And why so much other code? It's unclear if you want to store an image or a file also. – greenapps Nov 17 '15 at 08:40
  • 1
    Please refer this thread: http://stackoverflow.com/questions/9357668/how-to-store-image-in-sqlite-database – galvan Nov 17 '15 at 08:43

2 Answers2

1

I assume you already gotten your picture into a byte array variable. To store it in sqlite database as BLOB, you need a database class that extends SQLiteOpenHelper. You will define your methods in this class to save and retrieve image, also to create tables and all other CRUD operations. I have created a Database class for you to use in your project. You can modify to suite your need.

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;


/**
 * Created by Joe Adeoye on 17/11/2015.
 */
public class Database extends SQLiteOpenHelper{
    private static String DATABASE_NAME = "MyDatabase.db";
    private static int DATABASE_VERSION = 1;
    //private SQLiteDatabase mDatabase;
    private Context mContext;
    public Database(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //initialise database
    }

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

    }
    public boolean isTableExists(String tableName) {
        SQLiteDatabase mDatabase = getReadableDatabase();

        Cursor cursor = mDatabase.rawQuery("select name from sqlite_master where type='table' and name='"+tableName+"'", null);
        if(cursor!=null) {
            if(cursor.getCount()>0) {
                cursor.close();
                return true;
            }
            cursor.close();
        }
        return false;
    }

    private boolean createProfile(){
        SQLiteDatabase mDatabase = getWritableDatabase();

        String sql = "CREATE TABLE tbl_profile (id INTEGER PRIMARY KEY,dp BLOB)";
        try{
            mDatabase.execSQL(sql);
            return true;
        }
        catch(Exception e){
            return false;
        }
    }

    public boolean updateProfileDp(byte[] dp){
        ContentValues values = new ContentValues();
        values.put("dp", dp);
        if(isTableExists("tbl_profile")){
            SQLiteDatabase mDatabase = getWritableDatabase();
            try{
                mDatabase.update("tbl_profile", values, null, null);
                return true;
            }
            catch(Exception e){
                return false;
            }

        }
        else{
            createProfile();
            SQLiteDatabase db = getWritableDatabase();
            long id = db.insert("tbl_profile", null, values);
            if(id  != -1){
                return true;
            }
            else{
                return false;
            }
        }
    }

    public byte[] getProfileDp(){
        String selectQuery = "SELECT * FROM tbl_profile";

        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        byte[] result;
        if (cursor.moveToFirst()) {
            result = cursor.getBlob(1);
        }
        cursor.close();
        return result;
    }
}

Usage:

Database db = new Database(MyActivity.this);
db.updateProfileDp(myImageBytes); //pass the byte array containing your image here

to retrieve back your image:

byte[] myImage = db.getProfileDp(); //you will have your image back

finally, close the db object

db.close();

Hope it helps

JoeAdeoye
  • 170
  • 2
  • 10
  • Thanks : I have my database class but i dind't khw how to use BLOB and how to save image path to database ... @Gaurav Setia – Gaurav Setia Nov 17 '15 at 10:43
  • Let me show my database class to u (user2759156) , I am editing my question .pls chk @GauravSetia – Gaurav Setia Nov 17 '15 at 10:44
  • 1
    If you want to save image path, then YOU DONT NEED BLOB. BLOB are byte arrays while paths are strings. If you are to save path, then save it as TEXT but if you want to save the real image, then save as BLOB. You can refer to my answer to see methods you can use to save image as BLOB – JoeAdeoye Nov 17 '15 at 10:46
  • I have checked your database code, your code seems to be correct but check your Employee class's get_image() method and verify if it returns a valid byte array data – JoeAdeoye Nov 17 '15 at 10:58
  • I also noticed a slight mistake in your code which may cause your table not to be created. Look at the onCreate method of your Database class, in the line that says: KEY_IMAGE + "BLOB ," + change it to this KEY_IMAGE + " BLOB ," + just add a space between the first double quote and the BLOB keyword – JoeAdeoye Nov 17 '15 at 11:00
  • If it still doesn't work, consider removing the AUTOINCREMENT statement from your CREATE TABLE statement. Since it has been set has PRIMARY KEY, then auto increment automatically applies to it – JoeAdeoye Nov 17 '15 at 11:18
0

I also noticed a slight mistake in your code which may cause your table not to be created. Look at the onCreate method of your Database class, in the line that says:

KEY_IMAGE + "BLOB ," +

change it to this:

KEY_IMAGE + " BLOB ," +

just add a space between the first double quote and the BLOB keyword

If it still doesn't work, consider removing the AUTOINCREMENT statement from your CREATE TABLE statement. Since it has been set has PRIMARY KEY, then auto increment automatically applies to it.

JoeAdeoye
  • 170
  • 2
  • 10