read and save images into SQLite database - android

hey guys i am working on android to retrieve and save images from a SQLite database . here is my code ==>>
public class MainActivity extends Activity implements OnClickListener {
protected static TextView textView;
protected static ImageView image1, image2;
protected Button get_image, save_image, read_image;
private String selectedImagePath;
private static final int SELECT_PICTURE = 1;
String DB_NAME = Environment.getExternalStorageDirectory() + "/test.db";
String TABLE_NAME = "mytable";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image1 = (ImageView) findViewById(R.id.imageView1);
image2 = (ImageView) findViewById(R.id.imageView2);
textView = (TextView) findViewById(R.id.textView1);
get_image = (Button) findViewById(R.id.get_image);
get_image.setOnClickListener(this);
save_image = (Button) findViewById(R.id.save_image);
save_image.setOnClickListener(this);
read_image = (Button) findViewById(R.id.read_image);
read_image.setOnClickListener(this);
}
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.get_image:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
SELECT_PICTURE);
break;
case R.id.save_image:
createTable();
saveInDB();
break;
case R.id.read_image:
readFromDB();
break;
default:
break;
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
image1.setVisibility(View.VISIBLE);
image1.setImageURI(selectedImageUri);
}
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
void createTable() {
SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,
Context.MODE_PRIVATE, null);
String MySQL = "create table if not exists "
+ TABLE_NAME
+ " (_id INTEGER primary key autoincrement, name TEXT not null, image BLOB);";
myDb.execSQL(MySQL);
myDb.close();
}
void saveInDB() {
SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,
Context.MODE_PRIVATE, null);
byte[] byteImage1 = null;
String s = myDb.getPath();
myDb.execSQL("delete from " + TABLE_NAME); // clearing the table
ContentValues newValues = new ContentValues();
String name = "CoderzHeaven";
newValues.put("name", name);
try {
FileInputStream instream = new FileInputStream(selectedImagePath);
BufferedInputStream bif = new BufferedInputStream(instream);
byteImage1 = new byte[bif.available()];
bif.read(byteImage1);
newValues.put("image", byteImage1);
long ret = myDb.insert(TABLE_NAME, null, newValues);
if (ret < 0)
textView.append("Error");
} catch (IOException e) {
textView.append("Error Exception : " + e.getMessage());
}
myDb.close();
textView.append("\n Saving Details \n Name : " + name);
textView.append("\n Image Size : " + byteImage1.length + " KB");
textView.append("\n Saved in DB : " + s + "\n");
Toast.makeText(this.getBaseContext(),
"Image Saved in DB successfully.", Toast.LENGTH_SHORT).show();
}
void readFromDB() {
byte[] byteImage2 = null;
SQLiteDatabase myDb;
myDb = openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
Cursor cur = myDb.query(TABLE_NAME, null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false) {
textView.append("\n Reading Details \n Name : " + cur.getString(1));
cur.moveToNext();
}
// /////Read data from blob field////////////////////
cur.moveToFirst();
byteImage2 = cur.getBlob(cur.getColumnIndex("image"));
setImage(byteImage2);
cur.close();
myDb.close();
Toast.makeText(this.getBaseContext(),
"Image read from DB successfully.", Toast.LENGTH_SHORT).show();
Toast.makeText(this.getBaseContext(),
"If your image is big, please scrolldown to see the result.",
Toast.LENGTH_SHORT).show();
}
void setImage(byte[] byteImage2) {
image2.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0,
byteImage2.length));
textView.append("\n Image Size : " + byteImage2.length + " KB");
}
}
The problem i am facing is that when ever i am trying to execute the above code i am not able to retrieve or save the image from/into the sqlite database. i am able to fetch the images from gallery. i am stuck, please help me.
thank you :)

I have changed only DB Store location.. it works.
Try this...
SQLiteDatabase myDB = MainActivity.this.openOrCreateDatabase("test.db",//your db file name
MainActivity.this.MODE_PRIVATE, null);

Related

How to programmatically link a contact number?

