Hello Friends,
On many demands today I am writing a very Important post on Take Image from Camera/Gallery and save it into SqLite database and display it in a List-View. After that on select one image it will take you second detail page and from here you can delete this image from SqLite. Follow my blog step by step-
Screen Shot:
1)SQLiteDemoActivity.java
package com.manish.sqlite;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class SQLiteDemoActivity extends Activity {
Button addImage;
ArrayList<Contact> imageArry = new ArrayList<Contact>();
ContactImageAdapter imageAdapter;
private static final int CAMERA_REQUEST = 1;
private static final int PICK_FROM_GALLERY = 2;
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);
/**
* go to next activity for detail image
*/
dataList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
imageName = imageArry.get(position).getImage();
imageId = imageArry.get(position).getID();
Log.d("Before Send:****", imageName + "-" + imageId);
// convert byte to bitmap
ByteArrayInputStream imageStream = new ByteArrayInputStream(
imageName);
theImage = BitmapFactory.decodeStream(imageStream);
Intent intent = new Intent(SQLiteDemoActivity.this,
DisplayImageActivity.class);
intent.putExtra("imagename", theImage);
intent.putExtra("imageid", imageId);
startActivity(intent);
}
});
/**
* open dialog for choose camera/gallery
*/
final String[] option = new String[] { "Take from Camera",
"Select from Gallery" };
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();
}
if (which == 1) {
callGallery();
}
}
});
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();
Log.e("output before conversion", imageInByte.toString());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Android", imageInByte));
Intent i = new Intent(SQLiteDemoActivity.this,
SQLiteDemoActivity.class);
startActivity(i);
finish();
}
break;
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Bitmap yourImage = extras2.getParcelable("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Log.e("output before conversion", imageInByte.toString());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Android", imageInByte));
Intent i = new Intent(SQLiteDemoActivity.this,
SQLiteDemoActivity.class);
startActivity(i);
finish();
}
break;
}
}
/**
* open camera method
*/
public void callCamera() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", 0);
cameraIntent.putExtra("aspectY", 0);
cameraIntent.putExtra("outputX", 200);
cameraIntent.putExtra("outputY", 150);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
/**
* open gallery method
*/
public void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
PICK_FROM_GALLERY);
}
}
2)DataBaseHandler.java
package com.manish.sqlite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
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 = "imagedb";
// Contacts table name
private static final String TABLE_CONTACTS = "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, Update, Delete) 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(2));
// 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;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_IMAGE, contact.getImage());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
3)ContactImageAdapter.java
package com.manish.sqlite;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
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;
}
}
On many demands today I am writing a very Important post on Take Image from Camera/Gallery and save it into SqLite database and display it in a List-View. After that on select one image it will take you second detail page and from here you can delete this image from SqLite. Follow my blog step by step-
Screen Shot:
1)SQLiteDemoActivity.java
package com.manish.sqlite;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class SQLiteDemoActivity extends Activity {
Button addImage;
ArrayList<Contact> imageArry = new ArrayList<Contact>();
ContactImageAdapter imageAdapter;
private static final int CAMERA_REQUEST = 1;
private static final int PICK_FROM_GALLERY = 2;
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);
/**
* go to next activity for detail image
*/
dataList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
imageName = imageArry.get(position).getImage();
imageId = imageArry.get(position).getID();
Log.d("Before Send:****", imageName + "-" + imageId);
// convert byte to bitmap
ByteArrayInputStream imageStream = new ByteArrayInputStream(
imageName);
theImage = BitmapFactory.decodeStream(imageStream);
Intent intent = new Intent(SQLiteDemoActivity.this,
DisplayImageActivity.class);
intent.putExtra("imagename", theImage);
intent.putExtra("imageid", imageId);
startActivity(intent);
}
});
/**
* open dialog for choose camera/gallery
*/
final String[] option = new String[] { "Take from Camera",
"Select from Gallery" };
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();
}
if (which == 1) {
callGallery();
}
}
});
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();
Log.e("output before conversion", imageInByte.toString());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Android", imageInByte));
Intent i = new Intent(SQLiteDemoActivity.this,
SQLiteDemoActivity.class);
startActivity(i);
finish();
}
break;
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Bitmap yourImage = extras2.getParcelable("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Log.e("output before conversion", imageInByte.toString());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Android", imageInByte));
Intent i = new Intent(SQLiteDemoActivity.this,
SQLiteDemoActivity.class);
startActivity(i);
finish();
}
break;
}
}
/**
* open camera method
*/
public void callCamera() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", 0);
cameraIntent.putExtra("aspectY", 0);
cameraIntent.putExtra("outputX", 200);
cameraIntent.putExtra("outputY", 150);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
/**
* open gallery method
*/
public void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
PICK_FROM_GALLERY);
}
}
2)DataBaseHandler.java
package com.manish.sqlite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
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 = "imagedb";
// Contacts table name
private static final String TABLE_CONTACTS = "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, Update, Delete) 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(2));
// 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;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_IMAGE, contact.getImage());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
package com.manish.sqlite;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
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;
}
}
4)Contact.java
package com.manish.sqlite;
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(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;
}
}
5)DisplayImageActivity.java
package com.manish.sqlite;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class DisplayImageActivity extends Activity {
Button btnDelete;
ImageView imageDetail;
int imageId;
Bitmap theImage;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
btnDelete = (Button) findViewById(R.id.btnDelete);
imageDetail = (ImageView) findViewById(R.id.imageView1);
/**
* getting intent data from search and previous screen
*/
Intent intnt = getIntent();
theImage = (Bitmap) intnt.getParcelableExtra("imagename");
imageId = intnt.getIntExtra("imageid", 20);
Log.d("Image ID:****", String.valueOf(imageId));
imageDetail.setImageBitmap(theImage);
btnDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
/**
* create DatabaseHandler object
*/
DataBaseHandler db = new DataBaseHandler(
DisplayImageActivity.this);
/**
* Deleting records from database
*/
Log.d("Delete Image: ", "Deleting.....");
db.deleteContact(new Contact(imageId));
// /after deleting data go to main page
Intent i = new Intent(DisplayImageActivity.this,
SQLiteDemoActivity.class);
startActivity(i);
finish();
}
});
}
}
6)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="#000000"
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>
7)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="0dp"
android:layout_height="100dp"
android:layout_weight="0.71"
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="#ffffff"
android:layout_marginLeft="7dp" />
</LinearLayout>
8)display.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="#000000"
android:orientation="vertical" >
<Button
android:id="@+id/btnDelete"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:text="Delete Image" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/facebook" />
Your comments and suggestion requested!
Thanks,
You can refer my other blog for database in android-
1)Simple SqLite Data base Demo with Log
2)Image In SqLite Database from Drawable
Happy Coding :)
Android Hub 4 You Team
Hello!! Manish.
ReplyDeleteNice Post.!!!
Can you please share the source code of this.
My id: intel2ndGeneration@gmail.com
Hi Karan!
DeleteThanks for your comment please check your email I have sent you the zip code.
And please support my blog with your joing my site. see below link-
http://www.google.com/friendconnect/signin/home?st=e%3DAOG8GaA%252BW7jvEjfUU1R1uC86Pu12YIOhb%252F9PxfTlb6a4FXs80tnfVA5c%252BwPIlIQhRANY%252FpoE%252FW6qluA0EY3DpQUZNd7G%252B4P15%252Bq2gJA%252B1Pj7zcy02xWu0A7HfI4o0BMgFOb26p9VxxirQM2bwL%252Fww%252BB%252FmJ9OxU8gyFcBExh2UQ7wnyIe94oiDWSekLPn9YakKyIOpm1m5KJKfRfmtN9QX8XrryidcvwvmlafgBxFBnxX8KRo7X4PsO5EraKSk6OJnHzczSUrB1TcFsRroCzQu7QBr8lPqOUJ4VcL5eG792k7Dh33w3UZ8O0%253D%26c%3Dpeoplesense&psinvite=&subscribeOnSignin=1
great work done
ReplyDeletethanks a lot
plz send me zip file
i was tried your source code, but, I have problem in code about
ReplyDeletedb.addContact(new Contact("Android", imageInByte));
and if, I choose "select from gallery "
result is " No Media Found "..
can you give me solution???
Hi Yantisa,
DeleteI think you are using Emulator for testing that's why you are getting "No Media Found"
or your phone have no memory card please check...
I using emulator for testing. so, how to implementation source code with emulator???
ReplyDeleteSorry dear you should use phone instead of emulator well you can my below blog hope it will work for you but I can't guarantee.
Deletehttp://www.androidhub4you.com/2013/02/how-to-use-android-emulator-camera-and.html
okey, thanks your tutorial and information.....
ReplyDeleteThis can easily be adapted to text to-according the Android Developer's Cookbook.
ReplyDeleteThanks Mike..
Deleteu can send me full project
ReplyDeletekiwan38@hotmail.com
thx alot
Hi anas I think every thing clear on my blog so you can copy paste code from above..
DeleteWell I have sent you the zip code please check your email..
Thanks,
send me full project
ReplyDeletetentangmalam@hotmail.com
thanks
Just copy paste from above..
DeleteHi Manish. This is really a great work. Looking forward to more from you.
ReplyDeleteYour most welcome!
Deletesend me full project
ReplyDeleterajnish866@rocketmail.com
thanks
Are you asking or ordering to me?
DeleteWell Everything clear above just copy paste..
Rajnish sent you the code and please be polite with everyone and I am sorry if you feel bad..
DeleteThanks,
Hello Manish,
ReplyDeleteWe're trying to use your code and make it so we can take a picture. We have a program while cropping though. After we crop and click save it fails to take us back to the activity and save the image even though when we click save it says "saving image" yet never saves it. Do you have any idea why this might be? Besides that EXCELLENT tutorial thank you so much : ).
I think this issue because of high density resolution device I am sure you are using samsung gallexy or any other high resolution device..
DeletePlease try to get path of image instead of data please try some thing like below-
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
/**
* Get Path
*/
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
columnIndex = cursor.getColumnIndex(filePathColumn[0]);
/**
*
*/
and after that crop it...
I'm sorry for being ignorant but how do I do this?
DeleteI copied these lines of codes into the code already but not sure what variable columnIndex is or what i should do with it next, thank you for the help once again.
Nardo
Hi Please try above SQLiteDemoActivity.java Activity and comment crop code from above..
Deletepublic void callCamera() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
/*cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", 0);
cameraIntent.putExtra("aspectY", 0);
cameraIntent.putExtra("outputX", 200);
cameraIntent.putExtra("outputY", 150);*/
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
Hope it will help you..
Thanks,
This comment has been removed by the author.
Deleteif I will capture image, after capturing it will display "Unfortunately Camera has stopped."
DeleteHi sir, can I ask what is the solution for this, and If I will click a certain image to display the whole application stops... can I ask what is the solution for that?
thank you sir:)
Have you try latest zip code?
Deletehttps://github.com/manishsri01/SQLiteImageDemo
Hello
ReplyDeletecan u please share Source code........
Email-ID:
vermabca1001@gmail.com
You can copy paste from above.
DeleteI know it is some difficult to copy paste :)
So I am sending you zip code please check your email..
Thanks,
Manish
helo Dheeraj ..
Deletecan you please sand me the zip of this source at (atiqfarooq_satti@yahoo.com)
can you send me code i 'm facing prblm in my ide...
ReplyDeleterayees.rehaman@gmail.com
Sure! please check your email I have sent you the zip code..
DeleteThanks,
thanks manish for your replay
ReplyDeletehelo rayees ..
Deletecan you please sand me the zip of this source at (atiqfarooq_satti@yahoo.com)
Hi Manish,
ReplyDeleteThank's for sharing me such a nice post. can you email to me this zip code my email address is (atiqfarooq_satti@yahoo.com)
Check your email Please I have sent you the zip code..
DeleteAnd I like your way to ask code from rayees also..
I am sorry friend but every time i am not available so when
I got time sure I will reply...
Thanks,
Thanks Manish,
DeleteLet me check the code. if i face any kind of problem in it. i will let you know ASAP.
Thanks
Atiq
Sure! And your most welcome..
DeleteManish dear i am receiving the error message when i run the app in my mobile(unfortunately Camera SQlite has stopped ) can u please tell me what should i do now ??
DeleteHave you make any change in my code?
DeleteLet me know your log cat please..
i have sanding you email of my log cat please consider that let me know how i fix that .
DeleteI think you are using Samsung S3 for testing so please change SQLiteDemoActivity class with new one I have sent you the file please check your email...
DeleteThanks,
You are right its got crash on some devices..
DeleteGive me some time please I will fix it then send you new code..
Thanks,
ok dude .. um waiting ...
Deletehelo manish ..
Deletehave you fixed the app ?? kindly tell me please ??
Yes Atiq please check your email I have sent you the file please replace it with new one..
DeleteHi Manish,
ReplyDeleteThis is a great post. Instead of sending it in email to everyone who is asking to look at the source code, is it possible for you to upload it to github? I am sure u would have heard about it. Ppl create widgets/apps and share their code there , so others can see or download and play with it.
If u can email the code to orangewordpress@gmail.com or upload it to github and let us all know the link, it would be very helpful. Thanks.
You are right dear but problem is this when I upload the code no one comment on by blog.
DeleteSo for fame of my blog I don't want provide zip code on git hub..
After 100 comment I will add it..
Thanks for your suggestion..
And sending you the zip code..
Thanks,
I agree. Your blog is very informative.
DeleteHi Manish,
ReplyDeleteThanks for giving this type tutorials. It will help to beginners very much.
could you please send me the zip file to mail id : srinivas2009mca@gmail.com
waiting for your code.
Thanks
Yes sure please I am sending you zip code..
DeleteThanks,
Hi,
ReplyDeleteThe app throws error, after picking the image. I am running it on samsung galaxy S2. I have emailed you the logcat error. Can you please fix this and let me know.
Thanks Manish for fixing the pblm.. U r a true android enthusiast. thumbs up!! for you and your blog
ReplyDeleteThanks man!
DeleteI think you need to add another constructor to your Contact.java file. I was getting an error in the IDE for the lines
ReplyDeletedb.addContact(new Contact("Android", imageInByte));
in onActivityResult
I also had to remove
android:text="@string/hello"
from the TextView in screen_list.xml.
Is android:src="@drawable/facebook" required in the ImageView in display.xml? Does that start out as a dummy file when the program is installed? What type of file should it be (jpg, pgn, bmp) or does it matter?
This is a great lesson by the way. Answered a lot of my questions. Thanks
Hi Tim!
DeleteIf you have fixed your code then very good otherwise let me know your email-id i will sent you new updated code.
1)yes a constructor needed here
2)android:text="@string/hello" it is no matter textView will uodated dynamic data so no one hello display.
3)android:src="@drawable/facebook" yes it is an image(jpg,png,bmp) may be any type in your drawable.
Thanks for your valuable comment!
Hey Manish
ReplyDeleteI added the constructor and removed the two lines I commented on and it's working great. No need to send me the code but thanks for offering.
Hey Manish ,Can you get me the source code?
ReplyDeleteplease copy paste from above not much confusing!
DeleteHi Manish
ReplyDeletecan u please share Source code........
id:parigill77@gmail.com
hey manish, if I want to save images and text what should I change?
ReplyDeleteI am using both in my demo just change hard coded to dynamic one..
DeleteHi manish i need ur help in i am going to capture images and display all images into list can you write code and send to babugouda.b@gmail.com i am getting struct
ReplyDeleteMy post doing same thing.. you should use database for that...
DeleteHi Manish can you send the zip code to Kadekdatainfo@gmail.com i try to copy the sourcode and err in db.addContact(new Contact("Android", imageInByte)); thx's a lot
ReplyDeleteHi Manis .. please send me the zip code of this project.. thanks in advance .. my email address is talalqaboos@gmail.com
ReplyDeletePlease check your email sent you the code. And plz sent it to agus too..above ur comment plz.....
DeleteHi Manish,
ReplyDeletesorry for disturbing, i have the error regarding the constructor too. can you send me the source code? so that i can fix the error. my email is kenzleong1989@gmail.com thanks.
sorry for inconvenience.
Please download it from GIT server-
Deletehttps://github.com/manishsri01/SQLiteImageDemo
Hello!! Manish.
ReplyDeleteNice Post.!!!
Can you please share the source code of this.
My id: mallikarjuna234@gmail.com
Please download it from GIT server-
Deletehttps://github.com/manishsri01/SQLiteImageDemo
Hi all!
ReplyDeleteI have put my code on GIT Server, you can download it from download link on my blog..
https://github.com/manishsri01/SQLiteImageDemo
Thanks,
greetings manish, im really new on this andoir proggraming (take it literally since im really zero on this), i have some task like simple save item which is include name, story and image where there is browse button to pick which image should be pick, so on the form there is 2 button (save and browse) and 2 text box (for name and for browse path).
ReplyDeletedo you think you can help me to get what i mean ?
thank you before.
Copy paste my this article and remove camera button and code from here and put 2 editbox here for your title and history..
DeleteI am using hard coded value for text so you can change it dynamically..
Hope this blog help you, please do some R&D and try to did some simple demo first..
well actually im refering to this section..
Deletehttp://www.androidhub4you.com/2012/09/hello-friends-today-i-am-going-to-share.html
my problem is :
1. whenever i re-run the application, the data add by one, so..re-run 4 times = 4 same data insert and 4 same data on list, how to stop that ?
2. is there a way where i can input from a button where i can browse the image then save it to database ?
i would really appreciate if i can talk live via other site like fb or such, my apologize for my rush due to my deadline.
thank you for the answer beforehand.
Please try this code ones-
Deletehttp://www.androidhub4you.com/2013/04/sqlite-example-in-android-add-image.html?
1)Hear two button for camera and gallery, use gallery button it will offer you choose image from gallery..
2)you can remove camera button from your UI if you don't want.
3)Here I am adding hard coded text "Android" you can use textView for input.
4)And I think it is same what you want, just try to understand flow of code..
You can drop me email at- manishsri01@gmail.com and if needed you can talk over gtalk..
Thanks,
hie,if i want to save the image in MySQL database then what changes that i need to do
ReplyDeleteThanks
You should use web services...
DeleteThis comment has been removed by the author.
ReplyDeleteThis is great post. Can you sent me this code, I try copy and paste it but when I click button add image and choosen picture it didn't load into listview.
ReplyDeleteThanks
My id: nttuancntt4@gmail.com
Please check your email I have sent you the zip code..
Deletehello Manish Srivastava..
ReplyDeletethis is vary nice post and it's helpful to me.
i got error in this code
i try to solve error but couldn't solve it..
in the java file SQLiteDemoActivity.java i got error
db.addContact(new Contact("Android", imageInByte));
so please help me out..
shaikh.azhar411@gmail.com
Please check your email I have sent you the zip code. Hope it will help you..
DeleteHi Manish.
Deletethank for your Kindly help..
using yours code i solve my problem.
its really helpful to me..
good day!Please send your code fedormoore@gmail.com
ReplyDeletethank you!
Please check your email I have sent you the zip code...
DeleteHello.
ReplyDeleteCan you sent me this code, I try copy and paste it but when I click button add image and choosen picture it didn't load into listview.
Thanks!!
My id: cesar_211287@gmail.com
Please see my post there a updated download link for download zip code from git-server.
DeleteThanks,
Manish
Hi manish...i am sathish..i am new to android...when i am using ur project i get following error . but i save image from drwable..pls help me to fix it...
ReplyDeleteSkImageDecoder::Factory returned null
Gallery and Camera both are not working? Please check ones any other device..
ReplyDeleteactually i am not getting image from camera friend...i saved image sqlite as byte array..and i show image in listview with one text by by using custom adapter ..
ReplyDeleteTo insert image to sqlite i use following code
ReplyDeleteBitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.smile);
ByteArrayOutputStream stream = new ByteArrayOutputStream(bmp.getWidth() * bmp.getHeight());
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
db.execSQL("INSERT INTO " + TABLE_CONTACTS + "(name,image)"
+ " VALUES('SA',\"" +byteArray + "\");");
To retrive:
byte[] outImage = picture._image;
Bitmap bmp = BitmapFactory
.decodeByteArray(outImage, 0, outImage.length);
Log cat :
09-23 13:30:13.737: D/Result:(23769): ID:1 Name: SA ,Image: [B@43e45660
09-23 13:30:13.957: D/skia(23769): --- SkImageDecoder::Factory returned null
You are trying my zip demo? attach in my blog or any modification?
Deleteyes ...instead of getting image form gallery or a camera directly i just insert image from drawable friend...
DeleteHi Satish,
DeletePlease try my this article it will help you, and it is same what you want.
http://www.androidhub4you.com/2012/09/hello-friends-today-i-am-going-to-share.html
Hello dear Manish!please tell me when the picture is saved in the database, it is very small and almost useless, I tried to disconnect options cameraIntent.putExtra ("crop", "true"); cameraIntent.putExtra ("aspectX", 0); cameraIntent.putExtra ("aspectY", 0); cameraIntent.putExtra ("outputX", 200); cameraIntent.putExtra ("outputY", 150);but they are not what does not help, can you help in this matter?
ReplyDeleteHello Dear!
ReplyDeleteintent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
Above lines use for crop image before save in database. so if you remove that it will directly save image into database without cropping.
May be you got crash because of high resolution image but it should work for camera or gallery. Please test and let me know if any problem do you have..
camera image get width 153 height 204, I tried to insert the code here the following line yourImage = Bitmap.createScaledBitmap (yourImage, 510, 610, true) but the image quality can be seen that it is simply extended to these sizes.Thank you for your answers and help
ReplyDeleteHi Dear,
DeleteI think you are doing good, actually when we crop any image its quality got blur. I have tried many but no luck..
and above line only used for convert image into byte for save into database-
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
Here 100 means 100% quality of compression of image at the time of storing itno database.
i have also add text note with each image like that image and it description and image taken from same as gallery or camara?????? give me please solution
ReplyDeleteSo what issue you are getting?
DeleteThis comment has been removed by the author.
Deletei want to take image from gellary or sd card and take some text with it...and save to the database... and retrive to those things to list view as like Note. i hope now you getting some little idea about that...!!!
DeleteYes I got now what you want. Just do one thing where I add hard-coded string like-"android" just create a edittext and take input from user on first screen.like-
DeleteEditText
id="+id/editext
width=wrap
height=wrap
and then in your activity-
String value=editText.getText.toString();
And pass this value into your databse like that-
db.addContact(new Contact(value, imageInByte));
Hope it will work for you.
Thanks!
hi Manish !
ReplyDeletereally this is what i need i have been searching for week to do this and finally found it in your blog T_T !!
can you please send me the project as a zip to my email ?? please ???
my email is : lamlom_92@hotmail.com
thanks alot !!
please check post again, a download link there...
Deletei just copied the code and it works fine thank you ..
Deletebut what i want is a little diffrent ..
i want to add a picture then store it to the database then view it in a listview in another activity page
you did it in one xml and i want to do it in seprate xmls .. it wont be hard to do that right ?? x_x
hmmm so just put camera and gallery button in other xml.
Deletecan i ask another question ..
Deletecan i put 3 imageviews in one item in the listview and each picture is a diffrent picture from database
can i ??
hmmm sure you can.
DeleteJust create your table like that-
name ,image1, image2 ,image3 in same row.
and save 3 images in one row.. now you can easily display that item in singel row. Just modify your custom-adapter and row.xml layout.
Hi Manish..nice post and very helpful to me as a beginner..actually I have already copy and paste your source code but it does not work...So, Can you please send the zip file of your source code to me...
Deleteazwardy1990@gmail.com
Thanks... =)
if i want to do the same thing but on grid view ..
Deleteits the same right ? i just switch between list view and grid view right ?
sorry i know i bothered you x_x
but im new to android development and my application should be submited on thu !!
so im little nervouse x_x
@az wardy- why you are trying to copy paste? here a download link on my post just download it from git-server.
Deletehttps://github.com/manishsri01/CameraGallerySqliteDemo
@lama chan- please don't fell nervous. everything achievable and i am sure you can. and yes you can convert it into gridview. use same custom-adapter and place of listview put gridview and other things is same. for gridview demo you can refer my this blog-
Deletehttp://www.androidhub4you.com/2013/07/custom-grid-view-example-in-android.html
thank you so much !
DeleteI did it but it didn't work :'(
does I change a lot of things ?
I should do the steps on the other tutorial ? >> I didn't so maybe this is the problem ?
@lama I don't think you have make a lot of changes. just change that listview into gridview and i think other thing is same. actually you need some practice on android so please try both demo and after that try to merge both in one project.
DeleteThis comment has been removed by the author.
ReplyDeleteDear i am sorry but we can't did your whole project on blog just we can guide you. you can post your question on stack overflow. if it is your company project ask to your company hire me for that task, because it will take some time to fix it and we can't pour our whole time on post. without seeing your whole code we can't help you.
Deleteoh ok im sorry I will delete the code..
ReplyDeleteno its not .. im a student and this is my software course project
thanks a lot and sorry for bothering you .. :)
not bothering at all. please don't remove post, i think we always try to response everyone how much possible. so please don't feel angry.
Deletehello Manish Srivastava..
ReplyDeletethis is vary nice post and it's helpful to me.
i got error in this code
i try to solve error but couldn't solve it..
in the java file SQLiteDemoActivity.java i got error
db.addContact(new Contact("Android", imageInByte));
so please help me out..
nguyennam050192@gmail.com
have you dowonload code from git-server? i think it should work, have make any changes in that file?
DeleteHi! I'm using your example (I've downloaded it from GitHub) on my Samsung Galaxy Nexus and, when I take a photo, the app crashes! Can you help me, please? :)
ReplyDeleteYou are right Matteo, its happen on some devices. And yet i did not got any correct solution. I have tried many type of code but yet i am looking for best. If you got anything please post here so we can solve our problem.
DeleteThanks!
Hello!! Manish.
ReplyDeleteNice Post.!!!
Can you please share the source code of this.
My id: azure_93nmn@yahoo.com
A download link on my post please download from there.
Deletehi, can u send me ur zip file as i have problem at db.addContact(new Contact("Android", imageInByte));
ReplyDeleteThks
It should work! anyway give your email-id please..
DeleteHi Manish
ReplyDeletehow to pick image and name from gallery in listview
pls helpe me
just call this method for getting image from gallery-
Deletepublic void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
PICK_FROM_GALLERY);
}
And on you On onActivityResult just do like this-
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
/**
* Get Path
*/
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath1 = cursor.getString(columnIndex);
Log.e("Image View Path1", picturePath1);
}
cursor.close();
}
hi manish can you send me the full file zip? or i can download it?
ReplyDeletePlease check on my post there a download link for zip code.
Deletehi manish can you add some code for saving multiple images? thank you in advance..
ReplyDeletefor example you want to save up to 5 photos.
In case of choose of camera and gallery you can save only one image at one time.
DeleteFor multi image you can put them into your drawable or you can get using path from sd-card and insert them into sqlite.
Hi manish! Can you help me how can I save an images have a big resolution.for example 1200 X 800 and don't need to crop before you save..
Deletethank you in advance..
Create an app folder into your sd card and refrence of that image in your sqlite. And get data from there where you needed..
DeleteNice job Manish....App is running fine but wen I open the Image there is a force close "Unfortunately Closed" Please help me to fix it
ReplyDeletecan you share log-cat please?
DeleteHi Manish,Now I got my problem solved.Actually the problem was I did not declare the classes in AndriodManifest.xml. Thank You
DeleteHi Manish,Can u Please give me the code for showing images in grid View from database where the database is used to store images in another app
DeleteHow can you use another app database is it possible? well for gridview you can check this demo-
Deletehttp://www.androidhub4you.com/2013/07/custom-grid-view-example-in-android.html
Thank You.....And by the way the Images are storing in camera folder itself....Is it possible to store the images in separate folder in gallery(the fotos which we take thru our app).
DeleteHow to add xtra field in database???
Deletextra field means? You want some more column in your database? so just add others field like i have did for 2 column.
DeleteI can Add only 10 images.Can u plz tell me How to store more than tat?
Deletehey really very helpfull tutorial......... i have to add voice memo with perticular image what to do i m confused so if possible then pleaz send me code my email id is ankitapatel26091991@gmail.com thank you!
ReplyDeleteHi Ankita, i don't have any code but I can give you small suggestion may be it will help you.
Delete1)Create an app folder into you phone or sd-card.
2)And save your voice clip inside that folder.
3)Save reference of this voice memo into your sd-card.
4)Get data from your sqlite and display in your application and voice from your sd-card.
i got an error please send me the zip code
ReplyDeletesaikatuoda@gmail.com
Hi, which type of error you are getting? in importing project? so just create new project from exciting code.
Deletewhen i capture a photo and check right sight to add photo
Deletethen the camera is stopped
Thanks for sharing this android example! Love it! Keep it up!
ReplyDeleteHi Manish, after download zip from this link https://github.com/manishsri01/CameraGallerySqliteDemo/tree/master/CameraSQLiteDemo i tried your code and got an error. After capture a photo from camera the app stopped and display "Unfortunately Gallery has stopped.". Help me please brother. ;-)
ReplyDeleteits just because of data==null, its happen in some devices.You can do one thing-
Deletecreate an app folder and save your image in your sd-card and that path in your sqlite. and get image from there using URI.
Hi, great tutorial! Can you please give me advice on how to do that with a mysql database?
ReplyDeleteThanks,
You can use web-services.
DeleteI am unable to download the complete project
ReplyDeleteplease provide the complete source cocde
i got the file but when i m capturing image from camera it is shoeing stopped
ReplyDeletei have added camera permissions bt it is not working
hi manish, can i ask, when i run this app and taking picture with camera, the picture isn't show in the listview, can u help me?, i already download ur code, and copy it in my program. Thank Before
ReplyDeleteHi Manish your tutorial its very helpfull but i-m desesperated i cannot make it works when I took the picture form the camera it always Crashes and cant find any solution :( could you help me?
ReplyDeleteHi Manish, I have seen your tutorial and compiled your code, But I am receiving the following error
ReplyDelete[2014-05-08 12:57:01 - Emulator] invalid command-line parameter: http-proxy=http://10.1.8.30:8080.
[2014-05-08 12:57:01 - Emulator] Hint: use '@foo' to launch a virtual device named 'foo'.
[2014-05-08 12:57:01 - Emulator] please use -help for more information
Can you help me to solve the problem?
[Note: I ma using ADT bundle for my application development]
Using Emulator for testing? If yes i am not sure it will work on emulator if you don't have camera and gallery functionality on your emulator. You can try on real device.
DeleteHi, Thanks for your response... I tried ur code by increasing SDcard size and TARGET SDK (in creating new emulator) and I found that the above code is Sucessfully compiled.... It Compiled in Emulator itself.....
ReplyDeleteThank You....
hii ,after selecting image it again comes back on the frame where add image button is there,no option of cropping and no list view appears, plz help!! need it urgently
ReplyDeletehi manish i have downloaded your code but if i am removing crop in the call gallery method....i am getting null pointer exception..that is it is going to gallery and once image is selected it is unfortunately close...but if i using crop there is no problem why this is show??? from log cat it is saying that runtime exception and null pointer exception on bytestream..please help me out...need it very urgently...
ReplyDeletehey manish, could you give me all of source code. i mean this project. :)
ReplyDeleteplease send to (putra_rolli@yahoo.com)
thanks a lot manish :)
sir,Thanxx for your post. Can you send me the source code..??
ReplyDeleteswapnil18_1991@yahoo.in
App is not working when taking image from Camera. when I use putExtra(MediaStore.EXTRA_OUTPUT,fileUri) , then onActivityResult Intent data is null .And Bundle extras is also null . Can u please send me ZIP code at, anu19860@gmail.com
ReplyDeleteHi manish i was searching for this from last 1 week but i got error when i copy pasted the code i m using galaxy note can u plz mail the zip file of code...my id is vijaynareshpareek@gmail.com thanking u in advnc
ReplyDeleteHello. I ve sent a mail from dk. Will u please check the mail and reply. Thank u.
ReplyDeleteAnybody help me. My app is not working it stops after taking a picture and after choosing a pic from gallery. I really need this app to work urgently. I use samsung s4 and android studio. HELP my mail. sahimlida@yahoo.dk
ReplyDeleteHello i need the code too imranazmar@gmail.com
ReplyDeleteHello sir,, Thnk you so much but when i am running this code, Unfortunately Its stopped... PLO Modify it when we are clicking an image via WebCam
ReplyDeleteOn clicking camera , when i am going to save it, is Unfortunately Stopped bro.. plz remove this or tell me solution..
ReplyDeleteI hope it is just because of your data is null in your onActivityResult method so kindly check any code for this issue. you can try below code hope it will help you-
Deletehttp://www.androidhub4you.com/2014/09/android-camera-onactivityresult-intent.html
ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage); error is in this line brother... How to solve this.. ? Plz update this module once again sir...
ReplyDeletewhich type of error you are getting?
Deletewhy cursor.getBlob(1) i think that it is cursor.getBlob(2)
ReplyDeleteYes right, thanks for the suggestion, I just edited it.
Deletehi will you please send me complete code to my email id ?? pithadiya.nayan@hotmail.com
ReplyDeletedownload from below url-
Deletehttps://github.com/manishsri01/CameraGallerySqliteDemo
Hey sir,
ReplyDeletei downloaded the code and am running it on my android studio and then on my phone.
but whenever i try to take a picture from the camera it goes to camera -> takes picture and as i select the image the app crashes.
but if i use the gallery option everything works fine.
Please help
Thank this solved it :D
Deletepublic void callCamera() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
/*cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", 0);
cameraIntent.putExtra("aspectY", 0);
cameraIntent.putExtra("outputX", 200);
cameraIntent.putExtra("outputY", 150);*/
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
Great work :)
db.addContact(new Contact("Android", imageInByte));
ReplyDeleteHaving error: Constructor cannot be resolved!!!! ?????
Modify your input like(keyid, name,imageInByte) or add one more constructor-
Delete// constructor
public Contact(String name, byte[] image) {
this._name = name;
this._image = image;
}
I have implemented the above code. But the images are not getting showed up in the listView. Rest Everything seems good. When I select an image from the gallery, my listView still remains empty. What could be the problem?
ReplyDeleteI have implemented the above code. But the images are not getting showed up in the listView. Rest Everything seems good. When I select an image from the gallery, my listView still remains empty. What could be the problem?
ReplyDeleteUrgent!
Can you debug your app? please check your onActivityResult data must not be null. And how about camera?
Deleteyou can check below URL hope it will help you-
http://www.androidhub4you.com/2014/09/android-camera-onactivityresult-intent.html
Both camera and gallery images are not showing up in listview.
DeleteCan you try to debug and see what is the issue? or use any other phone for testing if you can arrange and see it is working or not?
DeleteSame problem on other phones. The dialogue box is openening fine, The Gallery an Camera opens fine, The App does not crash. But the ListView remains empty. How do I debug!
DeleteUse debug point, Google for how to use debugger in android. I hope your data is null and you need to modify your code.
DeleteAlso, Where is the URI of the images being used?
ReplyDeleteURI? we are storing image in sqlite database in byte array.
Deletethank you for this tutorial.
ReplyDeletecan you please guide me how to make the pictures taken from camera to the gridview.
one suggestion : please make vedio tutorial. it will be easy for us to understand
thanks anyway
Manish , i got this error when i'm trrying this code. "super camera and gallery has stopped" .. why?
ReplyDeleteok problem solved by comment this code , but for gallery still prbblem
Deletepublic void callCamera() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
/*cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", 0);
cameraIntent.putExtra("aspectY", 0);
cameraIntent.putExtra("outputX", 200);
cameraIntent.putExtra("outputY", 150);*/
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
Sir.
ReplyDeletewhen i take image from gallary it works fine,but
when i capture image from camera then after clicking ok symbol it shows "GAllary unfortunately stop" error.
plz help me solve this problem.i m using "micromax unite 2.kitkat 4.2 OS"
if possible reply me on my mail abhosale07@gmail.com
Try this link-
Deletehttp://www.androidhub4you.com/2014/09/android-camera-onactivityresult-intent.html
I am trying to use this code, but i dont know how to do it :/, i want to do like profile of whatsapp, change image profile but this code is Array, I Get Mixed up xd.., can somebody help me ?
ReplyDeleteSir can u send this code to my account
ReplyDeletesamreenimtiaz6@gmail.com
I like example with database mysql .
ReplyDelete