Getting images from SQLite database and displaying them into GridView Android Studio - android

I am new to Android Studio and I have been having some trouble with getting images, which have been stored into a database, and then displaying them into a GridView. Is there a way I can get the number of images stored in the database and then displaying them one by one, each in a different cell within GridView? This is my code so far:
NewsAddImageActivity class
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
public class NewsAddImageActivity extends AppCompatActivity {
//public MyDatabaseHelper dbHelper;
MyDatabaseHelper dbHelper = new MyDatabaseHelper(this);
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;
Bitmap bitmap;
int tabNo;
Tab1Class t1;
Tab2Class t2;
Tab3Class t3;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newsaddimage);
final ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadImagefromGallery(v);
}
});
Button submit = (Button) findViewById(R.id.addButton);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
dbHelper.addEntry(dbHelper.getBytes(bitmap)); //add image to database
byte[] image = cursor.getBlob(1); //get image from database as byte
dbHelper.getImage(image); //converts byte to bitmap
if(tabNo==0){
//place image in the grid view of tab1
}else if(tabNo==1) {
//place image in the grid view of tab2
}else if(tabNo==2){
//place image in the grid view of tab3
}
finish();
Toast.makeText(getApplicationContext(),"Added",Toast.LENGTH_LONG).show();
}
});
Button cancel = (Button) findViewById(R.id.cancelButton);
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
finish();
Toast.makeText(getApplicationContext(),"Cancelled",Toast.LENGTH_LONG).show();
}
});
}
private byte[] imageButtonToByte(ImageButton image){
Bitmap bitmap=((BitmapDrawable)image.getDrawable()).getBitmap();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray=stream.toByteArray();
return byteArray;
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton);
bitmap = ((BitmapDrawable) imageButton.getDrawable()).getBitmap();
// Set the Image in ImageView after decoding the String
imageButton.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
public void getTab(int num){
switch(num) {
case 0: tabNo=0;
case 1: tabNo=1;
case 2: tabNo=2;
}
}
}
MyDatabaseHelper Class
package com.example.mobilecomputingapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.ByteArrayOutputStream;
public class MyDatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "ImagesDB";
// Table Names
private static final String DB_TABLE = "imageTable";
// column names
private static final String KEY_NAME = "image_name";
private static final String KEY_IMAGE = "image_data";
// Table create statement
private static final String CREATE_TABLE_IMAGE = "CREATE TABLE " + DB_TABLE + "("+
KEY_NAME + " TEXT," +
KEY_IMAGE + " BLOB);";
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating table
db.execSQL(CREATE_TABLE_IMAGE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
// create new table
onCreate(db);
}
/* public void addEntry( String name, byte[] image) throws SQLiteException {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_IMAGE, image);
database.insert( DB_TABLE, null, cv );
}*/
public void addEntry( byte[] image) throws SQLiteException {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_IMAGE, image);
database.insert( DB_TABLE, null, cv );
}
// convert from bitmap to byte array
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
// convert from byte array to bitmap
public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}

you can create a bitmap of images which you want to select to save in db < don't save images save the URI(Path) of image like this.In this code selectedd images is an array which holds the selected images .And you should make method of insert images in Dbhelper and pass the string like this ..
Bitmap bitmap = thumbnails[i];
Uri uri = Utility.getImageUri(getContext(),bitmap);
byte[] path = Utility.getBytes(bitmap);
cnt++;
selecteddimages.add(uri);
String s = uri.toString();
databaseHelper.insertContact(s);
DBHELPER method of insert
public void insertContact (String name) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
long result=db.insert("images", null, contentValues);
if (result==-1){
Toast.makeText(context,"not save",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context,"save",Toast.LENGTH_SHORT).show();
}
}
UTILITIES CLass for getimage URI
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, stream);
return stream.toByteArray();
}
public static Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "title", null);
return Uri.parse(path);
}

Related

Can't run app on device when click sign up button

