How can I update Gallery After a Photo had been taken? - android

I created a program to capture a photo but when i look at it in the Photo Gallery it does not appear immediately.
I Already used the command provided in the other questions in this site which is similar to this Code:
"sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));"
this is my entire code:
enter code here
public class PicturesActivity extends AppCompatActivity {
public static final int REQUEST_TAKE_PHOTO = 1;
public static final String ACCOUNTNUM = "AccountNum";
public static final String METERNO = "MeterNo";
public static final int CAMERA_PERMISSION_REQUEST_CODE = 4192;
private static final String ALBUM_NAME = "DailySelfie";
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private static final String CAMERA_DIR = "/dcim/";
public static final String FILE_PATH_EXTRA = "image_currentPath";
private static final long INITIAL_ALARM_DELAY = 2 * 60 * 1000L;
public static final int REQUEST_CODE = 228;
private static final int CAMERA_REQUEST_CODE = REQUEST_CODE;
private ImageAdapter imageAdapter = null;
private String mCurrentPhotoPath = null;
private File capturedImage;
private AlarmManager alarmManager;
private Intent notificationReceiverIntent;
private PendingIntent notificationReceiverPendingIntent;
private ListView pictureList;
private SearchView searchText;
private File pictureFile;
private int pictureCounter = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pictures);
this.pictureList = (ListView) findViewById(R.id.picture_list);
this.searchText = (SearchView) findViewById(R.id.edit_image_search);
this.alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
this.imageAdapter = new ImageAdapter(getApplicationContext());
notificationReceiverIntent = new Intent(PicturesActivity.this, SelfieBroadCastReceiver.class);
notificationReceiverPendingIntent = PendingIntent.getBroadcast(PicturesActivity.this, 0, notificationReceiverIntent, 0);
getSupportActionBar();
this.pictureList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ImageRecord imageRecord = imageAdapter.getItem(position);
Intent picDetailIntent = new Intent(getApplicationContext(), PictureDetailActivity.class);
picDetailIntent.putExtra(FILE_PATH_EXTRA, imageRecord.getFullPath());
startActivity(picDetailIntent);
}
});
this.searchText.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
//imageAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
imageAdapter.getFilter().filter(newText);
return false;
}
});
try {
this.pictureList.setAdapter(imageAdapter);
}catch (Exception e){
Toast.makeText(getApplication(),e.toString(),Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
renameFile(this.capturedImage);
}
}
#Override
protected void onResume() {
super.onResume();
this.setUpPicList();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.pictures_menu, menu);
return true;
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.show_camera:
if(checkSelfPermission(Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)==PackageManager.PERMISSION_GRANTED){
try {
dispatchTakePictureIntent();
}catch (IOException e){}
}else{
String[] permissionRequest = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissionRequest, CAMERA_PERMISSION_REQUEST_CODE);
}
return true;
case R.id.set_alarm:
setAlarm();
return true;
case R.id.cancel_alarm:
cancelAlarm();
return true;
default:
return false;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==CAMERA_PERMISSION_REQUEST_CODE){
if(grantResults[0] == PackageManager.PERMISSION_GRANTED & grantResults[1]== PackageManager.PERMISSION_GRANTED){
try {
dispatchTakePictureIntent();
}catch(IOException e){}
}else{
viewSnackBar(getString(R.string.camera_needed_permission));
}
}
}
private void dispatchTakePictureIntent() throws IOException{
pictureFile = createImageFiles();
Uri uriFile = FileProvider.getUriForFile(this, getApplicationContext().getPackageName()+ ".provider", pictureFile);
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,uriFile);
takePictureIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(pictureFile)));
scanMedia(pictureFile.toString());
}
private File createImageFiles() {
SharedPreferences prefs = getSharedPreferences(ACCOUNTNUM, MODE_PRIVATE);
SharedPreferences meterNum = getSharedPreferences(METERNO, MODE_PRIVATE);
final String accountNumber = prefs.getString("accountNum", null);
final String MeterNumber = meterNum.getString("MeterNo", null);
File picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File imageFile = new File(picturesDirectory, accountNumber + "-" + MeterNumber.trim() + "-"+ pictureCounter + ".JPG");
pictureCounter++;
return imageFile;
}
private void scanMedia(String path) {
File file = new File(path);
Uri uri = Uri.fromFile(file);
Intent scanFileIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
sendBroadcast(scanFileIntent);
}
public void viewSnackBar(String message){
View parentLayout = findViewById(android.R.id.content);
Snackbar.make(parentLayout, message, Snackbar.LENGTH_LONG).show();
}
private void renameFile(File file) {
SharedPreferences prefs = getSharedPreferences(ACCOUNTNUM, MODE_PRIVATE);
final String accountNumber = prefs.getString("accountNum", null);
final Dialog dialog = new Dialog(PicturesActivity.this);
dialog.setContentView(R.layout.file_prompt);
final EditText editText = (EditText) dialog.findViewById(R.id.editTextDialogUserInput);
final Button button = (Button) dialog.findViewById(R.id.saveButton);
final File oldFile = file;
try {
editText.setText(accountNumber);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(editText.getText().toString())) {
String fileName = editText.getText().toString().toLowerCase() + "-";
try {
File newFile = File.createTempFile(fileName, JPEG_FILE_SUFFIX, getAlbumDir());
oldFile.renameTo(newFile);
setUpPicList();
dialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
dialog.show();
}catch (Exception e){
Toast.makeText(getApplication(), e.toString(),Toast.LENGTH_SHORT).show();
}
}
private File getAlbumDir(){
File storageDir = null;
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
storageDir = getAlbumStorageDir();
if(storageDir != null){
if(!storageDir.mkdirs()){
if(!storageDir.exists()){
Log.d("DailySelfie", "Failed to create directory");
return null;
}
}
}
} else {
Log.v("DailySelfie", "External Storage is not mounted READ/WRITE");
}
return storageDir;
}
///*************************
private File getAlbumStorageDir(){
File picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return picturesDirectory;
//return new File(Environment.getExternalStorageDirectory() + CAMERA_DIR + ALBUM_NAME);
}
private void galleryAddPic(){
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File file = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void setUpPicList(){
imageAdapter.removeAllViews();
File albumFile = getAlbumDir();
if(albumFile.isDirectory() && albumFile.exists()){
File[] files = albumFile.listFiles();
for(File file : files){
ImageRecord imageRecord = new ImageRecord(file);
imageAdapter.add(imageRecord);
}
}
}
}