I want to develop contact application with basic CRUD operations with Contacts, and Mostly Link Contact Numbers using Android.
Try this it works for me :
public class MyActivity extends Activity {
private static final String TAG = MyActivity.class.getSimpleName();
private static final int REQUEST_CODE_PICK_CONTACTS = 1;
private Uri uriContact;
private String contactID; // contacts unique ID
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClickSelectContact(View btnSelectContact) {
// using native contacts selection
// Intent.ACTION_PICK = Pick an item from the data, returning what was selected.
startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), REQUEST_CODE_PICK_CONTACTS);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PICK_CONTACTS && resultCode == RESULT_OK) {
Log.d(TAG, "Response: " + data.toString());
uriContact = data.getData();
retrieveContactName();
retrieveContactNumber();
retrieveContactPhoto();
}
}
private void retrieveContactPhoto() {
Bitmap photo = null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
ImageView imageView = (ImageView) findViewById(R.id.img_contact);
imageView.setImageBitmap(photo);
}
assert inputStream != null;
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void retrieveContactNumber() {
String contactNumber = null;
// getting contacts ID
Cursor cursorID = getContentResolver().query(uriContact,
new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
Log.d(TAG, "Contact ID: " + contactID);
// Using the contact ID now we will get contact phone number
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactID},
null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
Log.d(TAG, "Contact Phone Number: " + contactNumber);
}
private void retrieveContactName() {
String contactName = null;
// querying contact data store
Cursor cursor = getContentResolver().query(uriContact, null, null, null, null);
if (cursor.moveToFirst()) {
// DISPLAY_NAME = The display name for the contact.
// HAS_PHONE_NUMBER = An indicator of whether this contact has at least one phone number.
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursor.close();
Log.d(TAG, "Contact Name: " + contactName);
}
}
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select a Contact"
android:onClick="onClickSelectContact" />
<ImageView android:id="#+id/img_contact"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:adjustViewBounds="true"
android:contentDescription="Contacts Image"
/>
and add this to menifest file :
<uses-permission android:name="android.permission.READ_CONTACTS" />

Taking a camera picture and saving the path to a database, then using it to populate an ImageView

I am trying to take a snapshot with the camera, grab the path of the returned bitmap, then use that link to populate an ImageView. Everything seems to be working except that the ImageView is blank when I run the emulator. Here are some of the code snippets I have so far.
Here is my database code:
//constants for notes table
public static final String NOTES_TABLE = "note";
public static final String NOTES_ID = "noteId";
public static final String ACTUAL_NOTE = "theNotes";
public static final String IMAGE_PATH = "imagePath";
//Create notes table
public static final String CREATE_NOTES_TABLE = "CREATE TABLE "
+ NOTES_TABLE + " (" + NOTES_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ ACTUAL_NOTE + " TEXT, " + COURSE_ID + " INTEGER, "
+ IMAGE_PATH + " TEXT" + ")";
This is the code to take a photo:
private void takePhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(this.getExternalCacheDir(),
String.valueOf(System.currentTimeMillis()) + ".jpg");
Uri fileUri = FileProvider.getUriForFile(NoteViewActivity.this,
BuildConfig.APPLICATION_ID + ".provider",
file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
this.startActivityForResult(intent, RC_TAKE_PHOTO);
}
This it the code that returns the photo data and saves the path to my database
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_TAKE_PHOTO && resultCode == RESULT_OK) {
final long noteNo = (long) getIntent().getExtras().get(EXTRA_NOTENO);
DBOpenHelper helper = new DBOpenHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
Uri fileUri = FileProvider.getUriForFile(NoteViewActivity.this,
BuildConfig.APPLICATION_ID + ".provider",
file);
String pathToImage = fileUri.toString();
ContentValues cv = new ContentValues();
cv.put(DBOpenHelper.IMAGE_PATH, pathToImage);
db.update(DBOpenHelper.NOTES_TABLE, cv, DBOpenHelper.NOTES_ID + "=" + noteNo, null);
db.close();
}
}
Finally this is the code I'm using to populate the ImageView:
//Create a cursor
DBOpenHelper helper = new DBOpenHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.query(DBOpenHelper.NOTES_TABLE, new String[]{
DBOpenHelper.NOTES_ID,
DBOpenHelper.ACTUAL_NOTE,
DBOpenHelper.COURSE_ID,
DBOpenHelper.IMAGE_PATH},
DBOpenHelper.NOTES_ID + " = ?",
new String[]{String.valueOf(noteNo)}, null, null, null);
if (cursor.moveToFirst()) {
//Get all the info to populate TextViews
String actualNote = cursor.getString(1);
if (cursor.getString(3) != null){
String imagePath = cursor.getString(3);
Bitmap myBitmap = BitmapFactory.decodeFile(imagePath);
imageView.setImageBitmap(myBitmap);
}
//Populate first textview
TextView textView1 = (TextView) findViewById(R.id.note_edittext1);
textView1.setText(actualNote);
}
cursor.close();
db.close();
Thank you so much in advance. I've been working on this camera problem for way too long so any help is much appreciated!