I have build an app that can insert and retrieve data into listview. i used database that placed on assets folder. When i run my app on device (xiaomi redmi note4) via usb debug but I can not sign up user when I click sign up button. this also happens to the emulator if I delete the database file in "/data/data/com.example.ibtb.bmkg/databases/" with logcat like this
04-12 12:09:27.789 16299-16299/? E/SQLiteLog: (1) no such table: tb_user
04-12 12:09:27.794 16299-16299/? E/SQLiteDatabase: Error inserting email=t password=t nip=t username=t nama=t
android.database.sqlite.SQLiteException: no such table: tb_user (code 1): , while compiling: INSERT INTO tb_user(email,password,nip,username,nama) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1470)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1343)
at com.example.ibtb.bmkg.database.DatabaseHelper.insertUser(DatabaseHelper.java:73)
at com.example.ibtb.bmkg.SignUp$1.onClick(SignUp.java:68)
at android.view.View.performClick(View.java:5619)
at android.view.View$PerformClick.run(View.java:22295)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6342)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)
here is my database code
package com.example.ibtb.bmkg.database;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.ibtb.bmkg.model.Instrumen;
import com.example.ibtb.bmkg.model.User;
import com.example.ibtb.bmkg.model.Pengecekan;
import java.util.ArrayList;
import java.util.List;
/**
* Created by IBTB on 08/02/2018.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static String DB_PATH = "/data/data/com.example.ibtb.bmkg/databases/";
public static String DB_NAME = "bmkgdb.db";
SQLiteDatabase myDataBase;
private final Context myContext;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void openDataBase() {
String dbPath = myContext.getDatabasePath(DB_NAME).getPath();
if (myDataBase != null && myDataBase.isOpen()) {
return;
}
myDataBase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase() {
if (myDataBase != null) {
myDataBase.close();
}
}
public long insertUser(User c){
myDataBase = this.getWritableDatabase();
ContentValues values = new ContentValues();
/*String query = "select * from tb_user";
Cursor cursor = myDataBase.rawQuery(query,null);
int count = cursor.getCount();
values.put("id_user", count); */
values.put("nama", c.getName());
values.put("nip", c.getNip());
values.put("email", c.getEmail());
values.put("username", c.getUname());
values.put("password", c.getPass());
openDataBase();
long returnValue = myDataBase.insert("tb_user", null, values);
closeDatabase();
return returnValue;}
public String searchPass(String uname) {
myDataBase = this.getReadableDatabase();
String query = "select username, password from tb_user";
Cursor cursor = myDataBase.rawQuery(query, null);
String a, b;
b = "not found";
if (cursor.moveToFirst()) {
do {
a = cursor.getString(0);
//b= cursor.getString(1);
if (a.equals(uname)) {
b = cursor.getString(1);
break;
}
}
while (cursor.moveToNext());
}
return b;
}
public List<Pengecekan> getListPengecekan() {
// String[] whereargs = new String[]{String.valueOf(id)};
Pengecekan pengecekan = null;
List<Pengecekan> PengecekanList = new ArrayList<>();
openDataBase();
Cursor cursor = myDataBase.rawQuery("SELECT A.id_pengecekan, A.pengecekan, A.normal, B.nama_alat FROM tb_pengecekan A, tb_alat B, tb_instrumen C " +
"WHERE C.id_instrumen = B.id_instrumen AND A.id_alat = B.id_alat AND C.id_instrumen = '9' ", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
pengecekan = new Pengecekan(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
PengecekanList.add(pengecekan);
/* if (cursor.moveToFirst()) {
pengecekan = new Pengecekan(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
PengecekanList.add(pengecekan);*/
cursor.moveToNext();}
cursor.close();
close();
return PengecekanList;
}
public Pengecekan getPengecekanId(int id) {
Pengecekan pengecekan = null;
openDataBase();
Cursor cursor = myDataBase.rawQuery("SELECT A.id_pengecekan, A.pengecekan, A.normal, B.nama_alat FROM tb_pengecekan A, tb_alat B, tb_instrumen C " +
"WHERE A.id_pengecekan = ?", new String[]{String.valueOf(id)});
cursor.moveToFirst();
pengecekan = new Pengecekan(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
//Only 1 resul
cursor.close();
closeDatabase();
return pengecekan;
}
public long updatePengecekan(Pengecekan pengecekan) {
ContentValues contentValues = new ContentValues();
contentValues.put("pengecekan", pengecekan.getPengecekan());
contentValues.put("normal", pengecekan.getNormal());
contentValues.put("nama_alat", pengecekan.getNama_alat());
String[] whereArgs = {Integer.toString(pengecekan.getId_pengecekan())};
openDataBase();
long returnValue = myDataBase.update("tb_pengecekan",contentValues, "id_pengecekan=?", whereArgs);
closeDatabase();
return returnValue;
}
public long addPengecekan(Pengecekan pengecekan) {
ContentValues contentValues = new ContentValues();
contentValues.put("ID", pengecekan.getId_pengecekan());
contentValues.put("pengecekan", pengecekan.getPengecekan());
contentValues.put("normal", pengecekan.getNormal());
contentValues.put("nama_alat", pengecekan.getNama_alat());
openDataBase();
long returnValue = myDataBase.insert("tb_pengecekan", null, contentValues);
closeDatabase();
return returnValue;
}
public boolean deletePengecekanById(int id) {
openDataBase();
int result = myDataBase.delete("tb_pengecekan", "id_pengecekan =?", new String[]{String.valueOf(id)});
closeDatabase();
return result !=0;
}
public List<Instrumen> getListInstrumen() {
Instrumen instrumen = null;
List<Instrumen> InstrumenList = new ArrayList<>();
openDataBase();
Cursor cursor = myDataBase.rawQuery("SELECT * FROM tb_instrumen ", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
instrumen = new Instrumen(cursor.getInt(0), cursor.getString(1));
InstrumenList.add(instrumen);
cursor.moveToNext();
}
cursor.close();
close();
return InstrumenList;
}
public Instrumen geInstrumenId(int id) {
Instrumen instrumen = null;
openDataBase();
Cursor cursor = myDataBase.rawQuery("SELECT * FROM tb_instrumen WHERE id_instrumen = ?", new String[]{String.valueOf(id)});
cursor.moveToFirst();
instrumen = new Instrumen(cursor.getInt(0), cursor.getString(1));
//Only 1 resul
cursor.close();
closeDatabase();
return instrumen;
}
}
copy database
File database = getApplicationContext().getDatabasePath(DatabaseHelper.DB_NAME);
if(false == database.exists()) {
myDbHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)) {
Toast.makeText(this, "Copy database succes", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
return;
}
}
SignUp.Java
package com.example.ibtb.bmkg;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.ibtb.bmkg.database.DatabaseHelper;
import com.example.ibtb.bmkg.model.User;
/**
* Created by IBTB on 08/02/2018.
*/
public class SignUp extends Activity {
private Button reg;
private DatabaseHelper dbHelper;
private EditText name, nip, email, uname, pass1, pass2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
dbHelper = new DatabaseHelper(getApplicationContext());
reg = (Button)findViewById(R.id.Bsignupbutton);
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = (EditText) findViewById(R.id.Tfname);
nip = (EditText) findViewById(R.id.Tfnip);
email = (EditText) findViewById(R.id.Tfemail);
uname = (EditText) findViewById(R.id.Tfuname);
pass1 = (EditText) findViewById(R.id.Tfpass1);
pass2 = (EditText) findViewById(R.id.Tfpass2);
String namestr = name.getText().toString();
String nipstr = nip.getText().toString();
String emailstr = email.getText().toString();
String unamestr = uname.getText().toString();
String pass1str = pass1.getText().toString();
String pass2str = pass2.getText().toString();
User c = new User(namestr, nipstr, emailstr, unamestr, pass1str);
if (namestr.isEmpty() || nipstr.isEmpty() || emailstr.isEmpty() || unamestr.isEmpty() || pass1str.isEmpty() || pass2str.isEmpty()) {
Toast full = Toast.makeText(SignUp.this, "Please fill all the coloumn", Toast.LENGTH_SHORT);
full.show();
} else if (!pass1str.equals(pass2str)) {
Toast pass = Toast.makeText(SignUp.this, "Password dont match", Toast.LENGTH_SHORT);
pass.show();
} else {
/*c.setName(namestr);
c.setNip(nipstr);
c.setEmail(emailstr);
c.setUname(unamestr);
c.setPass(pass1str);*/
long result = dbHelper.insertUser(c);
Intent j = new Intent(SignUp.this, MainActivity.class);
startActivity(j);
if (result > 0) {
Toast.makeText(getApplicationContext(), "Added", Toast.LENGTH_SHORT).show();
//back to main activity
finish();
} else {
Toast.makeText(getApplicationContext(), "Add failed", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
MainActivity.Java
package com.example.ibtb.bmkg;
import android.content.Intent;
import android.app.Activity;
//import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ibtb.bmkg.database.DatabaseHelper;
public class MainActivity extends Activity {
private Session session;
//private Button button;
DatabaseHelper myDbHelper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new Session(this);
// button = (Button)findViewById(R.id.button);
if(session.loggedin()){
startActivity(new Intent(MainActivity.this,Home.class));
finish();
}
}
public void onButtonClick(View v)
{
if(v.getId()==R.id.Blogin)
{
EditText a = (EditText)findViewById(R.id.Tfusername);
String str = a.getText().toString();
EditText b = (EditText)findViewById(R.id.Tfpassword);
String pass = b.getText().toString();
String password = myDbHelper.searchPass(str);
if (pass.isEmpty() || str.isEmpty()) {
Toast full = Toast.makeText(MainActivity.this, "Please enter username and password", Toast.LENGTH_SHORT);
full.show();
}
else if(pass.equals(password))
{
session.setLoggedin(true);
Intent i = new Intent (MainActivity.this, Home.class);
i.putExtra("Username",str);
startActivity(i);
finish();
}
else
{
Toast temp = Toast.makeText(MainActivity.this, "Username and Password dont match", Toast.LENGTH_SHORT);
temp.show();
}
}
if (v.getId()==R.id.Bsignup)
{
Intent i = new Intent (MainActivity.this, SignUp.class);
startActivity(i);
}
}
/*
public void press (View v){
Intent i = new Intent (MainActivity.this, ListPengecekan2.class);
startActivity(i);
}*/
}
Session.java
package com.example.ibtb.bmkg;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by IBTB on 06/04/2018.
*/
public class Session {
SharedPreferences prefs;
SharedPreferences.Editor editor;
Context ctx;
public Session(Context ctx){
this.ctx = ctx;
prefs = ctx.getSharedPreferences("myapp", Context.MODE_PRIVATE);
editor = prefs.edit();
}
public void setLoggedin(boolean logggedin){
editor.putBoolean("loggedInmode",logggedin);
editor.commit();
}
public boolean loggedin(){
return prefs.getBoolean("loggedInmode", false);
}
}
ListPengecekan.java
package com.example.ibtb.bmkg;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ibtb.bmkg.adapter.ListPengecekanAdapter;
import com.example.ibtb.bmkg.database.DatabaseHelper;
import com.example.ibtb.bmkg.model.Pengecekan;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
public class ListPengecekan extends AppCompatActivity {
private ListView lvPengecekan;
private TextView instrumen;
private ListPengecekanAdapter adapter;
private List<Pengecekan> mPengecekanList;
private Button btnAdd;
private DatabaseHelper myDbHelper;
//Cursor c = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pengecekan);
lvPengecekan = (ListView) findViewById(R.id.listview_pengecekan);
btnAdd = (Button)findViewById(R.id.Badd);
myDbHelper = new DatabaseHelper(this);
String instrumen = getIntent().getStringExtra("ins");
TextView tv = (TextView) findViewById(R.id.tv_instrumen);
tv.setText(instrumen);
File database = getApplicationContext().getDatabasePath(DatabaseHelper.DB_NAME);
if(false == database.exists()) {
myDbHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)) {
Toast.makeText(this, "Copy database succes", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
return;
}
}
//String id = getIntent().getStringExtra("id");
mPengecekanList = myDbHelper.getListPengecekan();
adapter = new ListPengecekanAdapter (this, mPengecekanList);
lvPengecekan.setAdapter(adapter);
}
#Override
protected void onResume() {
super.onResume();
mPengecekanList = myDbHelper.getListPengecekan();
//Init adapter
adapter.updateList(mPengecekanList);
}
private boolean copyDatabase(Context context) {
try {
InputStream inputStream = context.getAssets().open(DatabaseHelper.DB_NAME);
String outFileName = DatabaseHelper.DB_PATH + DatabaseHelper.DB_NAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.v("ListPengecekan", "DB copied");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
// });
}
public void onRadioButtonClicked(View view) {
String kondisi="";
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.B:
if (checked)
kondisi = "Baik";
break;
case R.id.RR:
if (checked)
kondisi = "Rusak ringan";
AlertDialog.Builder mBuilder = new AlertDialog.Builder(ListPengecekan.this);
View mView = getLayoutInflater().inflate(R.layout.dialogrusak, null);
mBuilder.setTitle("Keterangan kerusakan");
final Spinner mSpinner = (Spinner) mView.findViewById(R.id.Spenanganan);
final Spinner mSpinner1 = (Spinner) mView.findViewById(R.id.Shasil);
final EditText kronologi = (EditText) mView.findViewById(R.id.ekro);
final EditText lapor = (EditText) mView.findViewById(R.id.elapor);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListPengecekan.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.penaganan));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(ListPengecekan.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.hasil));
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner1.setAdapter(adapter1);
mBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String Kronologi = kronologi.getText().toString();
Toast.makeText(ListPengecekan.this, Kronologi, Toast.LENGTH_SHORT).show();
if (!mSpinner.getSelectedItem().toString().equalsIgnoreCase("Pilih penanganan…")) {
Toast.makeText(ListPengecekan.this, mSpinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
dialogInterface.dismiss();
}
if (!mSpinner.getSelectedItem().toString().equalsIgnoreCase("Pilih hasil…")) {
Toast.makeText(ListPengecekan.this, mSpinner1.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
dialogInterface.dismiss();
}
String Lapor = lapor.getText().toString();
Toast.makeText(ListPengecekan.this, Lapor, Toast.LENGTH_SHORT).show();
}
});
mBuilder.setNegativeButton("Batal", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
break;
case R.id.RB:
if (checked)
kondisi = "Rusak berat";
AlertDialog.Builder mBuilder1 = new AlertDialog.Builder(ListPengecekan.this);
View mView1 = getLayoutInflater().inflate(R.layout.dialogrusak, null);
mBuilder1.setTitle("Keterangan kerusakan");
final Spinner mSpinner2 = (Spinner) mView1.findViewById(R.id.Spenanganan);
final Spinner mSpinner3 = (Spinner) mView1.findViewById(R.id.Shasil);
final EditText kronologi1 = (EditText) mView1.findViewById(R.id.ekro);
final EditText lapor1 = (EditText) mView1.findViewById(R.id.elapor);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(ListPengecekan.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.penaganan));
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner2.setAdapter(adapter2);
ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(ListPengecekan.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.hasil));
adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner3.setAdapter(adapter3);
mBuilder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String Kronologi = kronologi1.getText().toString();
Toast.makeText(ListPengecekan.this, Kronologi, Toast.LENGTH_SHORT).show();
if (!mSpinner2.getSelectedItem().toString().equalsIgnoreCase("Pilih penanganan…")) {
Toast.makeText(ListPengecekan.this, mSpinner2.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
dialogInterface.dismiss();
}
if (!mSpinner3.getSelectedItem().toString().equalsIgnoreCase("Pilih hasil…")) {
Toast.makeText(ListPengecekan.this, mSpinner3.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
dialogInterface.dismiss();
}
String Lapor = lapor1.getText().toString();
Toast.makeText(ListPengecekan.this, Lapor, Toast.LENGTH_SHORT).show();
}
});
mBuilder1.setNegativeButton("Batal", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
mBuilder1.setView(mView1);
AlertDialog dialog1 = mBuilder1.create();
dialog1.show();
break;
}
//myDbHelper.execSQl
}
}
Ok your issue could be that the onCreate method does nothing. if you delete an existing/useable database then there are no tables created.
You need to use db.execSql(a_string_with_the_sql_to_create_your_tables); in the onCreate method.
Something like :-
#Override
public void onCreate(SQLiteDatabase db) {
crtsql = "CREATE TABLE IF NOT EXISTS tb_user (id INTEGER PRIMARY KEY,nama TEXT,nip TEXT, email TEXT, password TEXT)";
db.execSQL(crtsql);
}
Note you'd need to do the same for all the other tables. Noting that you need a db.execSQL for each as you can only run 1 SQL statement at a time.
An exception would be if you have other code that copies the database from the assets folder. If so including that would be relevant as if this is the case, this not working could be the issue.
Edit re comments
It has been determined that issue is highly likely that the copy of the database from the assets folder is not being invoked.
To simplify the fix the following is suggested (rather than edit code) :-
Create a Java Class named CopyDBFromAssets i.e. file CopyDBFromAssets.java and copt the following into that class
:-
public class CopyDBFromAssets {
private static final String TAG = "DBASSETCOPY";
String mDBPath, mDatabasename;
CopyDBFromAssets(Context context, String databasename) {
mDatabasename = databasename;
mDBPath = context.getDatabasePath(mDatabasename).getPath();
if(!ifDatabaseExists(mDBPath)) {
Log.d(TAG,
"Attempting to copy database " +
mDatabasename +
" from assets folder."
);
if (copyDatabase(context)) {
Log.d(TAG,"Database " +
mDatabasename + " successfully copied.");
} else {
Log.e(TAG,"Database " + mDatabasename + " NOT COPIED!!!");
}
}
}
private boolean copyDatabase(Context context) {
try {
InputStream inputStream = context.getAssets().open(mDatabasename);
String outFileName = mDBPath;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.v(TAG, "DB copied");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
private boolean ifDatabaseExists(String dbpath) {
File db = new File(dbpath);
if(db.exists()) return true;
File dir = new File(db.getParent());
if (!dir.exists()) {
dir.mkdirs();
}
return false;
}
}
Edit MainActivity.java to add a single line to invoke the above as per
:-
public class MainActivity extends Activity {
private Session session;
//private Button button;
//DatabaseHelper myDbHelper = new DatabaseHelper(this); //<<<< COMMENTED OUT
DatabaseHelper myDbHelper; //<<<< ADDED
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CopyDBFromAssets cdbfa = new CopyDBFromAssets(this,DatabaseHelper.DB_NAME); //<<<< ADDED LINE
myDbHelper = new DatabaseHelper(this); //<<<< ADDED LINE
session = new Session(this);
// button = (Button)findViewById(R.id.button);
if(session.loggedin()){
startActivity(new Intent(MainActivity.this,Home.class));
finish();
}
}
........ the rest of MainActivity.Java
Notes
DatabaseHelper myDbHelper = new DatabaseHelper(this); has been commented out and split into declaration and instantiation (set)
check all lines with //<<<<
After making the changes above delete the App's data and run. Check the log you should see something along the lines of
:-
04-12 12:39:31.672 1568-1568/soanswers.soanswers D/DBASSETCOPY: Attempting to copy database mydb from assets folder.
04-12 12:39:31.672 1568-1568/soanswers.soanswers V/DBASSETCOPY: DB copied
04-12 12:39:31.672 1568-1568/soanswers.soanswers D/DBASSETCOPY: Database mydb successfully copied.
In the above the database used was called mydb rather than bmkgdb.db
You are inserting record into table which is not exist. Create table before performing insert operation.

Too much data returned warning on sqlite database

I am trying to create an app where the user can select their profile picture from gallery. I decided to save their profile picture to my Database as Blob. I am able to save the image and even retrieve it. The thing is, I am not able to replace it, or whenever I click it again, the application stops working and when I check my table where I store the image it says "Too much data returned..."
public class AccountFragment extends Fragment implements OnClickListener {
private LoginDataBaseAdapter loginDataBaseAdapter;
Bitmap image;
Bitmap bitmap;
String picture_location;
TextView textTargetUri;
ImageView targetImage;
public static final String MyPREFERENCES = "MyPrefs" ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// create a instance of SQLite Database
loginDataBaseAdapter = new LoginDataBaseAdapter(getActivity());
loginDataBaseAdapter=loginDataBaseAdapter.open();
//intialize variables
textTargetUri = (TextView) rootView.findViewById(R.id.targeturi);
targetImage=(ImageView) rootView.findViewById(R.id.profpic);
targetImage.setOnClickListener(new ImageView.OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}});
showpic();
return rootView;
}
#Override
public void onActivityResult( int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
Uri targetUri = data.getData();
picture_location = targetUri.toString();
textTargetUri.setText(targetUri.toString());
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(targetUri));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
loginDataBaseAdapter.insertPhoto(byteArray);
showpic();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
public void showpic() {
Cursor cursor = loginDataBaseAdapter.fetchProfileImageFromDatabase();
if(cursor != null)
{
cursor.moveToFirst();
byte[] data = cursor.getBlob(cursor.getColumnIndex("Path"));
ByteArrayInputStream imageStream = new ByteArrayInputStream(data);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
targetImage.setImageBitmap(theImage);
}
cursor.close();
}
}
and my database handler:
//IMAGE
public static final String Profpic_TABLE = "ProfilePic";
public static final String KEY_ProfpicID = "_id";
public static final String KEY_ProfPic = "Path";
//ProfilePic-Table
static final String DATABASE_ProfPic =
"create table " + Profpic_TABLE + " ("
+ KEY_ProfpicID + " integer primary key DEFAULT 1, "
+ KEY_ProfPic + " BLOB);";
public long insertPhoto(byte[] EImage) {
db.execSQL("delete from "+ Profpic_TABLE);
try {
System.out.println("Function call : ");
ContentValues values = new ContentValues();
values.put(KEY_ProfPic, EImage);
return db.insert(Profpic_TABLE, null, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public Cursor fetchProfileImageFromDatabase()
{
return db.rawQuery("SELECT Path FROM ProfilePic where _id = 1 " , null);
}
}
I was able to finally solve it. Turns out I have to do it this way instead:
public void showpic() {
LoginDataBaseAdapter db = loginDataBaseAdapter.open();
boolean emptytab = false;
boolean empty = db.checkPic(null, emptytab);
//Cursor cursor = loginDataBaseAdapter.fetchProfileImageFromDatabase();
if(empty==false)
{
Cursor cursor = loginDataBaseAdapter.fetchProfileImageFromDatabase();
cursor.moveToFirst();
byte[] data = cursor.getBlob(cursor.getColumnIndex("Path"));
ByteArrayInputStream imageStream = new ByteArrayInputStream(data);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
targetImage.setImageBitmap(theImage);
cursor.close();
}
}
and on my db adapter I added this:
public boolean checkPic(String count, Object object) {
boolean empty = false;
Cursor cursor = db.rawQuery("SELECT count(*) FROM ProfilePic", null);
if(cursor != null)
{
cursor.moveToFirst();
if(cursor.getInt(0)== 0)
{
empty = true; //rows not null;
}
else
{
empty = false; // rows null;
}
}
return empty;
}

how to save image in sqllite database?

this is my code below which browse imagew gellery and pick image but how do insert image view in database? this code sucessfuly show on screen selected image but not store in database how to pass image parameter? in that line where i comment/what i write here/
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class AddEditCountry extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private EditText Donedate;
private EditText Notes;
private EditText Person;
private ImageView imageView1;
Bitmap yourSelectedImage;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
nameEt = (EditText) findViewById(R.id.Address);
capEt = (EditText) findViewById(R.id.Stage);
codeEt = (EditText) findViewById(R.id.Dueby);
Donedate = (EditText) findViewById(R.id.Donedate);
Notes = (EditText) findViewById(R.id.Notes);
Person = (EditText) findViewById(R.id.Person);
imageView1 = (ImageView) findViewById(R.id.imageView1);
Button Browse = (Button) findViewById(R.id.Browse);
Browse.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
Donedate.setText(extras.getString("Location"));
Notes.setText(extras.getString("Notes"));
Person.setText(extras.getString("Person"));
imageView1.setImageURI(yourSelectedImage);
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
#Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new
AlertDialog.Builder(AddEditCountry.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});
}
private void saveContact()
{
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
/* what i write here for image*/
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
codeEt.getText().toString(),
Donedate.getText().toString(),
Notes.getText().toString(),
Person.getText().toString(), null
);
}
else
/* what i wirte here for image*/ {
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
codeEt.getText().toString(),
Donedate.getText().toString(),
Notes.getText().toString(),
Person.getText().toString(), null
);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex); // file path of selected image
cursor.close();
// Convert file path into bitmap image using below line.
yourSelectedImage = BitmapFactory.decodeFile(filePath);
// put bitmapimage in your imageview
imageView1.setImageBitmap(yourSelectedImage);
}
}
}
}
First make field in sqlite as blob datatype
than get byte and store in databse image.getBytes();
or if you have bitmap than convert into byte array
and store into database
public static byte[] getBitmapAsByteArray(Bitmap bitmap, boolean type) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
if (type) {
bitmap.compress(CompressFormat.PNG, 0, outputStream);
} else {
bitmap.compress(CompressFormat.JPEG, 0, outputStream);
}
return outputStream.toByteArray();
}
Please use below code for store images into sqlite database, it will solve your problem.
MySQLActivity.java:-
public class MySQLActivity extends Activity implements OnClickListener
{
protected static TextView textView;
protected static ImageView bmImage;
protected Button start;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bmImage = (ImageView)findViewById(R.id.imageView1);
textView = (TextView) findViewById(R.id.textView1);
start = (Button) findViewById(R.id.button1);
start.setOnClickListener(this);
DownloadFile();
}
public void onClick(View v)
{
SQLiteDatabase myDb;
String MySQL;
int icount;
byte[] byteImage1 = null;
byte[] byteImage2 = null;
MySQL="create table emp1(_id INTEGER primary key autoincrement, fio TEXT not null, picture BLOB);";
myDb = openOrCreateDatabase("/sdcard/Nick/MyWeatherDB.db", Context.MODE_PRIVATE, null);
String s=myDb.getPath();
textView.append("\r\n" + s+"\r\n");
myDb.execSQL("delete from emp1");
ContentValues newValues = new ContentValues();
newValues.put("fio", "Иванов Петр Сергеевич");
/////////// insert picture to blob field /////////////////////
try
{
FileInputStream instream = new FileInputStream("/sdcard/Dipak/Keshariya.png");
BufferedInputStream bif = new BufferedInputStream(instream);
byteImage1 = new byte[bif.available()];
bif.read(byteImage1);
textView.append("\r\n" + byteImage1.length+"\r\n");
newValues.put("picture", byteImage1);
long ret = myDb.insert("emp1", null, newValues);
if(ret<0) textView.append("\r\n!!! Error add blob filed!!!\r\n");
} catch (IOException e) {
textView.append("\r\n!!! Error: " + e+"!!!\r\n");
}
////////////Read data ////////////////////////////
Cursor cur = myDb.query("emp1",null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false)
{
textView.append("\r\n" + cur.getString(1)+"\r\n");
cur.moveToNext();
}
///////Read data from blob field////////////////////
cur.moveToFirst();
byteImage2=cur.getBlob(cur.getColumnIndex("picture"));
bmImage.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0, byteImage2.length));
textView.append("\r\n" + byteImage2.length+"\r\n");
//////////////////////////
cur.close();
myDb.close();
}
public void DownloadFile()
{
Bitmap bitmap1 = null;
bitmap1 = BitmapFactory.decodeFile("/sdcard/Dipak/Dipak.jpg"); //weather.png");
bmImage.setImageBitmap(bitmap1);
}
}
i would suggest to avoid saving images to database , not only on android .
this makes sense since it will slow down anything that is related to the database . also , the cursor won't be able to cache the results in order to move between the rows of the tables.
instead , put a filename to point to a path on your app's storage . you could also add where it's stored (internal/external storage) .