Related

how can i store gallery image in application directory

i have got the image directly from the camera , gallery to the image view in my app its all working fine.
Now what I want is to save this image from Image View to the application directory and also access it when required.
//You Can try This
File myDir = new File(Environment.getExternalStorageDirectory().toString() + "/yourDirectoryname");
myDir.mkdirs();
File file = new File(myDir, yourImagePath);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
imgBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
public class EditProfile extends AppCompatActivity {
ImageView imageView;
EditText Name,Email,MobileNo;
public static int count = 0;
String loginid;
Bitmap bitmap;
private static final int CAMERA_REQUEST = 1888;
String picturePath;
static int i=0;
private final int CAMERA_RESULT = 1;
private final String Tag = getClass().getName();
byte[] image = null;
Button button1;
static File out;
String path1;
ImageView imageView1;
Bitmap photo ;
byte[] b=null;
Button EditProfile;
String Username;
String name;
String email;
String Imgpath;
String Imgpath1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
EditProfile=(Button)findViewById(R.id.edit_profile);
Imgpath=getSharedPreferences("Bytearray",0).getString("Bytearray",null);
Imgpath1=getSharedPreferences("uri",0).getString("uri",null);
imageView=(ImageView)findViewById(R.id.profile_photo);
EditProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(EditProfile.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
PackageManager pm = getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, MyFileContentProvider.CONTENT_URI);
startActivityForResult(i, CAMERA_RESULT);
} else {
Toast.makeText(getBaseContext(), "Camera is not available", Toast.LENGTH_LONG).show();
}
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
out = new File(getFilesDir(), "newImage.jpg");
if(!out.exists()) {
Toast.makeText(getBaseContext(),
"Error while capturing image", Toast.LENGTH_LONG)
.show();
return;
}
Bitmap mBitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
String path=out.getAbsolutePath();
getSharedPreferences("path",0).edit().putString("path",path).commit();
imageView.setImageBitmap(mBitmap);
}
else if (requestCode == 2) {
imageView.setImageURI(selectedImage);
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();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
// imageView.setImageBitmap(yourSelectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bitmap image=BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
imageView.setImageBitmap(image);
}
}
}
Initiate the camera intent like this by creating a file of known path,and after the image capture Your image appears in that path:
Uri capturedImageUri;//global variable
private void initiateImageCapture() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
capturedImageUri = Uri.fromFile(photoFile);
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile == null || capturedImageUri == null) {
Utils.showLongToast(getActivity(), "error");
} else {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null)
startActivityForResult(takePictureIntent, Constants.INTENT_IMAGE_CAPTURE);
else
Utils.showLongToast(getActivity(), "try again);
}
}
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return image;
}