how to change selected contact image on button click from imageview.?

in main activity display list of contact. now select any contact and open Detail.java Activity. now i want to set this particular selected contact image from second activity imageview.
mainActivity.java
public class MainActivity extends Activity {
SimpleCursorAdapter mAdapter;
MatrixCursor mMatrixCursor;
Bitmap bitmap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// The contacts from the contacts content provider is stored in this cursor
mMatrixCursor = new MatrixCursor(new String[] { "_id","name","photo","details"} );
// Adapter to set data in the listview
mAdapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.lv_layout,
null,
new String[] { "name","photo","details"},
new int[] { R.id.tv_name,R.id.iv_photo,R.id.tv_details}, 0);
// Getting reference to listview
ListView lstContacts = (ListView) findViewById(R.id.lst_contacts);
// Setting the adapter to listview
lstContacts.setAdapter(mAdapter);
// Creating an AsyncTask object to retrieve and load listview with contacts
ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();
// Starting the AsyncTask process to retrieve and load listview with contacts
listViewContactsLoader.execute();
lstContacts.setOnItemClickListener(new OnItemClickListener()
{
#SuppressWarnings({ "null", "unused" })
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent intent = new Intent(MainActivity.this, detail.class);
// Intent intent = new Intent(Current.this, Next.class);
intent.putExtra("bmp", byteArray); // for image
// intent.putExtra("text", text); //for text
startActivity(intent);
// startActivity(intent);
}
});
}
/** An AsyncTask class to retrieve and load listview with contacts */
private class ListViewContactsLoader extends AsyncTask<Void, Void, Cursor>{
#Override
protected Cursor doInBackground(Void... params) {
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
// Querying the table ContactsContract.Contacts to retrieve all the contacts
Cursor contactsCursor = getContentResolver().query(contactsUri, null, null, null,
ContactsContract.Contacts.DISPLAY_NAME + " ASC ");
if(contactsCursor.moveToFirst()){
do{
long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID"));
Uri dataUri = ContactsContract.Data.CONTENT_URI;
// Querying the table ContactsContract.Data to retrieve individual items like
// home phone, mobile phone, work email etc corresponding to each contact
Cursor dataCursor = getContentResolver().query(dataUri, null,
ContactsContract.Data.CONTACT_ID + "=" + contactId,
null, null);
String displayName="";
String nickName="";
String homePhone="";
String mobilePhone="";
String workPhone="";
String photoPath="" + R.drawable.blank;
byte[] photoByte=null;
String title="";
if(dataCursor.moveToFirst()){
// Getting Display Name
displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));
do{
// Getting NickName
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE))
nickName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
// Getting Phone numbers
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME :
homePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE :
mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK :
workPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
}
}
// Getting Photo
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)){
photoByte = dataCursor.getBlob(dataCursor.getColumnIndex("data15"));
if(photoByte != null) {
bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the contact image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+contactId+".png");
// The FileOutputStream to the temporary file
try {
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Writing the bitmap to the temporary file as png file
bitmap.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
} catch (Exception e) {
e.printStackTrace();
}
photoPath = tmpFile.getPath();
}
}
}while(dataCursor.moveToNext());
String details = "";
// Concatenating various information to single string
if(homePhone != null && !homePhone.equals("") )
details = "HomePhone : " + homePhone + "\n";
if(mobilePhone != null && !mobilePhone.equals("") )
details += "MobilePhone : " + mobilePhone + "\n";
if(workPhone != null && !workPhone.equals("") )
details += "WorkPhone : " + workPhone + "\n";
if(nickName != null && !nickName.equals("") )
details += "NickName : " + nickName + "\n";
if(title != null && !title.equals("") )
details += "Title : " + title + "\n";
// Adding id, display name, path to photo and other details to cursor
mMatrixCursor.addRow(new Object[]{ Long.toString(contactId),displayName,photoPath,details});
}
}while(contactsCursor.moveToNext());
}
return mMatrixCursor;
}
#Override
protected void onPostExecute(Cursor result) {
// Setting the cursor containing contacts to listview
mAdapter.swapCursor(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Detail.java
public class detail extends Activity{
protected static final int CAPTURE_NEW_PICTURE = 1;
ImageView photo1;
Button camera, galary,save;
Uri selectedImageUri;
String selectedPath;
Bitmap photo;
private static final int CAMERA_REQUEST = 1888;
public static final String MIMETYPE_FORMALITY = "vnd.android.cursor.item/useformality";
public static final int MEDIA_TYPE_IMAGE = 1;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_list);
photo1=(ImageView)findViewById(R.id.photo);
camera=(Button)findViewById(R.id.camera);
galary=(Button)findViewById(R.id.galary);
save=(Button)findViewById(R.id.save);
//camera picture
camera.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
//gallery picture
galary.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
});
save.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
Context context= getApplicationContext();
Bitmap icon= BitmapFactory.decodeResource(context.getResources(), R.id.photo);
try
{
Intent myIntent = new Intent();
myIntent.setAction(Intent.ACTION_ATTACH_DATA);
myIntent.setType("image/jpeg");
myIntent.putExtra(Intent.EXTRA_STREAM, icon);
startActivity(myIntent);
}
catch (ActivityNotFoundException e)
{
e.printStackTrace();
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
photo1.setImageBitmap(photo);
}
else
{
if (data != null && resultCode == RESULT_OK)
{
Uri selectedImage = data.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);
cursor.close();
if(photo != null && !photo.isRecycled())
{
photo = null;
}
photo = BitmapFactory.decodeFile(filePath);
photo1.setBackgroundResource(0);
photo1.setImageBitmap(photo);
}
else
{
Log.d("Status:", "Photopicker canceled");
}
}
}
}
try this code...it will perfectly work...
here is your java class
public class demo extends Activity
{
SimpleCursorAdapter mAdapter;
MatrixCursor mMatrixCursor;
Bitmap bitmap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// The contacts from the contacts content provider is stored in this cursor
mMatrixCursor = new MatrixCursor(new String[] { "_id","name","photo","details"} );
// Adapter to set data in the listview
mAdapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.second,
null,
new String[] { "name","photo","details"},
new int[] { R.id.textView1,R.id.imageView1,R.id.textView2}, 0);
// Getting reference to listview
ListView lstContacts = (ListView) findViewById(R.id.listView1);
// Setting the adapter to listview
lstContacts.setAdapter(mAdapter);
// Creating an AsyncTask object to retrieve and load listview with contacts
ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();
// Starting the AsyncTask process to retrieve and load listview with contacts
listViewContactsLoader.execute();
lstContacts.setOnItemClickListener(new OnItemClickListener()
{
#SuppressWarnings({ "null", "unused" })
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent intent = new Intent(demo.this, secondactivity.class);
// Intent intent = new Intent(Current.this, Next.class);
intent.putExtra("bmp", byteArray); // for image
// intent.putExtra("text", text); //for text
startActivity(intent);
// startActivity(intent);
}
});
}
/** An AsyncTask class to retrieve and load listview with contacts */
private class ListViewContactsLoader extends AsyncTask<Void, Void, Cursor>{
#Override
protected Cursor doInBackground(Void... params) {
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
// Querying the table ContactsContract.Contacts to retrieve all the contacts
Cursor contactsCursor = getContentResolver().query(contactsUri, null, null, null,
ContactsContract.Contacts.DISPLAY_NAME + " ASC ");
if(contactsCursor.moveToFirst()){
do{
long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID"));
Uri dataUri = ContactsContract.Data.CONTENT_URI;
// Querying the table ContactsContract.Data to retrieve individual items like
// home phone, mobile phone, work email etc corresponding to each contact
Cursor dataCursor = getContentResolver().query(dataUri, null,
ContactsContract.Data.CONTACT_ID + "=" + contactId,
null, null);
String displayName="";
String nickName="";
String homePhone="";
String mobilePhone="";
String workPhone="";
String photoPath="" + R.drawable.ic_launcher;
byte[] photoByte=null;
String title="";
if(dataCursor.moveToFirst()){
// Getting Display Name
displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));
do{
// Getting NickName
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE))
nickName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
// Getting Phone numbers
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME :
homePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE :
mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK :
workPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
}
}
// Getting Photo
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)){
photoByte = dataCursor.getBlob(dataCursor.getColumnIndex("data15"));
if(photoByte != null) {
bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the contact image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+contactId+".png");
// The FileOutputStream to the temporary file
try {
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Writing the bitmap to the temporary file as png file
bitmap.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
} catch (Exception e) {
e.printStackTrace();
}
photoPath = tmpFile.getPath();
}
}
}while(dataCursor.moveToNext());
String details = "";
// Concatenating various information to single string
if(homePhone != null && !homePhone.equals("") )
details = "HomePhone : " + homePhone + "\n";
if(mobilePhone != null && !mobilePhone.equals("") )
details += "MobilePhone : " + mobilePhone + "\n";
if(workPhone != null && !workPhone.equals("") )
details += "WorkPhone : " + workPhone + "\n";
if(nickName != null && !nickName.equals("") )
details += "NickName : " + nickName + "\n";
if(title != null && !title.equals("") )
details += "Title : " + title + "\n";
// Adding id, display name, path to photo and other details to cursor
mMatrixCursor.addRow(new Object[]{ Long.toString(contactId),displayName,photoPath,details});
}
}while(contactsCursor.moveToNext());
}
return mMatrixCursor;
}
#Override
protected void onPostExecute(Cursor result) {
// Setting the cursor containing contacts to listview
mAdapter.swapCursor(result);
}
}
}
here is your listview layout
listview.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
here is your items layout,just change it with your name
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
and put this permission in your maniefest file.
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
here is second class
public class secondactivity extends Activity {
protected static final int CAPTURE_NEW_PICTURE = 1;
ImageView photo1;
Button camera, galary,save;
Uri selectedImageUri;
String selectedPath;
Bitmap photo;
private static final int CAMERA_REQUEST = 1888;
public static final String MIMETYPE_FORMALITY = "vnd.android.cursor.item/useformality";
public static final int MEDIA_TYPE_IMAGE = 1;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
photo1=(ImageView)findViewById(R.id.imageView1);
camera=(Button)findViewById(R.id.button1);
galary=(Button)findViewById(R.id.button2);
save=(Button)findViewById(R.id.button3);
//camera picture
camera.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
//gallery picture
galary.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
});
save.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
Context context= getApplicationContext();
Bitmap icon= BitmapFactory.decodeResource(context.getResources(), R.id.imageView1);
try
{
Intent myIntent = new Intent();
myIntent.setAction(Intent.ACTION_ATTACH_DATA);
myIntent.setType("image/jpeg");
myIntent.putExtra(Intent.EXTRA_STREAM, icon);
startActivity(myIntent);
}
catch (ActivityNotFoundException e)
{
e.printStackTrace();
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
photo1.setImageBitmap(photo);
}
else
{
if (data != null && resultCode == RESULT_OK)
{
Uri selectedImage = data.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);
cursor.close();
if(photo != null && !photo.isRecycled())
{
photo = null;
}
photo = BitmapFactory.decodeFile(filePath);
photo1.setBackgroundResource(0);
photo1.setImageBitmap(photo);
}
else
{
Log.d("Status:", "Photopicker canceled");
}
}
}
}

