When I click on CheckData button on android, it is throwing a nullpointer exception.
SaveData.java
public class SaveData extends Activity implements OnClickListener {
static final int DIALOG_ID = 0;
private Uri mImageCaptureUri;
private ImageView mImageView;
public static class Certificates {
private Bitmap bmp;
public Certificates(Bitmap b) {
bmp = b;
}
public Bitmap getBitmap() { return bmp; }
}
private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_FILE = 2;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.addname);
View button1Click=findViewById(R.id.btn_choose);
button1Click.setOnClickListener(this);
View button2Click = findViewById(R.id.Button01add);
button2Click.setOnClickListener(this);
View button3Click = findViewById(R.id.Button01check);
button3Click.setOnClickListener(this);
}
public void onClick(View v){
switch(v.getId()){
case R.id.Button01add:
showDialog(DIALOG_ID);
break;
case R.id.Button01check:
startActivity(new Intent (SaveData.this,CheckData.class));
break;
}
// picking an image from camera or gallery
final String [] items = new String [] {"From Camera", "From SD Card"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(), "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
mImageCaptureUri = Uri.fromFile(file);
try {
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (Exception e) {
e.printStackTrace();
}
dialog.cancel();
} else {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
mImageView = (ImageView) findViewById(R.id.image1);
((Button) findViewById(R.id.btn_choose)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
Bitmap bitmap = null;
String path = "";
if (requestCode == PICK_FROM_FILE) {
mImageCaptureUri = data.getData();
path = getRealPathFromURI(mImageCaptureUri); //from Gallery
if (path == null)
path = mImageCaptureUri.getPath(); //from File Manager
if (path != null)
bitmap = BitmapFactory.decodeFile(path);
} else {
path = mImageCaptureUri.getPath();
bitmap = BitmapFactory.decodeFile(path);
}
mImageView.setImageBitmap(bitmap);
}
public String getRealPathFromURI(Uri contentUri) {
String [] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( contentUri, proj, null, null,null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
protected final Dialog onCreateDialog(final int id) {
Dialog dialog = null;
switch(id) {
case DIALOG_ID:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Information saved successfully ! Add Another Info?")
.setCancelable(false)
.setPositiveButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SaveData.this.finish();
}
})
.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
dialog = alert;
break;
default:
}
return dialog;
}
// menu option
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.mymenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.item1) {
Log.d("Option", "Save option is clicked");
}
if(item.getItemId() == R.id.item2) {
Log.d("Option", "Delete option is clicked");
}
if(item.getItemId() == R.id.item3) {
Log.d("Option", "Exit option is clicked");
}
return super.onOptionsItemSelected(item);
}
}
DataManipulator.java:
public class DataManipulator {
public static final String KEY_IMG = "image";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "DBtest";
private static final int DATABASE_VERSION = 1;
private static final String CERTIFICATES_TABLE = "certificates";
private static final String CREATE_CERTIFICATES_TABLE = "create table "+CERTIFICATES_TABLE+" (" +KEY_IMG+" blob not null) ";
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_CERTIFICATES_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+CERTIFICATES_TABLE);
onCreate(db);
}
}
public void Reset() { mDbHelper.onUpgrade(this.mDb, 1, 1); }
public DataManipulator(Context ctx) {
mCtx = ctx;
mDbHelper = new DatabaseHelper(mCtx);
}
public DataManipulator open() throws SQLException {
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() { mDbHelper.close(); }
public void createCertificatesEntry(Certificates certificates) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
certificates.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, out);
ContentValues cv = new ContentValues();
cv.put(KEY_IMG, out.toByteArray());
mDb.insert(CERTIFICATES_TABLE, null, cv);
}
public Certificates getFirstCertificatesFromDB() throws SQLException {
Cursor cur = mDb.query(true, CERTIFICATES_TABLE, new String[] {KEY_IMG}, null, null, null, null, null, null);
if(cur.moveToFirst()) {
byte[] blob = cur.getBlob(cur.getColumnIndex(KEY_IMG));
ByteArrayInputStream inputStream = new ByteArrayInputStream(blob);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
cur.close();
return new Certificates(bitmap);
}
cur.close();
return null;
}
}
DataManipulator.java:60 is certificates.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, out);
CheckData.java:
public class CheckData extends ListActivity {
TextView selection;
DataManipulator dm;
private DataManipulator DataManipulator;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.check);
dm = new DataManipulator(this);
LinearLayout layout = new LinearLayout(this);
ImageView image = new ImageView(this);
DataManipulator = new DataManipulator(this);
Certificates testCertificates = new Certificates(BitmapFactory.decodeFile(Context.STORAGE_SERVICE));
DataManipulator.open();
DataManipulator.createCertificatesEntry( (Certificates) testCertificates);
DataManipulator.close();
testCertificates = null;
DataManipulator.open();
testCertificates = DataManipulator.getFirstCertificatesFromDB();
DataManipulator.close();
image.setImageBitmap(((Certificates) testCertificates).getBitmap());
setContentView(layout);
}
}
CheckData.java:29 is DataManipulator.createCertificatesEntry( (Certificates) testCertificates);
Logcat error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{list.certificates/list.certificates.CheckData}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
at android.app.ActivityThread.access$600(ActivityThread.java:122)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4340)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at list.certificates.DataManipulator.createCertificatesEntry(DataManipulator.java:60)
at list.certificates.CheckData.onCreate(CheckData.java:29)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
You're getting a null from certificates.getBitmap() because there's not a bitmap there. In your initial assignment, you're trying to decode a file that doesn't exist. Using Context.STORAGE_SERVICE doesn't work that way, it's just a string equaling storage.
For example code of how to use a storage manager properly, try this.
If you're just trying to decode a resource(drawable, raw, etc) use another form of decode:
InputStream is = context.getResources().openRawResource(resID);
Bitmap bitmap = BitmapFactory.decodeStream(is);
Update:
Assuming I know what it is you're trying to do, the problem is that you're switching to the CheckData activity without passing the selected bitmap in any way. The activity has no way of knowing what bitmap to use, and Context.STORAGE_SERVICE is not a bitmap in any way, so you can't decode it.
For good answers on how to pass the bitmap to the new activity, look here.
In short, you could add an mBitmap variable to SaveData, and pass it along to CheckData.
For this, change the code in SaveData.onClick() to:
case R.id.Button01check:
Intent intent = new Intent (SaveData.this,CheckData.class);
intent.putExtra("bitmapData", mBitmap)
startActivity(intent);
break;
And, in onActivityResult(), add this at the end:
mBitmap = bitmap;
In CheckData.onCreate():
Bitmap bmp = getIntent().getExtras().get("bitmapData");
if(bmp != null) {
Certificates testCertificates = new Certificates(bmp);
} else {
// Back out gracefully //
}
Problem root:
Your problem is in this line
Certificates testCertificates =
new Certificates(BitmapFactory.decodeFile(Context.STORAGE_SERVICE));
The parameter to decodeFile is invalid hence it returns null. The parameter should be the path to the image file, whereas you are passing a constant that is to be used for retrieving the storage service.
Fix:
You already have the bitmap in SaveData activity. You need to pass it to CheckData activity through intent.
Add the bitmap to the intent :
case R.id.Button01check:
Intent intent = new Intent(this, CheckData.class);
intent.putExtra("BitmapImage", bitmap);
startActivity(intent);
Then in CheckData activity, retrieve the bitmap from intent and create the Certificates object.
Bitmap bitmap = (Bitmap) getIntent().getParcelableExtra("BitmapImage");
Certificates testCertificates = new Certificates(bitmap );
Reference: How can I pass a Bitmap object from one activity to another
Either certificates is null, or certificates.getBitmap() is returning null. Add logging to find out which.
check certificates is null or not before inserting data as:
public void createCertificatesEntry(Certificates certificates) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
if(certificates !=null)
{
certificates.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, out);
ContentValues cv = new ContentValues();
cv.put(KEY_IMG, out.toByteArray());
mDb.insert(CERTIFICATES_TABLE, null, cv);
}
else
{
}
}
generally , in order to handle exceptions, i would give you this tip:
when you get the exception on the logcat , double click (or press
ENTER) each of the red lines of the logs in this chunk , till the text
cursor goes to the correct line that you got the exception .
then , once you know on which of the variables you got the expcetion ,
put a breakpoint there ,on the event of clicking , and on the event of
onCreate , to see why you got this exception .
however , your code has so many weird things , for example:
why do you call setContentView twice in the same method ?
why do you try to decode a bitmap file which its name is Context.STORAGE_SERVICE ?
why do you have a class and and instance with the same name (DataManipulator) ? please use a more standard way to name fields and variables.
Related
I am inside a fragment and I have a CircleImageView to which I have set an image in xml by default using android:src="#drawable/default_profile_image".
The user can decide whether to load another image and I do it by launching an intent that opens the gallery and in the onActivityResult() I load the image in this way:
if(requestCode==0 && resultCode == Activity.RESULT_OK) {
Uri path = data.getData();
Bitmap photo = null;
try {
photo = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), path);
} catch (IOException e) {
e.printStackTrace();
}
if(photo != null)
mProfilePhoto.setImageBitmap(photo);
}
Now whether the user has uploaded another image or left the default image, I would like to save it in the database, and then take it.
I already have a method that takes the name from the database correctly.
private void getUserInformation(){
Cursor data = databaseHelper.getUserInformation();
if(data.moveToFirst()) {
//this crash
Bitmap bitmap = BitmapFactory.decodeByteArray(data.getBlob(2), 0, data.getBlob(2).length);
if(bitmap != null)
mProfilePhoto.setImageBitmap(bitmap);*/
mProfileName = data.getString(1);
}
data.close();
}
This is what I have for the moment that does not work
onclick method inside the fragment
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.saveProfileButton:
//need to pass a bitmap insted of null
addUserInformation(name,null);
break;
case R.id.profile_photo:
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
try {
startActivityForResult(
Intent.createChooser(i, "Select Picture"), 0);
}catch (ActivityNotFoundException ex){
ex.printStackTrace();
}
break;
}
}
private void addUserInformation(String username, Bitmap profile_pic){
boolean b = databaseHelper.addUserInformation(username, profile_pic);
if(b) {
toastMessage("Update Success");
}
else
toastMessage("Update Failed");
}
DatabaseHelper class
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "userinfo";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME1 = "USER_INFORMATION";
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+TABLE_NAME1+" (ID INTEGER PRIMARY KEY AUTOINCREMENT, USERNAME TEXT, PICTURE BLOB)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME1);
onCreate(db);
}
public boolean addUserInformation(String username, Bitmap picture){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("USERNAME", username);
byte[] data = getBitmapAsByteArray(picture);
values.put("PICTURE", data);
long id = db.insert(TABLE_NAME1, null, values);
db.close();
if(id == -1)
return false;
else
return true;
}
private static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
}
Modify your method:
private void getUserInformation(){
Cursor data = databaseHelper.getUserInformation();
if(data.moveToFirst()) {
byte[] btyeArray = data.getBlob(2);
if(btyeArray != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(btyeArray , 0, btyeArray .length);
if(bitmap != null) {
mProfilePhoto.setImageBitmap(bitmap);
photo = bitmap;
}else
mProfilePhoto.setImageResource(R.drawable.defaultImage); // set your default Image here
} else {
mProfilePhoto.setImageResource(R.drawable.defaultImage); // set your default Image here
}
mProfileName = data.getString(1);
}
data.close();
}
in onActivityResult Bitmap photo define it as a global variable. and while calling addUserInformation send photo variable.
case R.id.saveProfileButton:
//need to pass a bitmap insted of null
addUserInformation(name, photo);
Modify your DatabaseHelper method
public boolean addUserInformation(String username, Bitmap picture){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("USERNAME", username);
if(picture != null) {
byte[] data = getBitmapAsByteArray(picture);
values.put("PICTURE", data);
}
long id = db.insert(TABLE_NAME1, null, values);
db.close();
if(id == -1)
return false;
else
return true;
}
I am new to android programming so hopefully someone can be off help. Been having issues with attempting to add an image from Gallery or Camera to my SQLite database. I stumbled across someone's GitHub who had a CameraGallerySqliteDemo
Found here
I tried to amend the code for my needs but have been unable to add an image to my gallery table.
Below is the class I am using to add images to the database.
public class add_gallery extends AppCompatActivity {
Button addImage;
ArrayList<Gall> imageArry = new ArrayList<Gall>();
GalleryImageAdapter imageAdapter;
private static final int CAMERA_REQUEST = 1;
private static final int PICK_FROM_GALLERY = 2;
ListView dataList;
//maybe change to image title later
byte[] imageName;
int imageId;
Bitmap theImage;
DatabaseHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_gallery);
dataList = (ListView) findViewById(R.id.list);
/**
* create DatabaseHelper object
*/
myDb = new DatabaseHelper(this);
/**
* Reading and getting all records from database
*/
List<Gall> images = myDb.getAllGallery();
for (Gall cn : images) {
String log = "ID:" + cn.getID() + " Image: " + cn.getImage()
+ " ,Title: " + cn.getTitle()
+ " ,Caption: " + cn.getCaption();
// Writing Galls to log
Log.d("Result: ", log);
// add images data in arrayList
imageArry.add(cn);
}
/**
* Set Data base Item into listview
*/
imageAdapter = new GalleryImageAdapter(this, R.layout.gallery_list,
imageArry);
dataList.setAdapter(imageAdapter);
/**
* go to next activity for detail image
*/
dataList.setOnItemClickListener(new AdapterView.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(add_gallery.this,
DisplayImageActivity.class);
intent.putExtra("imageid", imageId);
intent.putExtra("imagename", theImage);
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 Galls
Log.d("Insert: ", "Inserting ..");
myDb.addGallery(new Gall("Android", imageInByte));
Intent i = new Intent(add_gallery.this,
add_gallery.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 Galls
Log.d("Insert: ", "Inserting ..");
myDb.addGallery(new Gall("Android", imageInByte));
Intent i = new Intent(add_gallery.this,
add_gallery.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);
}
}
Below is the method I call to add an Image to the Gallery, addGallery
public// Adding new image to gallery
void addGallery(Gall gallery) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(IMAGE, gallery._image);
values.put(TITLE, gallery._title);
values.put(CAPTION, gallery._caption);
// Inserting Row
db.insert(GALLERY_TABLE, null, values);
db.close(); // Closing database connection
}
Below is the Gall class
public class Gall {
// private variables
int _id;
byte[] _image;
String _title;
String _caption;
// Empty constructor
public Gall() {
}
// constructor
public Gall(int keyId, byte[] image, String title, String caption) {
this._id = keyId;
this._image = image;
this._title = title;
this._caption = caption;
}
public Gall(byte[] image, String title, String caption) {
this._image = image;
this._title = title;
this._caption = caption;
}
public Gall(int keyId) {
this._id = keyId;
}
// getting ID
public int getID() {
return this._id;
}
// setting id
public void setID(int keyId) {
this._id = keyId;
}
// getting image
public byte[] getImage() {
return this._image;
}
// setting image
public void setImage(byte[] image) {
this._image = image;
}
// getting
public String getTitle() {
return this._title;
}
// setting title
public void setTitle(String title) {
this._title = title;
}
// getting caption
public String getCaption() {
return this._title;
}
// setting caption
public void setCaption(String caption) {
this._title = caption;
}
Perhaps a trained eye can spot where I am going wrong, I not receiving any errors, just that the image is not being added to database table. Any help would be greatly appreciated.
Store image as byte array in the db.
Please check the example here. This might help you.
You should save your images in a folder and save their paths in you db . If you want your images to be protected and don't wanna show them in gallery as well then there are some ways like using .nomedia files or you can save your images in private folder which will not be accessible to any other app rather than yours.
I'm a newbie in Android,
I just wondering how to store an image to SQLite database in Android, well i have database look like this.
Photo
id (int) | image (BLOB)
Then i have a class to get an image from gallery..
LogoSQLiDemoActivity
public class LogoSQLiteDemoActivity extends Activity implements OnClickListener{
ContactImageAdapter imageAdapter;
Validation valid;
DBDataSource db;
private ArrayList<image> imageArry = new ArrayList<image>();
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int CAMERA_REQUEST = 1;
private static final int PICK_FROM_GALLERY = 2;
int imageId;
byte[] imageName;
String nama_foto;
String nama;
Bitmap theImage;
byte imageInByte[];
private Long id;
//widget
private EditText edNama_foto;
Button addImage;
Button cancel;
ListView dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_data_photo2);
/*** create DatabaseHandler object*/
db = new DBDataSource(this);
//error in here
db.open();
dataList = (ListView) findViewById(R.id.list);
cancel = (Button)findViewById(R.id.btnCancel);
addImage = (Button) findViewById(R.id.btnAdd);
cancel.setOnClickListener(this);
Sma sekolah = db.getLastSma();
id = sekolah.getId();
/**
* Reading and getting all records from database
*/
List<image> img = db.getAllImage_Logo(id);
for (image cn : img)
{
// 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).getLokasi_foto();
imageId = imageArry.get(position).get_id_sma();
Log.d("Before Send:****", imageName + "-" + imageId);
// convert byte to bitmap
ByteArrayInputStream imageStream = new ByteArrayInputStream(
imageName);
theImage = BitmapFactory.decodeStream(imageStream);
Intent intent = new Intent(LogoSQLiteDemoActivity.this,
DisplayImageActivity2.class);
intent.putExtra("imagename", theImage);
intent.putExtra("imageid", imageId);
startActivity(intent);
}
});
/**
* open dialog for choose camera/gallery
*/
final String[] option = new String[] { "Ambil dari Kamera",
"Pilih dari Album" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, option);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pilihan");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.e("Pilihan", String.valueOf(which));
if (which == 0) {
callCamera();
}
if (which == 1) {
callGallery();
}
}
});
final AlertDialog dialog = builder.create();
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.addImage3(new image(imageInByte));
Intent i = new Intent(LogoSQLiteDemoActivity.this, LogoSQLiteDemoActivity.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.addImage3(new image(imageInByte));
Intent i = new Intent(LogoSQLiteDemoActivity.this,
LogoSQLiteDemoActivity.class);
startActivity(i);
finish();
}
}
}
/**
* open camera method
*/
public void callCamera() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", 0);
cameraIntent.putExtra("aspectY", 0);
cameraIntent.putExtra("outputX", 150);
cameraIntent.putExtra("outputY", 150);
cameraIntent.putExtra("return-data", true);
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", 150);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
PICK_FROM_GALLERY);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.btnCancel:
Intent intent = new Intent(getApplicationContext(), MenuAdmin.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
}
and this a method i use to store picture in sqlite
public void addImage3(image img) {
open(); //it's mean to open the connection from database
//THE Question is right here, how i can put a byte array into database
//without using this method, a.k.a INSERT INTO, cause i have tried to search any
//solution in google, but i can't solve my problem
ContentValues values = new ContentValues();
values.put(image, img._lokasi_foto);
// Inserting Row
database.insert(Photo, null, values);
close(); // Closing database connection
}
and here's my image class
public class image {
public byte[] _lokasi_foto;
//this is getter
public byte[] getLokasi_foto() {
return _lokasi_foto;
}
//this is setter
public void setLokasi_foto(byte[] lokasi_foto) {
this._lokasi_foto = lokasi_foto;
}
and this the constructor
public image(byte[] lokasi_foto) {
this._lokasi_foto = lokasi_foto;
}
}
Can someone help me with this problem, cause i have been search in google, but i can't still solve my problem, Please Help...
Save the image in a local folder with the same name as your id. So now whenever you want to retrieve the image, just open id.jpg / id.png
private void saveToDB() {
SQLiteDatabase myDb;
String MySQL;
byte[] byteImage1 = null;
byte[] byteImage2 = null;
MySQL = "create table emp1(_id INTEGER primary key autoincrement, sample TEXT not null, audio BLOB);";
myDb = openOrCreateDatabase("Blob List", Context.MODE_PRIVATE, null);
myDb.execSQL(MySQL);
String s = myDb.getPath();
textView.append("\r\n" + s + "\r\n");
myDb.execSQL("delete from emp1");
ContentValues newValues = new ContentValues();
newValues.put("sample", "HI Hello");
try {
InputStream is = new FileInputStream("YOUR IMAGE PATH");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();
textView.append("\r\n" + bytes.length + "\r\n");
newValues.put("audio", bytes);
long ret = myDb.insert("emp1", null, newValues);
if (ret < 0)
textView.append("\r\n!!! Error add blob failed!!!\r\n");
} catch (IOException e) {
textView.append("\r\n!!! Error: " + e + "!!!\r\n");
}
Cursor cur = myDb.query("emp1", null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false) {
textView.append("\r\n" + cur.getString(1) + "\r\n");
cur.moveToNext();
}
// /////Read data from blob field////////////////////
cur.moveToFirst();
byteImage2 = cur.getBlob(cur.getColumnIndex("audio"));
// bmImage.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0,
// byteImage2.length));
textView.append("\r\n" + byteImage2.length + "\r\n");
cur.close();
myDb.close();
}
am use activity as a dialog.In that i have button to browse and select the image to show it in image view.
My Dialog activity code and browse image
public class Update_profile extends Activity{
private Uri mImageCaptureUri;
private static final int PICK_FROM_FILE = 1;
private View rootView;
Button save,browse_image;
ImageView profile_pic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(new ColorDrawable(0));
setContentView(R.layout.update_profile);
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
});
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
this.rootView=findViewById(R.id.update_profile_details);
profile_pic = (ImageView)findViewById(R.id.update_profile_picture);
save = (Button)findViewById(R.id.save);
browse_image = (Button)findViewById(R.id.browse_image);
browse_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
Bitmap bitmap = null;
String path = "";
if (requestCode == PICK_FROM_FILE) {
mImageCaptureUri = data.getData();
path = getRealPathFromURI(mImageCaptureUri); //from Gallery
Log.v("Path", ""+path);
if (path == null)
path = mImageCaptureUri.getPath(); //from File Manager
Log.v("Path", ""+path);
if (path != null)
bitmap = BitmapFactory.decodeFile(path);
} else {
path = mImageCaptureUri.getPath();
Log.v("Path", ""+path);
bitmap = BitmapFactory.decodeFile(path);
}
profile_pic.setImageBitmap(bitmap);
}
public String getRealPathFromURI(Uri contentUri) {
String [] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( contentUri, proj, null, null,null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#SuppressLint("NewApi")
#Override
public boolean onTouchEvent(MotionEvent event) {
Rect rect = new Rect();
rootView.getHitRect(rect);
if (!rect.contains((int)event.getX(), (int)event.getY())){
setFinishOnTouchOutside(false);
return true;
}
return false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
finish();
}
return true;
}
}
My manifest code to change the activity as a dialog
<activity
android:name="test.Update_profile"
android:excludeFromRecents="true"
android:launchMode="singleInstance"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Dialog"
android:windowSoftInputMode="stateHidden" >
</activity>
When am using above browse images code in ordinary activity means it fetch the images and show it in image view but in this dialog activity.its now able to pick the image.I want to pic the image from dialog activity.am not able to solve this issue.Can any one know please help me to solve this issue.
if u want to retrive direct from gallary then use this code
http://viralpatel.net/blogs/pick-image-from-galary-android-app/
this is my method for getting all file from sdcard and u just save this in one datacontroller class ohk dude
private void getallimages()
{
String[] STAR = { "*" };
final String[] columns = { MediaStore.Images.Thumbnails._ID , MediaStore.Images.Media.DATA};
final String orderBy = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
Cursor imagecursor = ((Activity) cntx).managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STAR, null, null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
int imgNameIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME);
int count = imagecursor.getCount();
for (int i = 0; i < count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
ImageItem imageItem = new ImageItem();
imageItem.id = id;
imageItem.filePath = imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA));
lastId = id;
imageItem.img = MediaStore.Images.Thumbnails.getThumbnail(cntx.getContentResolver(), id,MediaStore.Images.Thumbnails.MICRO_KIND, null);
imageItem.selection = false; //newly added item will be selected by default
controller.images.add(imageItem);
}
}
this is ImageItem wrapper class
public class ImageItem {
public boolean selection=true;
public int id;
public Bitmap img;
public String filePath;
public String fileType;
}
You can try this :
public class EMView extends Activity {
ImageView img,img1;
int column_index;
Intent intent=null;
// Declare our Views, so we can access them later
String logo,imagePath,Logo;
Cursor cursor;
//YOU CAN EDIT THIS TO WHATEVER YOU WANT
private static final int SELECT_PICTURE = 1;
String selectedImagePath;
//ADDED
String filemanagerstring;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img= (ImageView)findViewById(R.id.gimg1);
((Button) findViewById(R.id.Button01))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
}
//UPDATED
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
//OI FILE Manager
filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
img.setImageURI(selectedImageUri);
imagePath.getBytes();
TextView txt = (TextView)findViewById(R.id.title);
txt.setText(imagePath.toString());
Bitmap bm = BitmapFactory.decodeFile(imagePath);
img1.setImageBitmap(bm);
}
}
}
//UPDATED!
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
return cursor.getString(column_index);
}
}
In my app, I' using Tab. There are three tabs. In which 3rd tab is Activity group which has two activities. In first activity, there are two options for user. User can choose image from camera or from gallery. After selecting an image, user should move to child activity, which will display selected image in that activity. Till this app is working fine. But only problem here I'm facing is, image is not being cleared when I move back to parent activity from child activity. Means once I choose image from gallery/camera, user moves to child activity, and image is being displayed in child activity. Now when I press back button from child activity, user moves back to parent activity and again if user selects different image from galley/camera, that different image is not there in child activity. The previous image is there in child activity. Below is my code.
ABCGroup.java
public class ABCGroup extends ActivityGroup{
public static ABCGroup group;
private ArrayList<View> history;
View view;
int column_index;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.history = new ArrayList<View>();
group = this;
view = getLocalActivityManager().startActivity("ParentActivity", new Intent(ABCGroup.this, Tab1.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)).getDecorView();
replaceView(view);
}
public void replaceView(View v) {
history.add(v);
setContentView(v);
}
public void back() {
if(history.size() > 0)
{
history.remove(history.size()-1);
if(history.size()<=0)
{
finish();
}
else
{
setContentView(history.get(history.size()-1));
}
}
else
{
finish();
}
}
#Override
public void onBackPressed() {
ABCGroup.group.back();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK){
ABCGroup.group.back();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
InputStream stream = null;
if (requestCode == Tab1.REQUEST_ID && resultCode == Activity.RESULT_OK) {
try
{
stream = getContentResolver().openInputStream(data.getData());
Bitmap original = null;
original= BitmapFactory.decodeStream(stream);
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
}
catch (Exception e)
{
e.printStackTrace();
}
if (stream != null)
{
try
{
stream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
if (requestCode == 3 && resultCode == Activity.RESULT_OK)
{
getContentResolver().notifyChange(Tab1.mUri, null);
ContentResolver cr = getContentResolver();
try
{
Tab1.mPhoto = android.provider.MediaStore.Images.Media.getBitmap(cr, Tab1.mUri);
Second.bmp = Tab1.mPhoto;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
Tab1.mPhoto.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File direct = new File(Environment.getExternalStorageDirectory() + "/ABCGroup");
String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
Toast.makeText(getBaseContext(), "Time :" + mydate, 5000).show();
if(!direct.exists())
{
direct.mkdir();
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "/ABCGroup/image" + mydate +".jpg");
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
}
else
{
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "/ABCGroup/image" + mydate +".jpg");
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
}
View mview = ABCGroup.group.getLocalActivityManager().startActivity("activity3", new Intent(ABCGroup.this, Second.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)).getDecorView();
replaceView(mview);
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("data", cursor.getString(column_index) );
editor.commit();
View mview = ABCGroup.group.getLocalActivityManager().startActivity("activity3", new Intent(ABCGroup.this, Second.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)).getDecorView();
replaceView(mview);
return cursor.getString(column_index);
}
public void onResume()
{
super.onResume();
column_index = 0;
}
}
Tab1.java
public class Tab1 extends ActivityGroup {
Button gallery, camera;
private ArrayList<View> myActivityHistory;
ImageView iv;
private static final int TAKE_PICTURE = 3;
public static final int REQUEST_ID = 1;
private static final int HALF = 2;
public static Uri mUri;
public static Bitmap mPhoto;
int i = 0;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.tab1);
View viewToLoad = LayoutInflater.from(Tab1.this.getParent()).inflate(R.layout.tab1, null);
Tab1.this.setContentView(viewToLoad);
myActivityHistory = new ArrayList<View>();
gallery = (Button)viewToLoad.findViewById(R.id.gallery);
camera = (Button)viewToLoad.findViewById(R.id.camera);
iv = (ImageView)viewToLoad.findViewById(R.id.iv);
gallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
ABCGroup.group.startActivityForResult(intent, REQUEST_ID);
}
});
camera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
File f = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
mUri = Uri.fromFile(f);
ABCGroup.group.startActivityForResult(i, TAKE_PICTURE);
}
});
}
public void replaceContentView(String id, Intent newIntent)
{
View mview = ABCGroup.group.getLocalActivityManager().startActivity(id,newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)).getDecorView();
ABCGroup.group.replaceView(mview);
}
}
Second.java
public class Second extends Activity {
public static Bitmap bmp;
Bitmap myBitmap;
String path;
ImageView iv;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
View viewToLoad = LayoutInflater.from(Second.this.getParent()).inflate(R.layout.second, null);
Second.this.setContentView(viewToLoad);
Button btn = (Button)viewToLoad.findViewById(R.id.button1);
iv = (ImageView)viewToLoad.findViewById(R.id.imageView1);
iv.setImageBitmap(bmp);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
path = preferences.getString("data", "");
File imgFile = new File(path);
if(imgFile.exists()){
Toast.makeText(getBaseContext(), "" + path, 1000).show();
myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
iv.setImageBitmap(myBitmap);
}
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ABCGroup.group.back();
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(Second.this, Tab1.class);
Tab1 parentActivity = (Tab1)getParent();
parentActivity.replaceContentView("Profile", new Intent(Second.this, Tab1.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY ) );
}
public void onResume()
{
super.onResume();
}
}
Finally I got the answer
public void onResume()
{
super.onResume();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
path = preferences.getString("data", "");
imgFile = new File(path);
Toast.makeText(getBaseContext(), "" + path, 2000).show();
if(imgFile.exists())
{
myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
iv.setImageBitmap(myBitmap);
}
}