Android crop image while asking select image either gallery or camera

below is my code, can anyone help me, where can i put crop image code when asked to select image from gallery or camera. thanks in advance.
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
//public static final String UPLOAD_URL = "http://192.168.0.137/image_json /upload.php";
public static final String URL_ADD = "http://192.168.0.104/image_json/addEmp.php";
public static final String URL_GET_ALL = "http://192.168.0.137/image_json/getAllEmp.php";
public static final String URL_GET_EMP = "http://192.168.0.137/image_json/getEmp.php?id=";
public static final String URL_UPDATE_EMP = "http://192.168.0.137/image_json/updateEmp.php";
public static final String URL_DELETE_EMP = "http://192.168.0.137/image_json/deleteEmp.php?id=";
// Keys that will be used to send the request to php scripts
public static final String KEY_EMP_ID = "id";
public static final String KEY_EMP_NAME = "name";
public static final String KEY_EMP_DESG = "desg";
public static final String KEY_EMP_SAL = "salary";
// JSON Tags
public static final String TAG_JSON_ARRAY = "result";
public static final String TAG_ID = "id";
public static final String TAG_NAME = "name";
public static final String TAG_DESG = "desg";
public static final String TAG_SAL = "salary";
// employee id to pass with intent
public static final String EMP_ID = "emp_id";
public static final String UPLOAD_KEY = "image";
private int PICK_IMAGE_REQUEST = 1;
int REQUEST_CAMERA = 0;
private Button buttonChoose;
private Button buttonUpload;
// private Button buttonView;
private EditText editTextName;
private EditText editTextDesg;
private EditText editTextSal;
private Button buttonAdd;
private Button buttonView;
private ImageView imageView;
private Bitmap bitmap;
private Uri filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextDesg = (EditText) findViewById(R.id.editTextDesg);
editTextSal = (EditText) findViewById(R.id.editTextSalary);
buttonAdd = (Button) findViewById(R.id.buttonAdd);
buttonView = (Button) findViewById(R.id.buttonView);
// Setting listeners to button
buttonAdd.setOnClickListener(this);
buttonView.setOnClickListener(this);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
// buttonView = (Button) findViewById(R.id.buttonViewImage);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
// buttonView.setOnClickListener(this);
}
private void addEmployee() {
final String name = editTextName.getText().toString().trim();
final String desg = editTextDesg.getText().toString().trim();
final String sal = editTextSal.getText().toString().trim();
class AddEmployee extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Adding...",
"Wait...", false, false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... v)
{
String uploadImage = getStringImage(bitmap);
HashMap<String, String> params = new HashMap<String, String>();
params.put(KEY_EMP_NAME, name);
params.put(KEY_EMP_DESG, desg);
params.put(KEY_EMP_SAL, sal);
params.put(UPLOAD_KEY, uploadImage);
RequestHandler rh = new RequestHandler();
String res = rh.sendPostRequest(URL_ADD, params);
Log.i("result",""+res);
return res;
}
}
AddEmployee ae = new AddEmployee();
ae.execute();
}
#SuppressLint("NewApi")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(
getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
/*
* Bundle extras = data.getExtras(); Bitmap photo = (Bitmap)
* extras.get("data");
*/
bitmap = getImageFileFromSDCard("abc.jpg");
imageView.setImageBitmap(bitmap);
} else {
Toast.makeText(getApplicationContext(), "bundal is null",
Toast.LENGTH_LONG).show();
}
}
private Bitmap getImageFileFromSDCard(String filename) {
Bitmap bitmap = null;
File outputFile = Environment.getExternalStorageDirectory();
File file = new File(outputFile, filename);
Log.i("pathstore", "" + file);
try {
FileInputStream fis = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bitmap;
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
selectImage();
// showFileChooser();
}
if (v == buttonAdd) {
addEmployee();
}
}
private void viewImage() {
// startActivity(new Intent(this, ImageListView.class));
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
String userChoosenTask = "Take Photo";
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
String userChoosenTask = "Choose from Library";
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File out = Environment.getExternalStorageDirectory();
out = new File(out, "abc.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(out));
startActivityForResult(intent, REQUEST_CAMERA);
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"),
PICK_IMAGE_REQUEST);
}
}
You can do cropping part in onActivityResult method as it is called just after you select photo from gallery or camera.
I hope this answer will help you.
Use your Intent like this.
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 128);
cropIntent.putExtra("outputY", 128);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, CROP_PIC_REQUEST_CODE);
Good Luck!

