I am trying to embed a cropper through a library in the Main activity of ABBYY Cloud OCR sample code. But no matter how hard I try, instead of executing the crop-code, it always jumps on to the next activity. Why is this happening?
package bahadur.translateit;
import abbyy.ocrsdk.android.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.net.*;
import java.io.*;
import eu.janmuller.android.simplecropimage.CropImage;
import android.os.Environment;
import android.provider.MediaStore;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
public class MainActivity extends Activity {
private final int TAKE_PICTURE = 0;
private final int SELECT_FILE = 1;
private String resultUrl = "result.txt";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void captureImageFromSdCard( View view ) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, SELECT_FILE);
}
public static final int MEDIA_TYPE_IMAGE = 1;
private static Uri getOutputMediaFileUri(){
return Uri.fromFile(getOutputMediaFile());
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "TranlateIt!");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "image.jpg" );
return mediaFile;
}
public void captureImageFromCamera( View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
Uri fileUri = getOutputMediaFileUri(); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK)
return;
String imageFilePath = null;
switch (requestCode) {
case TAKE_PICTURE:
imageFilePath = getOutputMediaFileUri().getPath();
// the following code for crop does not execute
Intent intent = new Intent(this, CropImage.class);
intent.putExtra(CropImage.IMAGE_PATH, imageFilePath);
intent.putExtra(CropImage.SCALE, true);
intent.putExtra("outputX", 200); //Set this to define the max size of the output bitmap
intent.putExtra("outputY", 150); //Set this to define the max size of the output bitmap
intent.putExtra(CropImage.ASPECT_X, 0);
intent.putExtra(CropImage.ASPECT_Y, 0);
break;
case SELECT_FILE:
Uri imageUri = data.getData();
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cur = managedQuery(imageUri, projection, null, null, null);
cur.moveToFirst();
imageFilePath = cur.getString(cur.getColumnIndex(MediaStore.Images.Media.DATA));
// same goes for the following chunk of code
Intent intet = new Intent(this, CropImage.class);
intet.putExtra(CropImage.IMAGE_PATH, imageFilePath);
intet.putExtra(CropImage.SCALE, true);
intet.putExtra("outputX", 200); //Set this to define the max size of the output bitmap
intet.putExtra("outputY", 150); //Set this to define the max size of the output bitmap
intet.putExtra(CropImage.ASPECT_X, 0);
intet.putExtra(CropImage.ASPECT_Y, 0);
break;
}
this runs instead
String lastfilepath = imageFilePath;
//Remove output file
deleteFile(resultUrl);
Intent results = new Intent( this, ResultsActivity.class);
results.putExtra("IMAGE_PATH", lastfilepath);
results.putExtra("RESULT_PATH", resultUrl);
startActivity(results);
}
}
from my comments, i mean somethign like this:
case TAKE_PICTURE:
imageFilePath = getOutputMediaFileUri().getPath();
Intent intent = new Intent(this, CropImage.class);
intent.putExtra(CropImage.IMAGE_PATH, imageFilePath);
intent.putExtra(CropImage.SCALE, true);
intent.putExtra("outputX", 200); //Set this to define the max size of the output bitmap
intent.putExtra("outputY", 150); //Set this to define the max size of the output bitmap
intent.putExtra(CropImage.ASPECT_X, 0);
intent.putExtra(CropImage.ASPECT_Y, 0);
startActivity(intent);// THIS is the line you are missing!
Related
I usually don't work with images. I tried it. App will onBttnClick show gallery and user can choose picture and he has to crop it. It will save great but I want to save it and use cropped image until user change it.
So please can you tell me how can I save image for later use ?
Here is code in Activity
public void onImage(View view){
//Přechod do třídy GalleryUtil
Intent gallery_Intent = new Intent(getApplicationContext(), GalleryUtil.class);
startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
}
//Vyhodnocení zadaných údajů
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_ACTIVITY_CODE) {
if(resultCode == Activity.RESULT_OK){
String picturePath = data.getStringExtra("picturePath");
performCrop(picturePath);
}
}
if (requestCode == RESULT_CROP ) {
if(resultCode == Activity.RESULT_OK){
Bundle extras = data.getExtras();
Bitmap selectedBitmap = extras.getParcelable("data");
ImageView imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(getCroppedBitmap(selectedBitmap));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
String path = Environment.getExternalStorageDirectory().getAbsolutePath() +"/images"; // save to SD Card in images folder. Make sure path is there !
OutputStream fOut = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
File file = new File(path, "Cropped_Image_"+currentDateandTime+".jpg"); // the File to save to
try {
fOut = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap pictureBitmap = getCroppedBitmap(selectedBitmap); // Using the cropped bitmap.
pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close(); // do not forget to close the stream
} catch (IOException e) {
e.printStackTrace();
}
try {
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
private void performCrop(String picUri) {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
File f = new File(picUri);
Uri contentUri = Uri.fromFile(f);
cropIntent.setDataAndType(contentUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 280);
cropIntent.putExtra("outputY", 280);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, RESULT_CROP);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
public Bitmap getCroppedBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,
bitmap.getWidth() / 2, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
}
And here is my GalleryUtil code
public class GalleryUtil extends Activity{
private final static int RESULT_SELECT_IMAGE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String TAG = "GalleryUtil";
String mCurrentPhotoPath;
File photoFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
//Pick Image From Gallery
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_SELECT_IMAGE);
}catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case RESULT_SELECT_IMAGE:
if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
try{
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 picturePath = cursor.getString(columnIndex);
//return Image Path to the Main Activity
Intent returnFromGalleryIntent = new Intent();
returnFromGalleryIntent.putExtra("picturePath",picturePath);
setResult(RESULT_OK,returnFromGalleryIntent);
finish();
}catch(Exception e){
e.printStackTrace();
Intent returnFromGalleryIntent = new Intent();
setResult(RESULT_CANCELED, returnFromGalleryIntent);
finish();
}
}else{
Log.i(TAG,"RESULT_CANCELED");
Intent returnFromGalleryIntent = new Intent();
setResult(RESULT_CANCELED, returnFromGalleryIntent);
finish();
}
break;
}
}
}
Error:
12-04 23:00:25.521 1728-1728/com.tomiktuts.tom.mygirlfriendapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.tomiktuts.tom.mygirlfriendapp, PID: 1728
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=400, result=-1, data=Intent { (has extras) }} to activity {com.tomiktuts.tom.mygirlfriendapp/com.tomiktuts.tom.mygirlfriendapp.DashBoardActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:4067)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4110)
at android.app.ActivityThread.access$1400(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1498)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Caused by: java.lang.NullPointerException
at android.graphics.Bitmap.compress(Bitmap.java:1143)
at com.tomiktuts.tom.mygirlfriendapp.DashBoardActivity.onActivityResult(DashBoardActivity.java:161)
at android.app.Activity.dispatchActivityResult(Activity.java:6549)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4063)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4110)
at android.app.ActivityThread.access$1400(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1498)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Thank you for help. Have a nice day.
You should use the Bitmap.compress() method to save a Bitmap as a file. It will compress your picture and push it into an OutputStream.
I think the best thing would be to add below logic just when imageview is set using getCroppedBitmap(Bitmap bitmap) (which is called after performCrop(String picUri) is performed).
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
OutputStream fOut = null;
// Lets save using date
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
String fileName = "Cropped_Image_" + currentDateandTime + ".png";
// Not sure if the / is on the path or not
File file = new File(baseDir + File.separator + fileName); // the File to save to
fOut = new FileOutputStream(file);
Bitmap pictureBitmap = getCroppedBitmap(selectedBitmap); // Using the cropped bitmap.
pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
fOut.flush();
fOut.close(); // do not forget to close the stream
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
Hope this helps !
Remember to add below to manifest, if you have not :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Complete Working Code :
GalleryUtil.java
package com.example.user.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.os.Bundle;
import android.util.Log;
import java.io.File;
public class GalleryUtil extends Activity {
private final static int RESULT_SELECT_IMAGE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String TAG = "GalleryUtil";
String mCurrentPhotoPath;
File photoFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
//Pick Image From Gallery
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_SELECT_IMAGE);
}catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case RESULT_SELECT_IMAGE:
if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
try{
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 picturePath = cursor.getString(columnIndex);
//return Image Path to the Main Activity
Intent returnFromGalleryIntent = new Intent();
returnFromGalleryIntent.putExtra("picturePath",picturePath);
setResult(RESULT_OK,returnFromGalleryIntent);
finish();
}catch(Exception e){
e.printStackTrace();
Intent returnFromGalleryIntent = new Intent();
setResult(RESULT_CANCELED, returnFromGalleryIntent);
finish();
}
}else{
Log.i(TAG, "RESULT_CANCELED");
Intent returnFromGalleryIntent = new Intent();
setResult(RESULT_CANCELED, returnFromGalleryIntent);
finish();
}
break;
}
}
}
MainActivity :
package com.example.user.myapplication;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends Activity {
private final static int GALLERY_ACTIVITY_CODE = 100;
public static final int RESULT_CROP = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// onImage can be called with anything doesn't matter :
onImage(null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onImage(View view){
//Přechod do třídy GalleryUtil
Intent gallery_Intent = new Intent(getApplicationContext(), GalleryUtil.class);
startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
}
//Vyhodnocení zadaných údajů
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_ACTIVITY_CODE) {
if(resultCode == Activity.RESULT_OK){
String picturePath = data.getStringExtra("picturePath");
performCrop(picturePath);
}
}
if (requestCode == RESULT_CROP ) {
if(resultCode == Activity.RESULT_OK){
Bundle extras = data.getExtras();
Bitmap selectedBitmap = extras.getParcelable("data");
Bitmap croppedBitmap = getCroppedBitmap(selectedBitmap);
ImageView imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(croppedBitmap);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
FileOutputStream fOut = null;
String fileName = "Cropped_Image.jpg";
try {
// Not sure if the / is on the path or not
File file = new File(baseDir + File.separator + fileName); // the File to save to
fOut = new FileOutputStream(file);
Bitmap pictureBitmap = getCroppedBitmap(selectedBitmap); // Using the cropped bitmap.
pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
fOut.flush();
fOut.close(); // do not forget to close the stream
MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private void performCrop(String picUri) {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
File f = new File(picUri);
Uri contentUri = Uri.fromFile(f);
cropIntent.setDataAndType(contentUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 280);
cropIntent.putExtra("outputY", 280);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, RESULT_CROP);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
public Bitmap getCroppedBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,
bitmap.getWidth() / 2, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.user.myapplication">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".GalleryUtil"></activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.user.myapplication.MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
The above code is working absolutely fine. I am able to get pics cropped and saved in my sd card.
Compare and check where you are doing wrong.
To read every time app opens, we need to add following to main activity :
.
.
.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adding code for reading if file is already saved :
loadImageFromStorage(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Cropped_Image.jpg")
// onImage can be called with anything doesn't matter :
onImage(null);
}
private void loadImageFromStorage(String path)
{
try {
File f=new File(path);
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.imageView);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
...
i am trying to show a pic clicked from camera on another activity image view,but getting image out of the bundle into bitmaps.. i get this error.
my code is
package com.example.iwm;
import java.io.File;
import java.text.SimpleDateFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
//private static final int RESULT_OK = -1;
private static final int MEDIA_TYPE_IMAGE = 1;
public static Bundle s = null;
//public static String y ;
private Uri fileUri;
private static Intent intent;
private static Intent intent2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create Intent to take a picture and return control to the calling application
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(android.provider.MediaStore.ACTION_IMAGE_CAPTURE, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
//onActivityResult(CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE, int resultCode, intent)
}
private Uri getOutputMediaFileUri(int type) {
// TODO Auto-generated method stub
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
#SuppressLint("SimpleDateFormat")
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "IWMP-Images");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("IWMP-Images", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" + fileUri, Toast.LENGTH_LONG).show();
s =data.getExtras();
intent2 = new Intent(MainActivity.this,MainActivity2.class);
intent2.putExtra("Image", s);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(intent2);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
Toast.makeText(this, "Image NOT saved ", Toast.LENGTH_LONG).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
`
from this i an saving the data(Intent) in a bundle S and sending it to activty2
my activity2 code is
package com.example.iwm;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity2 extends Activity {
TextView tx;
Bitmap bmp;
ImageView ivUserImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
ivUserImage = (ImageView)findViewById(R.id.image);
tx = (TextView)findViewById(R.id.text1);
//tx.setText(MainActivity.y);
Bundle bundle = getIntent().getExtras();
try
{
bmp =(Bitmap)bundle.get("Image");
}
catch(Exception e)
{
tx.setText(e.toString());
}
ivUserImage.setImageBitmap(bmp);
//int i=10;
}
public void upload(View view)
{
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main_activity2, menu);
return true;
}
}
can u try like this
get the image path after u taken from camera like this
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
final String[] imageColumns = { MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns,
null, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
String pathoflasttakenimage = imageCursor.getString(imageCursor
.getColumnIndex(MediaStore.Images.Media.DATA));
}
}
pass this imagepath in bundle like this
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
Bundle bundle = new Bundle();
bundle.putString("path", pathoflasttakenimage);
intent.putExtras(bundle);
startActivity(intent);
in another activity use this imagepath to show image in imageview like this
Bundle b = getIntent().getExtras();
String path = b.getString("path");
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 2; // for 1/2 the image to be loaded
Bitmap thumb = Bitmap.createScaledBitmap(
BitmapFactory.decodeFile(path, opts), 96, 96, false);
ivUserImage.setImageBitmap(thumb);
let tell me what's problem in this way u face.
use bundle.get("data") instead bundle.get("Image") for getting Bitmap from Bundle in Second Activity. try it as:
Bundle bundle = getIntent().getExtras();
try
{
// getting error here.
bmp = (Bitmap)bundle.get("data"); //<< use data instead of Image
ivUserImage.setImageBitmap(bmp);
}
catch(Exception e)
{
tx.setText(e.toString());}
}
I use the camera intent to capture video. Here is the problem:
If I use this line of code, I can record video. But onActivityResult doesn't work.
Intent intent = new Intent("android.media.action.VIDEO_CAMERA");
If I use this line of code, after press the recording button, the camera is freezed, I mean,
the picture is still.
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
BTW, when I use Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); to capture a picture, it works fine.
The java file is as follows:
package com.camera.picture;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;
public class PictureCameraActivity extends Activity {
private static final int IMAGE_CAPTURE = 0;
private static final int VIDEO_CAPTURE = 1;
private Button startBtn;
private Button videoBtn;
private Uri imageUri;
private Uri videoUri;
private ImageView imageView;
private VideoView videoView;
/** Called when the activity is first created.
* sets the content and gets the references to
* the basic widgets on the screen like
* {#code Button} or {#link ImageView}
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView)findViewById(R.id.img);
videoView = (VideoView)findViewById(R.id.videoView);
startBtn = (Button) findViewById(R.id.startBtn);
startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startCamera();
}
});
videoBtn = (Button) findViewById(R.id.videoBtn);
videoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startVideoCamera();
}
});
}
public void startCamera() {
Log.d("ANDRO_CAMERA", "Starting camera on the phone...");
String fileName = "testphoto.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image capture by camera");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, IMAGE_CAPTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_CAPTURE) {
if (resultCode == RESULT_OK){
Log.d("ANDROID_CAMERA","Picture taken!!!");
imageView.setImageURI(imageUri);
}
}
if (requestCode == VIDEO_CAPTURE) {
if (resultCode == RESULT_OK) {
Log.d("ANDROID_CAMERA","Video taken!!!");
Toast.makeText(this, "Video saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
videoView.setVideoURI(videoUri);
}
}
}
private void startVideoCamera() {
// TODO Auto-generated method stub
//create new Intent
Log.d("ANDRO_CAMERA", "Starting camera on the phone...");
String fileName = "testvideo.mp4";
ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.TITLE, fileName);
values.put(MediaStore.Video.Media.DESCRIPTION,
"Video captured by camera");
values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
videoUri = getContentResolver().insert(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent("android.media.action.VIDEO_CAMERA");
//Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
// start the Video Capture Intent
startActivityForResult(intent, VIDEO_CAPTURE);
}
private static File getOutputMediaFile() {
// TODO Auto-generated method stub
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
return mediaFile;
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(){
return Uri.fromFile(getOutputMediaFile());
}
}
Use MediaStore.ACTION_VIDEO_CAPTURE to record Video .
Intent photoPickerIntent= new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(Intent.createChooser(photoPickerIntent,"Take Video"),TAKE_VIDEO);
And your OnActivityResult must be like this to Save Video in particular location :
if(requestCode==TAKE_VIDEO)
{
try
{
Log.e("videopath","videopath");
AssetFileDescriptor videoAsset = getContentResolver().openAssetFileDescriptor(data.getData(), "r");
FileInputStream fis = videoAsset.createInputStream();
File root=new File(Environment.getExternalStorageDirectory(),"Directory");
if (!root.exists()) {
root.mkdirs();
}
File file;
file = new File(root,filename+".mp4" );
Uri uri=Uri.fromFile(file);
Item1.videopath=uri.getPath();
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Alright I am making an Android app, and using the CAPTURE_PIC_REQUEST to take a picture and store it as a preview on the screen in an imageviewer. I wanted to know how to get the Uri and actually path because I am planning on taking that information, saving it and accessing it later. So I can't figure how to get the Uri or path name from that picture I just took. Here is the code from my activity that is handling
package com.CS480;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class AddEx extends Activity {
static final int CAMERA_PIC_REQUEST = 1337;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
Button camera = (Button) findViewById(R.id.picButton);
camera.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ImageView image = (ImageView) findViewById(R.id.returnedPic);
image.setImageBitmap(thumbnail);
}
}
}
So how from that image that I am getting back on the app do I get the file location
As far as I know, you can do something like this:
private Uri mImageCaptureUri;
public class AddEx extends Activity {
static final int CAMERA_PIC_REQUEST = 1337;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
Button camera = (Button) findViewById(R.id.picButton);
camera.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent =
new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ImageView image = (ImageView) findViewById(R.id.returnedPic);
image.setImageBitmap(thumbnail);
String pathToImage = mImageCaptureUri.getPath();
// pathToImage is a path you need.
// If image file is not in there,
// you can save it yourself manually with this code:
File file = new File(mImageCaptureUri.getPath());
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut); // You can choose any format you want
}
}
From Android documentation about android.provider.MediaStore.EXTRA_OUTPUT:
The name of the Intent-extra used to indicate a content resolver Uri
to be used to store the requested image or video.
You can try getting the URI of the image with
data.getExtras.get("URI");
but this might not work. What you can do is simply save the Bitmap yourself. See this question for a guide on how to do that: Save bitmap to location
When you take your image, you must store it somewhere to get the location of the image.
To do this, you can store to the MediaStore:
String result = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "", "");
imageFileUri = Uri.parse(result);
Try this get image file path form Bitmap
public void uploadBitmap(Context mContext, Bitmap bitmap) {
String imagePath = null;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
Uri uri;
Cursor cursor = mContext.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, MediaStore.Images.Media.DATE_ADDED, null, "date_added DESC");
if (cursor != null && cursor.moveToFirst()) {
do {
uri = Uri.parse(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)));
imagePath = uri.toString();
Log.d("pathatka", uri.toString());
break;
} while (cursor.moveToNext());
cursor.close();
}
}
The android documentation has an example of defining a file URI for saving the output when you setup the Intent for your image capture.
I am starting gallery through intent otherwise its giving problem to display gallery in grid view.
But i want the actual sd card path of the image i am selection from the gallery, opened by intent.
here is the code..
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/jpg");
photoPickerIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/Pictures/image.jpg"));
startActivityForResult(photoPickerIntent, 1);
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_CANCELED) {
showToast(this,"Activity cancelled");
return;
}
else if(resultCode == RESULT_OK) {
System.out.println("requestCode--"+requestCode);
System.out.println("resultCode--"+resultCode);
System.out.println("data--"+intent.getData());
Uri uri = intent.getData();
String data = uri.getPath();
System.out.println("uri.getPath()--"+uri.getPath());
System.out.println("type--"+intent.getType());
System.out.println("path--"+Environment.getExternalStorageState());
return;
}
switch (requestCode) {
case CAMERA_ACTIVITY:
Bundle b = intent.getExtras();
Bitmap bm = (Bitmap) b.get("data");
// mImageView.setImageBitmap(bm); // Display image in the View
// large image?
if (b.containsKey(MediaStore.EXTRA_OUTPUT)) { // large image?
Log.i(TAG, "This is a large image");
showToast(this,"Large image");
// Should have to do nothing for big images -- should already saved in MediaStore ... but
MediaStore.Images.Media.insertImage(getContentResolver(), bm, null, null);
}
else {
Log.i(TAG, "This is a small image");
showToast(this,"Small image");
MediaStore.Images.Media.insertImage(getContentResolver(), bm, null, null);
}
break;
}
}
}
I am getting all data from intent object. But i want the sd card path for the image what i am selecting to upload that image in server..
how do i get that?
You may want something like this:
Uri uri = (Uri) intent.getExtras().get("android.intent.extra.STREAM");
if ( intent.getAction().equals( Intent.ACTION_SEND ) )
{
if ( uri.getScheme().equals("content"))
{
Cursor cursor = getContentResolver().query( uri, null, null, null, null );
cursor.moveToFirst();
filePath = cursor.getString(cursor.getColumnIndexOrThrow(Images.Media.DATA));
}
}
This Code may help you
This code will pop up one Dialog Box with Camera and gallery and devices SD card to get the images path.
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import com.fanosedu.R;
public class FileAttachPopUpUtils extends Activity {
private View rootView;
private Dialog popup;
private Button Assig_PopUp_DeviceBtn;
private Button Assig_PopUp_GalaryBtn;
private Button Assi_PopUp_CameraBtn;
private Button Assig_PopUp_CancelPopupBtn;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.assignment_popupfile);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
/*
* getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
* WindowManager.LayoutParams.FLAG_FULLSCREEN);
*/
popup = new Dialog(this);
// popup.requestWindowFeature(Window.FEATURE_NO_TITLE);
// popup.getWindow().setBackgroundDrawable(new
// ColorDrawable(android.graphics.Color.TRANSPARENT));
popup.setContentView(R.layout.assignment_popupfile);
popup.setCanceledOnTouchOutside(false);
popup.show();
Assig_PopUp_DeviceBtn = (Button) popup
.findViewById(R.id.Assignment_PopUp_DeviceBtn);
Assig_PopUp_GalaryBtn = (Button) popup
.findViewById(R.id.Assignment_PopUp_GalaryBtn);
Assi_PopUp_CameraBtn = (Button) popup
.findViewById(R.id.Assignment_PopUp_CameraBtn);
Assig_PopUp_CancelPopupBtn = (Button) popup
.findViewById(R.id.Assignment_PopUp_CancelPopupBtn);
Assig_PopUp_DeviceBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*
* Toast.makeText(FileAttachPopUpUtils.this,
* "Device File In-Progress", Toast.LENGTH_SHORT) .show();
*/
Intent intent = new Intent(FileAttachPopUpUtils.this,
FileExplore.class);
startActivity(intent);
popup.dismiss();
finish();
}
});
Assig_PopUp_GalaryBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
});
Assi_PopUp_CameraBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// ///////////////////////////////////////////////////////////////
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
}
});
Assig_PopUp_CancelPopupBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
popup.dismiss();
FileAttachPopUpUtils.this.finish();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_OK) {
if (requestCode == 1) {
/*
* Intent intent = new Intent( Intent.ACTION_PICK,
* android.provider
* .MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
* startActivityForResult(intent, 2);
*/
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
// mImage.setImageBitmap(thumbnail);
// 3
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
// 4
String name;
int n = 100000;
int rand;
rand = new Random().nextInt(n);
name = "Image-" + rand + ".jpg";
// File fileimage = new File(path, name);
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + name);
System.out.println("FILE PATH=======>>>>>>>>>>"
+ file.toString());
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
// 5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Assignments.mulPathArry.add(file.toString());
// Here You will get the full path
FileAttachPopUpUtils.this.finish();
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = this.getContentResolver().query(selectedImage,
filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Assignments.mulPathArry.add(picturePath);
// Here you will get Path
popup.dismiss();
FileAttachPopUpUtils.this.finish();
}
}
// ///////////////////////////////////////////////////////////////////////
}
#Override
public void onBackPressed() {
return;
}
}