Android Read Contact Information

I am calling intent to pick a contact using this code.
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
((Activity) mContext).startActivityForResult(intent, PICK_CONTACT);
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (reqCode == PICK_CONTACT) {
if (resultCode == Activity.RESULT_OK) {
Uri uri= data.getData();
}
Here I want to fetch three information of contact such as Name, Phone number, and contact Image.
I am able to fetch name and number but not able to fetch Image. any help would be appreciated.
use following function:
private String retrieveContactPhoto(String contactID) {
// Bitmap photo = null;
/*
* if (inputStream != null) { photo =
* BitmapFactory.decodeStream(inputStream); ImageView imageView =
* (ImageView) findViewById(R.id.img_contact);
* imageView.setImageBitmap(photo); }
*/
Uri photoUri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI,
Long.parseLong(contactID));
final Cursor image = getContentResolver().query(photoUri,
PHOTO_ID_PROJECTION, null, null,
ContactsContract.Contacts._ID + " ASC");
try {
Integer thumbnailId = null;
if (image.moveToFirst()) {
thumbnailId = image.getInt(image
.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
Uri uri = ContentUris.withAppendedId(
ContactsContract.Data.CONTENT_URI, thumbnailId);
image.close();
if (uri.toString().equals("content://com.android.contacts/data/0"))
return null;
return uri.toString();
}
} finally {
image.close();
}
return null;
and for showing image use following code
if (entries.get(position).getphoto() != null
&& entries.get(position).getphoto() != "content:////com.android.contacts//data//0") {
try {
holder.photo.setImageURI(Uri.parse(entries.get(position)
.getphoto()));
} catch (Exception e) {
holder.photo.setImageResource(R.drawable.abc); //use default image
}
} else
holder.photo.setImageResource(R.drawable.abc); //use default image
Try following
InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),uri);
BufferedInputStream buf =new BufferedInputStream(photo_stream);
Bitmap my_btmp = BitmapFactory.decodeStream(buf);
Use this:
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(this.getContentResolver(), uri);
BufferedInputStream buffer =new BufferedInputStream(input);
Bitmap bitmap = BitmapFactory.decodeStream(buffer);
Check the below code which will help you to get the Contact Name,Number and contact Image as well. Call the below code on click of a button.
public void onClickSelectContact(View btnSelectContact) {
// using native contacts selection
// Intent.ACTION_PICK = Pick an item from the data, returning what was selected.
startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), REQUEST_CODE_PICK_CONTACTS);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PICK_CONTACTS && resultCode == RESULT_OK) {
Log.d(TAG, "Response: " + data.toString());
uriContact = data.getData();
retrieveContactName();
retrieveContactNumber();
retrieveContactPhoto();
}
}
//To get the Contact Image
private void retrieveContactPhoto() {
Bitmap photo = null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
ImageView imageView = (ImageView) findViewById(R.id.img_contact);
imageView.setImageBitmap(photo);
}
assert inputStream != null;
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//To get Contact Number.
private void retrieveContactNumber() {
String contactNumber = null;
// getting contacts ID
Cursor cursorID = getContentResolver().query(uriContact,
new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
Log.d(TAG, "Contact ID: " + contactID);
// Using the contact ID now we will get contact phone number
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactID},
null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
Log.d(TAG, "Contact Phone Number: " + contactNumber);
}
//To get Contact Name.
private void retrieveContactName() {
String contactName = null;
// querying contact data store
Cursor cursor = getContentResolver().query(uriContact, null, null, null, null);
if (cursor.moveToFirst()) {
// DISPLAY_NAME = The display name for the contact.
// HAS_PHONE_NUMBER = An indicator of whether this contact has at least one phone number.
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursor.close();
Log.d(TAG, "Contact Name: " + contactName);
}
}
Also to get all the phone numbers + email address try as below:
ContentResolver contactResolver = context.getContentResolver();
Cursor cursor = contactResolver.query(Uri.parse(aContact.getLookupUri()), null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String photoUri = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = contactResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { contactId }, null);
while (pCur.moveToNext())
{
String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String type = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(), Integer.parseInt(type), "");
Log.d("TAG", s + " phone: " + phone);
}
pCur.close();
}
Cursor emailCursor = contactResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { contactId }, null);
while (emailCursor.moveToNext())
{
String phone = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
int type = emailCursor.getInt(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(context.getResources(), type, "");
Log.d("TAG", s + " email: " + phone);
}
emailCursor.close();
cursor.close();
}