Android - Take a picture from the Camera and save it to the internal storage

I have been stuck on this problem for a while now.
I am trying to take a picture with the Camera and save the full size picture directly into the internal memory.
I can save to the external storage without a glitch, but for some reason I cannot get it to work for the internal memory.
The solution below ONLY saves the small picture returned by the data object, and not the full-size picture.
It seems that the camera does not retrieve the full size picture, or that when I use file functions (new File, FileOutputStream...), Android is not retrieving the image from the camera Intent (shows a blank image).
I read all the forums, tutorials and tried different ways of achieving this, but I have not found the answer. I can't be the only one trying to do this.
Could you please help me with this problem?
Thanks!
Here is my code:
public class AddItem extends Fragment {
ListCell cell = new ListCell();
View view;
private Bitmap mImageBitmap;
protected myCamera cameraObject = null;
private Button saveBtn;
private Button cancelBtn;
DBSchema dbSchema;
protected boolean bdisplaymessage;
protected boolean ExternalStorage = false;
public AddItem(){
}
private class ListCell{
private EditText total;
private ImageView mImageView;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.add_item, container,
false);
saveBtn = (Button) rootView.findViewById(R.id.SaveItem);
cancelBtn = (Button) rootView.findViewById(R.id.CancelItem);
cameraObject = new myCamera();
cell.total = (EditText) rootView.findViewById(R.id.item_total_Value);
cell.mImageView = (ImageView) rootView.findViewById(R.id.item_logo);
cell.mImageView.setImageResource(R.drawable.camera_icon);
cell.mImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
saveBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//save item to internal db
//get names of columns from db
bdisplaymessage = true;
dbSchema = new DBSchema();
Transaction transac = dbSchema.new Transaction();
Context context = getActivity().getApplicationContext();
//put values in content values
ContentValues values = new ContentValues();
values.put(transac.Total,cell.total.getText().toString());
StatusData statusData = ((MyFunctions) getActivity().getApplication()).statusData;
long nInsert = 0;
nInsert = statusData.insert(values,dbSchema.table_transaction);
if(nInsert!=0){
Toast.makeText(context, "inserted " + nInsert , Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(context, "not inserted " + nInsert , Toast.LENGTH_LONG).show();
}
}
});
cancelBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//redirect to home page
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new LoadMenu()).commit();
}
});
return rootView;
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(cameraObject.BITMAP_STORAGE_KEY, mImageBitmap);
outState.putBoolean(cameraObject.IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
super.onSaveInstanceState(outState);
}
//take picture
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//takePictureIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String mCurrentPhotoPath;
File f = null;
try {
//create image
f = cameraObject.setUpPhotoFile(getResources().getString(R.string.album_name),ExternalStorage, getActivity().getApplicationContext());
cameraObject.setCurrentPath(f.getAbsolutePath());
Log.d("uri_fromfile",Uri.fromFile(f).toString());
//uncomment the line below when ExternalStorage=true
//takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
startActivityForResult(takePictureIntent, cameraObject.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestcode, int resultCode, Intent data) {
if (requestcode == cameraObject.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == getActivity().RESULT_OK) {
handleCameraPhoto(data);
}
}
private void handleCameraPhoto(Intent data) {
setPic(data);
galleryAddPic();
}
private void setPic(Intent data) {
/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target bitmap into which the file is decoded */
/* Get the size of the ImageView */
int targetW = cell.mImageView.getWidth();
int targetH = cell.mImageView.getHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(cameraObject.getCurrentPath(), bmOptions);
Log.d("image_path",cameraObject.getCurrentPath());
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW/targetW, photoH/targetH);
}
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = null;
if(ExternalStorage){
bitmap = BitmapFactory.decodeFile(cameraObject.getCurrentPath(), bmOptions);
}
else{
File internalStorage = getActivity().getApplicationContext().getDir("imageDir", Context.MODE_PRIVATE);
File reportFilePath = new File(internalStorage, cameraObject.JPEG_FILE_PREFIX +"hello" + ".jpg");
String picturePath = reportFilePath.toString();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(reportFilePath);
bitmap = (Bitmap) data.getExtras().get("data");
bitmap.compress(Bitmap.CompressFormat.PNG, 100 /*quality*/, fos);
fos.close();
}
catch (Exception ex) {
Log.i("DATABASE", "Problem updating picture", ex);
picturePath = "";
}
/* below is a bunch of options that I tried with decodefile, FileOutputStream... none seems to work */
//File out = new File(getActivity().getApplicationContext().getFilesDir(),cameraObject.JPEG_FILE_PREFIX + "hello");
//bitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
//FileOutputStream fos = null;
//try {
//fos = new FileOutputStream(new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX).getAbsolutePath());
//bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
// Use the compress method on the BitMap object to write image to the OutputStream
//fos.close();
//Bitmap bitmap = null;
/*try{
FileInputStream fis = new FileInputStream(new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX).getAbsolutePath());
//getActivity().getApplicationContext().openFileInput(cameraObject.getCurrentPath());
bitmap = BitmapFactory.decodeStream(fis);
//
fis.close();
}
catch(Exception e){
Log.d("what?",e.getMessage());
bitmap = null;
}*/
/*} catch (Exception e) {
e.printStackTrace();
}*/
/*File mypath=new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX);
bitmap = BitmapFactory.decodeFile(mypath.getAbsolutePath());*/
//bitmap = (Bitmap) data.getExtras().get("data");
}
/* Associate the Bitmap to the ImageView */
cell.mImageView.setImageBitmap(bitmap);
cell.mImageView.setVisibility(View.VISIBLE);
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(cameraObject.mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
}
My other class called myCamera handles the camera:
public class myCamera extends MainMenu{
private ImageView mImageView;
private Bitmap mImageBitmap;
static final String BITMAP_STORAGE_KEY = "viewbitmap";
static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
protected static final int ACTION_TAKE_PHOTO_B = 1;
protected static final int ACTION_TAKE_PHOTO_S = 2;
protected int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = MEDIA_TYPE_IMAGE;
protected Uri fileUri;
protected String mCurrentPhotoPath;
protected static final String JPEG_FILE_PREFIX = "IMG_";
protected static final String JPEG_FILE_SUFFIX = ".jpg";
private static final String CAMERA_DIR = "/dcim/";
protected String mAlbumName;
protected AlbumStorageDirFactory mAlbumStorageDirFactory = null;
protected String getAlbumName() {
return "test";
}
protected String getCurrentPath(){
return mCurrentPhotoPath;
}
protected void setCurrentPath(String mCurrentPhotoPath){
this.mCurrentPhotoPath=mCurrentPhotoPath;
}
public File getAlbumStorageDir(String albumName) {
return new File (
Environment.getExternalStorageDirectory()
+ CAMERA_DIR
+ albumName
);
}
private File getAlbumDir() {
File storageDir = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
} else {
mAlbumStorageDirFactory = new BaseAlbumDirFactory();
}
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("CameraSample", "failed to create directory");
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.base_for_drawer);
mAlbumName = getIntent().getStringExtra("AlbumName");
}
public myCamera(){
}
//save full size picture
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File storageDir = getAlbumDir();
File image = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, storageDir);
return image;
}
protected File setUpPhotoFile(String albumName, boolean ExternalStorage, Context context) throws IOException {
mAlbumName = albumName;
File f =null;
if(ExternalStorage){
f = createImageFile();
}
else{
f = saveToInternalSorage(context);
}
// Save a file: path for use with ACTION_VIEW intents
if(f !=null){
mCurrentPhotoPath = f.getAbsolutePath();
}
return f;
}
private File saveToInternalSorage(Context context) throws IOException{
ContextWrapper cw = new ContextWrapper(context);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + "hello";
// path to /data/data/yourapp/app_data/imageDir
File directory = context.getDir("imageDir", Context.MODE_PRIVATE);
File mypath=new File(directory,imageFileName + JPEG_FILE_SUFFIX);
/*below is a bunch of options that I tried*/
//File directory =context.getFilesDir();
//File directory = new File(getFilesDir(),imageFileName,Context.MODE_PRIVATE);
// Create imageDir
//File image = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, storageDir);
//File mypath = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, directory);
//return image;
return mypath;
}
}
I found the solution! I did not use the native camera application, but rather created my own camera class and use the data sent back by the camera via a callback. Works smoothly!