How to insert selected image in a SqlLite database ?

My code is not inserting image in database. How can I insert selected image in the database, and also retrieve it ? I'm following this tutorial:
http://vimaltuts.com/android-tutorial-for-beginners/android-sqlite-database-example
What modifications the code below requires to insert selected image in database ?
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class AddEditCountry extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private EditText Donedate;
private EditText Notes;
private EditText Person;
private ImageView imageView1;
Bitmap yourSelectedImage;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
nameEt = (EditText) findViewById(R.id.Address);
capEt = (EditText) findViewById(R.id.Stage);
codeEt = (EditText) findViewById(R.id.Dueby);
Donedate = (EditText) findViewById(R.id.Donedate);
Notes = (EditText) findViewById(R.id.Notes);
Person = (EditText) findViewById(R.id.Person);
imageView1 = (ImageView) findViewById(R.id.imageView1);
Button Browse = (Button) findViewById(R.id.Browse);
Browse.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
Donedate.setText(extras.getString("Location"));
Notes.setText(extras.getString("Notes"));
Person.setText(extras.getString("Person"));
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
#Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new
AlertDialog.Builder(AddEditCountry.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});
}
private void saveContact()
{
// ByteArrayOutputStream outStr = new ByteArrayOutputStream();
// yourSelectedImage.compress(CompressFormat.PNG, 100, outStr);
// byte[] blob = outStr.toByteArray();
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
codeEt.getText().toString(),
Donedate.getText().toString(),
Notes.getText().toString(),
Person.getText().toString()
//,blob
);
}
else
{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
codeEt.getText().toString(),
Donedate.getText().toString(),
Notes.getText().toString(),
Person.getText().toString()
//, blob
);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex); // file path
of selected image
cursor.close();
// Convert file path into bitmap image using below
line.
yourSelectedImage = BitmapFactory.decodeFile(filePath);
// put bitmapimage in your imageview
imageView1.setImageBitmap(yourSelectedImage);
}
}
}
}
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseConnector {
private static final String DB_NAME = "WorldCountries";
private SQLiteDatabase database;
private DatabaseOpenHelper dbOpenHelper;
public DatabaseConnector(Context context) {
dbOpenHelper = new DatabaseOpenHelper(context, DB_NAME, null, 1);
}
public void open() throws SQLException
{
//open database in reading/writing mode
database = dbOpenHelper.getWritableDatabase();
}
public void close()
{
if (database != null)
database.close();
}
public void insertContact(String name, String cap, String code, String
LocationEd, String Notes, String Person)
///,byte[] blob)
{
ContentValues newCon = new ContentValues();
newCon.put("name", name);
newCon.put("cap", cap);
newCon.put("code", code);
newCon.put("Location",LocationEd);
newCon.put("Notes",Notes);
newCon.put("Person",Person);
// newCon.put("Image", blob);
open();
database.insert("country", null, newCon);
close();
}
public void updateContact(long id, String name, String
cap,String code,String LocationEd, String Notes, String Person)
//,byte[] blob)
{
ContentValues editCon = new ContentValues();
editCon.put("name", name);
editCon.put("cap", cap);
editCon.put("code", code);
editCon.put("Location", LocationEd);
editCon.put("Notes", Notes);
editCon.put("Person", Person);
// editCon.put("Image", blob);
open();
database.update("country", editCon, "_id=" + id, null);
close();
}
public Cursor getAllContacts()
{
return database.query("country", new String[] {"_id",
"name"},
null, null, null, null, "name");
}
public Cursor getOneContact(long id)
{
return database.query("country", null, "_id=" + id, null,
null, null, null);
}
public void deleteContact(long id)
{
open();
database.delete("country", "_id=" + id, null);
close();
}
}
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createQuery = "CREATE TABLE country (_id integer primary key
autoincrement,name text,cap text,code text,Location double,Notes text,Person
text,blob BLOB);";
db.execSQL(createQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
import java.io.ByteArrayInputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class ViewCountry extends Activity {
private long rowID;
private TextView nameTv;
private TextView capTv;
private TextView codeTv;
private TextView Locationlb;
private TextView Noteslb;
private TextView Personlb;
byte[] byteImage2 = null;
private ImageView imageView2;
Bitmap yourSelectedImage;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.view_country);
setUpViews();
Bundle extras = getIntent().getExtras();
rowID = extras.getLong(CountryList.ROW_ID);
}
private void setUpViews() {
nameTv = (TextView) findViewById(R.id.nameText);
capTv = (TextView) findViewById(R.id.capText);
codeTv = (TextView) findViewById(R.id.codeText);
Locationlb = (TextView) findViewById(R.id.Location_lbl);
Noteslb = (TextView) findViewById(R.id.Notes_lbl);
Personlb = (TextView) findViewById(R.id.Person_lbl);
imageView2= (ImageView) findViewById(R.id.imageView2);
Button Browse2 = (Button) findViewById(R.id.Browse2);
Browse2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onResume()
{
super.onResume();
new LoadContacts().execute(rowID);
}
private class LoadContacts extends AsyncTask<Long, Object, Cursor>
{
DatabaseConnector dbConnector = new DatabaseConnector(ViewCountry.this);
#Override
protected Cursor doInBackground(Long... params)
{
dbConnector.open();
return dbConnector.getOneContact(params[0]);
}
#Override
protected void onPostExecute(Cursor result)
{
super.onPostExecute(result);
result.moveToFirst();
// get the column index for each data item
int nameIndex = result.getColumnIndex("name");
int capIndex = result.getColumnIndex("cap");
int codeIndex = result.getColumnIndex("code");
int LocationIndex = result.getColumnIndex("Location");
int NotesIndex = result.getColumnIndex("Notes");
int PersonIndex = result.getColumnIndex("Person");
// byte[] blob = result.getBlob("image");
// byte[] data = result.getBlob(result.getColumnIndex("image"));
// byte[] blob result.getColumnIndex(MyBaseColumn.MyTable.ImageField));
nameTv.setText(result.getString(nameIndex));
capTv.setText(result.getString(capIndex));
codeTv.setText(result.getString(codeIndex));
Locationlb.setText(result.getString(LocationIndex));
Noteslb.setText(result.getString(NotesIndex));
Personlb.setText(result.getString(PersonIndex));
// ByteArrayInputStream input = new ByteArrayInputStream(byteImage2);
// Bitmap bit = BitmapFactory.decodeStream(input);
// imageView2.setImageBitmap(bit);
// imageView2.setImageURI(byteImage2);
imageView2.setImageBitmap(yourSelectedImage);
result.close();
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.editItem:
Intent addEditContact =
new Intent(this, AddEditCountry.class);
addEditContact.putExtra(CountryList.ROW_ID, rowID);
addEditContact.putExtra("name", nameTv.getText());
addEditContact.putExtra("cap", capTv.getText());
addEditContact.putExtra("code", codeTv.getText());
addEditContact.putExtra("Location", Locationlb.getText());
addEditContact.putExtra("Notes", Noteslb.getText());
addEditContact.putExtra("Person", Personlb.getText());
// addEditContact.putExtra("blob", yourSelectedImage);
startActivity(addEditContact);
return true;
case R.id.deleteItem:
deleteContact();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void deleteContact()
{
AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.this);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int button)
{
final DatabaseConnector dbConnector =
new DatabaseConnector(ViewCountry.this);
AsyncTask<Long, Object, Object> deleteTask =
new AsyncTask<Long, Object, Object>()
{
#Override
protected Object doInBackground(Long... params)
{
dbConnector.deleteContact(params[0]);
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
}
);
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent
imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex); // file path
of selected image
cursor.close();
// Convert file path into bitmap image using below
line.
yourSelectedImage = BitmapFactory.decodeFile(filePath);
// put bitmapimage in your imageview
imageView2.setImageBitmap(yourSelectedImage);
}
}
}
}
Do not put images into database. Keep the file on the filesystem (SD card or internal storage) and put reference to it into database. But do not put images directly.
There's no need to put a binary blob in a database. The primary goal of a database is to be queried, ie it organizes data so that it's fast to locate it later. An image is a sequence of bytes, and you won't be able to filter your query based on it, so simply store the image in the filesystem, and maybe adopt a convention that it will be named after the row's ID.

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);
}
}
}
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.
Create DataBase helper class like this..
On Capturing the image insert the image by converting into bytes:
Imagehelper help=new Imagehelper(this);
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
help.insert(byteArray);
}
To retrieve Form the Database:
Imagehelper help=new Imagehelper(this);
Cursor c= help.getAll();
int i=0;
if(c.getCount()>0)
{
Bitmap[] array=new Bitmap[c.getCount()];
c.moveToFirst();
while(c.isAfterLast()==false)
{
byte[] bytes=c.getBlob(c.getColumnIndex("imageblob"));
array[i]=BitmapFactory.decodeByteArray(bytes, 0, 0);
c.moveToNext();
i++;
}
Log.e("Bitmap length",""+array.length);
}
Pass this Bitmap array to ListView
I am not convinced to save the bitmap itself in a sqlite database.
But it is possible when using Blob. A blob needs a byte[].
You could get a byte array by saving the Bitmap (with compress) and reading the file again.
http://developer.android.com/reference/android/graphics/Bitmap.html
Bitmap b;
File f = new File (...);
FileOutputStream fs = new FileOutputStream (f);
b.compress(JPEG, 85, fs);
fs.close ();
// Reread the file f into a byte []
or
Bitmap b;
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
b.compress(JPEG, 85, baos);
baos.close ();
byte[] blob = baos.toByteArray ();
b.compress(JPEG, 85, baos)
Or you could serialize the Bitmap into ByteArrayOutputStream (using ObjectOutputStream)
Bitmap b;
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
ObjectOutputStream oos = new ObjectOutputStream (baos);
oos.write (b);
oos.close ();
baos.close ();
byte[] blob = baos.toByteArray ();
However, probably it make sense to save the Bitmap as files (JPG or PNG) because they may become larger in size. The database will only hold the path info about that image.

Categories

Resources