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");
}
}
Related
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" />
FIRSTPAGE.JAVA Here there few edit text and to be saved temporarily
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.first_page);
applno = (EditText) findViewById(R.id.rpfno);
financerups = (EditText) findViewById(R.id.finance_rupees);
tenure = (EditText) findViewById(R.id.tenure);
assetname = (EditText) findViewById(R.id.asset);
rowId = (EditText) findViewById(R.id.etRowInfo);
page1 = (Button) findViewById(R.id.pf1);
page2 = (Button) findViewById(R.id.pf2);
page3 = (Button) findViewById(R.id.pf3);
page4 = (Button) findViewById(R.id.pf4);
save = (Button) findViewById(R.id.btn_saveandcontinue);
exit = (Button) findViewById(R.id.btn_exit);
info = (Button) findViewById(R.id.info);
submitserver = (Button) findViewById(R.id.submitserver);
edit = (Button) findViewById(R.id.bEdit);
update = (Button) findViewById(R.id.bUpdate);
delete = (Button) findViewById(R.id.bDelete);
delete.setOnClickListener(this);
save.setOnClickListener(this);
exit.setOnClickListener(this);
info.setOnClickListener(this);
submitserver.setOnClickListener(this);
edit.setOnClickListener(this);
update.setOnClickListener(this);
page2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
startActivity(new Intent(FirstPage.this, Reference.class));
}
});
page1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
startActivity(new Intent(FirstPage.this, ProfilePage1.class));
}
});
page3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(FirstPage.this, Asset.class));
}
});
page4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(FirstPage.this, OfficeUse.class));
}
});
}
public void onClick(View arg0)
{
switch (arg0.getId())
{
case R.id.btn_saveandcontinue:
boolean didItWork = true;
try{
String Applno = applno.getText().toString();
String Financerups = financerups.getText().toString();
String Tenure = tenure.getText().toString();
String Assetname = assetname.getText().toString();
WayDataBase entry = new WayDataBase(FirstPage.this);
entry.open();
entry.createEntry(Applno, Financerups, Tenure, Assetname);
entry.close();
} catch (Exception e){
didItWork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Dang");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}finally
{
if(didItWork)
{
/*Dialog d = new Dialog(this);
d.setTitle("Heck Yea!");
TextView tv = new TextView(this);
tv.setText("SUCCESS");
d.setContentView(tv);
d.show();*/
startActivity(new Intent(FirstPage.this, OfficeUse.class));
}
}
break;
case R.id.info:
startActivity(new Intent (FirstPage.this, TableView.class));
finish();
break;
case R.id.bEdit:
String s = rowId.getText().toString();
long l = Long.parseLong(s);
WayDataBase wdb = new WayDataBase(this);
wdb.open();
String returnedappno = wdb.getAppno(l);
String returnedfinancerups= wdb.getfinancerups(l);
String returnedtenure = wdb.getTenure(l);
String returnedasset = wdb.getAsset(l);
wdb.close();
applno.setText(returnedappno);
financerups.setText(returnedfinancerups);
tenure.setText(returnedtenure);
assetname.setText(returnedasset);
break;
case R.id.bUpdate:
break;
case R.id.bDelete:
break;
}}}
OFFICEUSE.JAVA Here there is few mor edit text to be saved with repect to the above fields using update method and with its corresponding unique field must be used to retrieval
page2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(OfficeUse.this, Reference.class));
}});
page1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(OfficeUse.this,ProfilePage1.class));
}});
page4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(OfficeUse.this, OfficeUse.class));
}});
page3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(OfficeUse.this, Asset.class));
}});
exit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),FirstPage.class);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}});}
public void onClick(View arg0){
switch (arg0.getId()){
case R.id.btn_saveandcontinue:
boolean isItWork = true;
try{
String Applcname = applcname.getText().toString();
String Employee = employee.getText().toString();
String Psnem = psnem.getText().toString();
String Branch = branch.getText().toString();
String Clientid = clientid.getText().toString();
String Schmcode = schmcode.getText().toString();
String Agreeno = agreeno.getText().toString();
String Promoschm = promoschm.getText().toString();
WayDataBase entry1 = new WayDataBase(OfficeUse.this);
entry1.open();
entry1.createEntry1(Applcname, Employee, Psnem, Branch, Clientid, Schmcode, Agreeno, Promoschm);
entry1.close();
} catch (Exception e){
isItWork = false;
String error = e.toString();
Dialog d1 = new Dialog(this);
d1.setTitle("Office Dang");
TextView tv1 = new TextView(this);
tv1.setText(error);
d1.setContentView(tv1);
d1.show();
}finally{
if(isItWork){
Dialog d1 = new Dialog(this);
d1.setTitle("Office too work");
TextView tv1 = new TextView(this);
d1.setContentView(tv1);
d1.show();
}}
break;
case R.id.info:
startActivity(new Intent (OfficeUse.this, TableView.class));
finish();
break;
}}}
WAYDATABASE.JAVA
private static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL( "CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_APPNO + " TEXT NOT NULL, " +
KEY_AMT + " TEXT NOT NULL, " +
KEY_TENURE + " TEXT NOT NULL, " +
KEY_ASSETS + " TEXT NOT NULL, " +
KEY_APPLCNAME + " TEXT NOT NULL, " +
KEY_EMPLOYEE + " TEXT NOT NULL, " +
KEY_PSNEM + " TEXT NOT NULL, " +
KEY_BRANCH + " TEXT NOT NULL, " +
KEY_CLIENTID + " TEXT NOT NULL, " +
KEY_SCHMCODE + " TEXT NOT NULL, " +
KEY_AGREENO + " TEXT NOT NULL, " +
KEY_PROMOSCHM + " TEXT NOT NULL);" );}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(" DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
} }
public WayDataBase(Context c){
ourContext=c;
}
public WayDataBase open() throws SQLException{
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public long createEntry(String applno, String financerups, String tenure,String assetname){
ContentValues cv = new ContentValues();
cv.put(KEY_APPNO, applno);
cv.put(KEY_AMT, financerups);
cv.put(KEY_TENURE, tenure);
cv.put(KEY_ASSETS, assetname);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public long createEntry1(String applcname, String employee, String psnem,
String branch, String clientid, String schmcode, String agreeno,
String promoschm) {
ContentValues cv1 = new ContentValues();
cv1.put(KEY_APPLCNAME,applcname);
cv1.put(KEY_EMPLOYEE,employee);
cv1.put(KEY_PSNEM,psnem);
cv1.put(KEY_BRANCH,branch);
cv1.put(KEY_CLIENTID,clientid);
cv1.put(KEY_SCHMCODE,schmcode);
cv1.put(KEY_AGREENO,agreeno);
cv1.put(KEY_PROMOSCHM,promoschm);
return ourDatabase.insert(DATABASE_TABLE, null, cv1);
}
public void close(){
ourHelper.close();
}
public String getData() {
String[] columns = new String[]{ KEY_ROWID, KEY_APPNO, KEY_AMT,KEY_TENURE, KEY_ASSETS,KEY_APPLCNAME,KEY_EMPLOYEE,KEY_PSNEM,KEY_BRANCH,KEY_CLIENTID,KEY_SCHMCODE,KEY_AGREENO,KEY_PROMOSCHM };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result=" ";
int iRow = c.getColumnIndex(KEY_ROWID);
int iAppno = c.getColumnIndex(KEY_APPNO);
int iAmt = c.getColumnIndex(KEY_AMT);
int iTenure = c.getColumnIndex(KEY_TENURE);
int iAssets = c.getColumnIndex(KEY_ASSETS);
int iApplcname = c.getColumnIndex(KEY_APPLCNAME);
int iEmployee = c.getColumnIndex(KEY_EMPLOYEE);
int iPsnem = c.getColumnIndex(KEY_PSNEM);
int iBranch = c.getColumnIndex(KEY_BRANCH);
int iClientId = c.getColumnIndex(KEY_CLIENTID);
int iSchmode = c.getColumnIndex(KEY_SCHMCODE);
int iAgreeno = c.getColumnIndex(KEY_AGREENO);
int iPromoschm = c.getColumnIndex(KEY_PROMOSCHM);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
result = result + c.getString(iRow) + " " + c.getString(iAppno) + " " + c.getString(iAmt) + " " + c.getString(iTenure) + c.getString(iAssets) +
c.getString(iApplcname) + " " + c.getString(iEmployee) + " " + c.getString(iPsnem) + " " + c.getString(iBranch) + c.getString(iClientId) +
c.getString(iSchmode) + " " + c.getString(iAgreeno) + " " + c.getString(iPromoschm) + "\n";
}
return result; }
public String getAppno(long l) {
String[] columns = new String[]{ KEY_ROWID, KEY_APPNO, KEY_AMT, KEY_TENURE, KEY_ASSETS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null, null);
if(c != null) {
c.moveToFirst();
String appno = c.getString(1);
return appno;
}
return null;}
public String getfinancerups(long l) {
String[] columns = new String[]{ KEY_ROWID, KEY_APPNO, KEY_AMT, KEY_TENURE, KEY_ASSETS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null, null);
if(c != null) {
c.moveToFirst();
String rups = c.getString(2);
return rups;
}
return null; }
public String getTenure(long l) {
String[] columns = new String[]{ KEY_ROWID, KEY_APPNO, KEY_AMT, KEY_TENURE, KEY_ASSETS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null, null);
if(c != null){
c.moveToFirst();
String tenur = c.getString(3);
return tenur;
}
return null;
}
public String getAsset(long l) {
String[] columns = new String[]{ KEY_ROWID, KEY_APPNO, KEY_AMT, KEY_TENURE, KEY_ASSETS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null, null);
if(c != null){
c.moveToFirst();
String aset = c.getString(4);
return aset;
}
return null;
}}
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);
I'm simply getting the all contact list to an object (PhoneBookContact):
private static final Uri PURI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
private static final String PID = ContactsContract.CommonDataKinds.Phone._ID;
private static final String PNAME = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;
private static final String PNUM = ContactsContract.CommonDataKinds.Phone.NUMBER;
String[] projection = new String[]{PID, PNAME, PNUM};
String sortOrder = PNAME + " COLLATE LOCALIZED ASC";
Cursor people = mContext.getContentResolver().query(PURI, projection, null, null, sortOrder);
int indexid = people.getColumnIndex(PID);
int indexName = people.getColumnIndex(PNAME);
int indexNumber = people.getColumnIndex(PNUM);
people.moveToFirst();
do {
PhoneBookContact phoneBookContact = new PhoneBookContact();
phoneBookContact.setmCursorId(people.getLong(indexid));
phoneBookContact.setmDisplayName(people.getString(indexName));
phoneBookContact.setmPhoneNumber(UriFactory.formatNumberToInternational(people.getString(indexNumber)));
phoneList.put(phoneBookContact.getmPhoneNumber(), phoneBookContact);
} while (people.moveToNext());
people.close();
To fetch the photo of the user from Android Contacts, I'am using this method:
public static Uri loadContactPhotoUri(ContentResolver contentResolver, long id) {
try {
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
return person;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
Finally, this code gives this URI for a specific user:
content://com.android.contacts/contacts/5907
Since I'm calling this URI with ContactsContract.CommonDataKinds.Phone._ID id, I can't get the photo of the user successfully. In fact, it should be the id of ContactsContract.Contacts._ID. How can I query the photo of the user and fix this problem?
Instead of ContactsContract.CommonDataKinds.Phone._ID, you must use ContactsContract.CommonDataKinds.Phone.CONTACT_ID to save the cursorID of Contacts table. It solved my problem.
This file have funtion get contact photo
https://github.com/heinrisch/Contact-Picture-Sync/blob/master/src/heinrisch/contact/picture/sync/ContactHandler.java
package heinrisch.contact.picture.sync;
import java.io.InputStream;
import java.util.ArrayList;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDiskIOException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts.Data;
import android.provider.ContactsContract.RawContacts;
import android.util.Log;
public class ContactHandler {
public static ArrayList<String> getNumbers(String ID, Context context){
ArrayList<String> numbers = new ArrayList<String>();
ContentResolver cr = context.getContentResolver();
Cursor phones = cr.query(Phone.CONTENT_URI, null,Phone.CONTACT_ID + " = " + ID, null, null);
while (phones.moveToNext()) {
numbers.add(phones.getString(phones.getColumnIndex(Phone.NUMBER)));
}
phones.close();
return numbers;
}
public static void matchContactsToFriends(ArrayList<Friend> friends, Context context) {
Cursor people = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if(people == null){
Log.e("ContactHandler", "Could not find contacts...?");
return;
}
while(people.moveToNext()) {
String ID = null,name = null;
int columnIndex = people.getColumnIndex(ContactsContract.Contacts._ID);
if(columnIndex != -1) ID = people.getString(columnIndex);
columnIndex = people.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
if(columnIndex != -1) name = people.getString(columnIndex);
//ArrayList<String> numbers = getNumbers(ID,context); //"can't" get this from facebook
if(name == null) continue;
for(Friend f : friends){
if(f.isMatchedWithContact()) continue;
if(f.getName().equals(name)){
f.setContactID(ID);
Bitmap contactPhoto = getPhoto(context, ID);
if(contactPhoto != null) f.setContactPicture(contactPhoto);
break;
}
}
}
people.close();
}
public static void setContactPicture(Friend f, Context context){
f.setContactPicture(getPhoto(context, f.getContactID()));
}
public static int getNumberOfContacts(Context context) {
Cursor people = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
int numberOfContacts = people.getCount();
people.close();
return numberOfContacts;
}
public static Uri getPicture(Context context, String ID){
ContentResolver cr = context.getContentResolver();
Uri rawContactUri = null;
Cursor rawContactCursor = cr.query(RawContacts.CONTENT_URI, new String[] {RawContacts._ID}, RawContacts.CONTACT_ID + " = " + ID, null, null);
if(!rawContactCursor.isAfterLast()) {
rawContactCursor.moveToFirst();
rawContactUri = RawContacts.CONTENT_URI.buildUpon().appendPath(""+rawContactCursor.getLong(0)).build();
}
rawContactCursor.close();
return rawContactUri;
}
public static void setContactPicture(Context context, String ID, Bitmap picture){
ContentResolver cr = context.getContentResolver();
Uri rawContactUri = getPicture(context, ID);
if(rawContactUri == null){
Log.e("rawContactUri", "is null");
return;
}
ContentValues values = new ContentValues();
int photoRow = -1;
String where = ContactsContract.Data.RAW_CONTACT_ID + " == " +
ContentUris.parseId(rawContactUri) + " AND " + Data.MIMETYPE + "=='" +
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI, null, where, null, null);
int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID);
if(cursor.moveToFirst()){
photoRow = cursor.getInt(idIdx);
}
cursor.close();
values.put(ContactsContract.Data.RAW_CONTACT_ID,
ContentUris.parseId(rawContactUri));
values.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, Tools.bitmapToByteArray(picture));
values.put(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
try{
if(photoRow >= 0){
cr.update(
ContactsContract.Data.CONTENT_URI,
values,
ContactsContract.Data._ID + " = " + photoRow, null);
} else {
cr.insert(
ContactsContract.Data.CONTENT_URI,
values);
}
}catch(SQLiteDiskIOException dIOe){
//TODO: should show this to the user..
dIOe.printStackTrace();
}
}
public static Bitmap getPhoto(Context context, String contactId) {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactId));
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), uri);
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
}
I'm trying to retrieve contact list with there name and phone numbers. I try following code:
// Get a cursor over every contact.
Cursor cursor = getContentResolver().query(People.CONTENT_URI,
null, null, null, null);
// Let the activity manage the cursor lifecycle.
startManagingCursor(cursor);
// Use the convenience properties to get the index of the columns
int nameIdx = cursor.getColumnIndexOrThrow(People.NAME);
int phoneIdx = cursor. getColumnIndexOrThrow(People.NUMBER);
String[] result = new String[cursor.getCount()];
if (cursor.moveToFirst())
do {
// Extract the name.
String name = cursor.getString(nameIdx);
// Extract the phone number.
String phone = cursor.getString(phoneIdx);
result[cursor.getPosition()] = name + "-" +" "+ phone;
} while(cursor.moveToNext());
This code should return an array with the all contacts name and its phone number but this only returns name of the contact and returns NULL in phone number,
Example Output:
John - null
In Android manifest:
<uses-permission android:name="android.permission.READ_CONTACTS" />
Then in the activity:
editText.setOnFocusChangeListener(new OnFocusChangeListener(){
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
editText.setText("");
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
}
});
And then you have to catch the result of the action pick contact:
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data){
super.onActivityResult(reqCode, resultCode, data);
switch(reqCode)
{
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK)
{
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst())
{
String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1"))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
phones.moveToFirst();
String cNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(getApplicationContext(), cNumber, Toast.LENGTH_SHORT).show();
String nameContact = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
editText.setText(nameContact+ " "+ cNumber);
}
}
}
}
}
Don't use deprecated API access like as follow
Cursor cursor = getContentResolver().
query( Contacts.CONTENT_URI,
new String[]{Contacts.DISPLAY_NAME}, null, null,null);
if(cursor!=null){
while(cursor.moveToNext()){
Cursor c = getContentResolver().query(Phone.CONTENT_URI, new String[]{Phone.NUMBER, Phone.TYPE},
" DISPLAY_NAME = '"+cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME))+"'", null, null);
while(c.moveToNext()){
switch(c.getInt(c.getColumnIndex(Phone.TYPE))){
case Phone.TYPE_MOBILE :
case Phone.TYPE_HOME :
case Phone.TYPE_WORK :
case Phone.TYPE_OTHER :
}
}
}
}
Look on the sample code for retrieve the contacts from android mobile,
Cursor cursor = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String contactId = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phones = context.getContentResolver().query(
Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones
.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
switch (type) {
case Phone.TYPE_HOME:
Log.i("TYPE_HOME", "" + number);
break;
case Phone.TYPE_MOBILE:
Log.i("TYPE_MOBILE", "" + number);
break;
case Phone.TYPE_WORK:
Log.i("TYPE_WORK", "" + number);
break;
case Phone.TYPE_FAX_WORK:
Log.i("TYPE_FAX_WORK", "" + number);
break;
case Phone.TYPE_FAX_HOME:
Log.i("TYPE_FAX_HOME", "" + number);
break;
case Phone.TYPE_OTHER:
Log.i("TYPE_OTHER", "" + number);
break;
}
}
phones.close();
cursor.close();
HellBoy is right, Phone.xxx is depricated. I did it that way with a lookup-uri:
Uri look = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, "23N9983726428fnwe");
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(look);
Experiment with Contacts.xxx on the first line, you will find the right sollution.
Try the below code.
Cursor managedCursor = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER}, null, null, Phone.DISPLAY_NAME + " ASC");
package com.number.contatcs;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Main2Activity extends Activity {
private static final int CONTACT_PICKER_RESULT = 1001;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button getContacts = (Button) findViewById(R.id.button1);
getContacts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(i, CONTACT_PICKER_RESULT);
}
});
}
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (reqCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String number = "";
String lastName = "";
try {
Uri result = data.getData();
// get the id from the uri
String id = result.getLastPathSegment();
// query
cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone._ID
+ " = ? ", new String[] { id }, null);
// cursor = getContentResolver().query(Phone.CONTENT_URI,
// null, Phone.CONTACT_ID + "=?", new String[] { id },
// null);
int numberIdx = cursor.getColumnIndex(Phone.DATA);
if (cursor.moveToFirst()) {
number = cursor.getString(numberIdx);
// lastName =
// cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
} else {
// WE FAILED
}
} catch (Exception e) {
// failed
} finally {
if (cursor != null) {
cursor.close();
} else {
}
}
EditText numberEditText = (EditText) findViewById(R.id.w);
numberEditText.setText(number);
// EditText lastNameEditText =
// (EditText)findViewById(R.id.last_name);
// lastNameEditText.setText(lastName);
}
}
}
}