Save output image from layout on Android

i want to save output image from layout[redline],
the program, take image picture from camera -> save in sdcard -> load image gray and original to layout. i want to save gray and original image became one image like on the red line.
public class PhotoIntentActivity extends Activity {
private static final String TAG = "Saliency";
private static final int ACTION_TAKE_PHOTO_B = 1;
private static final String BITMAP_STORAGE_KEY = "viewbitmap";
private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
private ImageView mImageView;
private ImageView mImageView2;
private Bitmap mImageBitmap;
private View view;
private String mCurrentPhotoPath;
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private AlbumStorageDirFactory mAlbumStorageDirFactory = null;
/* Photo album for this application */
private String getAlbumName() {
return getString(R.string.album_name);
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = mAlbumStorageDirFactory.getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("ImageDataset", "failed to create directory");
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
return imageF;
}
private File setUpPhotoFile() throws IOException {
File f = createImageFile();
mCurrentPhotoPath = f.getAbsolutePath();
return f;
}
private void setPic() {
/* Decode the JPEG file into a Bitmap */
Mat mInput = new Mat();
mInput = Highgui.imread(mCurrentPhotoPath, CvType.CV_8UC1);
Mat mRgba = new Mat(mInput.rows()/4, mInput.cols()/4, CvType.CV_64FC1);
Imgproc.resize(mInput, mInput, mRgba.size());
Bitmap resultBitmap = Bitmap.createBitmap(mInput.cols(), mInput.rows(),Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mInput, resultBitmap);
//
Bitmap ImageAsli= BitmapFactory.decodeFile(mCurrentPhotoPath);
Bitmap ImageAsliResize = Bitmap.createScaledBitmap(ImageAsli, ImageAsli.getWidth(), ImageAsli.getHeight(), false);
/* Associate the Bitmap to the ImageView */
mImageView.setImageBitmap(resultBitmap);
mImageView2.setImageBitmap(ImageAsliResize);
mImageView.setVisibility(View.VISIBLE);
mImageView2.setVisibility(View.VISIBLE);
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
switch(actionCode) {
case ACTION_TAKE_PHOTO_B:
File f = null;
try {
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
break;
default:
break;
} // switch
startActivityForResult(takePictureIntent, actionCode);
}
private void handleBigCameraPhoto() {
if (mCurrentPhotoPath != null) {
setPic();
galleryAddPic();
mCurrentPhotoPath = null;
}
}
Button.OnClickListener mTakePicOnClickListener =
new Button.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent(ACTION_TAKE_PHOTO_B);
}
};
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
// Load native library after(!) OpenCV initialization
;
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageView = (ImageView) findViewById(R.id.imageView1);
mImageView2 = (ImageView) findViewById(R.id.imageView2);
mImageBitmap = null;
Button picBtn = (Button) findViewById(R.id.btnIntend);
setBtnListenerOrDisable(
picBtn,
mTakePicOnClickListener,
MediaStore.ACTION_IMAGE_CAPTURE
);
//minimal versi froyo
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
} else {
mAlbumStorageDirFactory = new BaseAlbumDirFactory();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_TAKE_PHOTO_B: {
if (resultCode == RESULT_OK) {
handleBigCameraPhoto();
}
break;
} // ACTION_TAKE_PHOTO_B
} // switch
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
mImageView.setImageBitmap(mImageBitmap);
mImageView.setVisibility(
savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
}
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private void setBtnListenerOrDisable(
Button btn,
Button.OnClickListener onClickListener,
String intentName
) {
if (isIntentAvailable(this, intentName)) {
btn.setOnClickListener(onClickListener);
} else {
btn.setText(
getText(R.string.cannot).toString() + " " + btn.getText());
btn.setClickable(false);
}
}
#Override
public void onResume()
{
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_8, this, mLoaderCallback);
}
}
You can get a "screenshot" of any view (including your parent layout) by temporarily enabling the drawing cache on it with setDrawingCacheEnabled() and then calling getDrawingCache() to retrieve a Bitmap of the view. Don't forget to disable the drawing cache after saving the image to improve performance. Save the bitmap to disk using the Bitmap.compress() method.
However please note that the size of your bitmap image will then depend on the size of the device screen. You can get more control by drawing your images directly to a Canvas backed by a mutable Bitmap instead of using a visible layout as source.

Image doesn't change in child activity using Activitygroup in android

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);
}
}

Categories

Resources