my application not save image

My app crashes when I press the Save button. I have been following this tutorial. LogCat is showing the error "unable to open database file
Here is my code:
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
protected static TextView textView;
protected static ImageView image1, image2;
protected Button get_image, save_image, read_image;
private String selectedImagePath;
private static final int SELECT_PICTURE = 1;
String DB_NAME = Environment.getExternalStorageDirectory() + "/test.db"; String
TABLE_NAME = "mytable";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image1 = (ImageView) findViewById(R.id.imageView1);
image2 = (ImageView) findViewById(R.id.imageView2);
textView = (TextView) findViewById(R.id.textView1);
get_image = (Button) findViewById(R.id.get_image);
get_image.setOnClickListener(this);
save_image = (Button) findViewById(R.id.save_image);
save_image.setOnClickListener(this);
read_image = (Button) findViewById(R.id.read_image);
read_image.setOnClickListener(this);
}
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.get_image:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(
intent,"Select Picture"),SELECT_PICTURE);
break;
case R.id.save_image:
createTable();
saveInDB();
break;
case R.id.read_image:
readFromDB();
break;
default:
break;
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
image1.setVisibility(View.VISIBLE);
image1.setImageURI(selectedImageUri);
}
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} void createTable() {
SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
String MySQL = "create table if not exists " + TABLE_NAME
+ " (_id INTEGER primary key autoincrement,
name TEXT not null, image BLOB);";
myDb.execSQL(MySQL);
myDb.close();
}
void saveInDB() {
SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,Context.MODE_PRIVATE, null);
byte[] byteImage1 = null;
String s = myDb.getPath();
myDb.execSQL("delete from " + TABLE_NAME);
// clearing the table
ContentValues newValues = new ContentValues();
String name = "CoderzHeaven";
newValues.put("name", name);
try {
FileInputStream instream = new FileInputStream(selectedImagePath);
BufferedInputStream bif = new BufferedInputStream(instream);
byteImage1 = new byte[bif.available()];
bif.read(byteImage1);
newValues.put("image", byteImage1);
long ret = myDb.insert(TABLE_NAME, null, newValues);
if (ret < 0)
textView.append("Error");
} catch (IOException e) {
textView.append("Error Exception : " + e.getMessage()); }
myDb.close();
textView.append("\n Saving Details \n Name : " + name);
textView.append("\n Image Size : " + byteImage1.length + " KB");
textView.append("\n Saved in DB : " + s + "\n");
Toast.makeText(this.getBaseContext(),
"Image Saved in DB successfully.", Toast.LENGTH_SHORT).show();
}
void readFromDB() {
byte[] byteImage2 = null;
SQLiteDatabase myDb;
myDb = openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
Cursor cur = myDb.query(TABLE_NAME, null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false) {
textView.append("\n Reading Details \n Name : " + cur.getString(1));
cur.moveToNext();
} // /////Read data from blob field////////////////////
cur.moveToFirst();
byteImage2 = cur.getBlob(cur.getColumnIndex("image"));
setImage(byteImage2);
cur.close();
myDb.close();
Toast.makeText(this.getBaseContext(),"Image read from DB successfully.",
Toast.LENGTH_SHORT).show();
Toast.makeText(this.getBaseContext(),
"If your image is big, please scrolldown to see the result.",
Toast.LENGTH_SHORT).show();
}
void setImage(byte[] byteImage2) {
image2.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0,
byteImage2.length));
textView.append("\n Image Size : " +
byteImage2.length + " KB");
}
}

Categories

Resources