data null onActivityResult - java

Activity results is NullPointerException, What I have done wrong or missed?
Photo gallery application(Eventually), followed the instructions on the android developer site about taking photos with inbuilt camera. onActivityResult giving null pointer. I am new to android so can't figure it out.
Because of this it crashes, i expect it to show a bitmap in the activity.
public class aCamera extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_TAKE_PHOTO = 1;
ImageView imageView;
String currentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a_camera);
dispatchTakePictureIntent();
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
Log.i("DTPI-1", "dispatchTakePictureIntent: The IF AND TRY");
} catch (IOException ex) {
Log.i("DTPI-3" , "dispatchTakePictureIntent: catch");
}
// Continue only if the File was successfully created
if (photoFile != null) {
Log.i("photoURI", "dispatchTakePictureIntent: PHOTO FILE NOT EMPTY");
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
//setResult(RESULT_OK, takePictureIntent);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
Log.i("CIF -1", "createImageFile: Create FILE");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("Result", "onActivityResult: WE GET HERE");
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView = findViewById(R.id.imageView);
imageView.setImageBitmap(imageBitmap);
}
}
Error logs.
2019-05-06 20:01:33.555 23363-23363/com.example.camera E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.camera, PID: 23363
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.camera/com.example.camera.aCamera}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4339)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4382)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1654)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:251)
at android.app.ActivityThread.main(ActivityThread.java:6572)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at com.example.camera.aCamera.onActivityResult(aCamera.java:81)
at android.app.Activity.dispatchActivityResult(Activity.java:7235)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4335)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4382) 
at android.app.ActivityThread.-wrap19(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1654) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:251) 
at android.app.ActivityThread.main(ActivityThread.java:6572) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

The camera saves the image to the photoUri that you supply in your Intent. In onActivityResult you have to get the Bitmap from that file.

The line putExtra is the issue. Delete that line and receive bitmap in
onActivityResult like mentioned below.
#Override
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
if (requestCode == REQUEST_TAKE_PHOTO && resultcode == RESULT_OK) {
Uri uri = intent.getData();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
image.setImageBitmap(bitmap);
}
}
Hope this works. You will see the explaination here on a post with similar issue.

As mentioned by #aalap patel, the issue is not with onActivityResult, it is with one line in dispatchTakePictureIntent method.
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
adding to this is the code that he also mentions.

Related

How to send image from one fragment to another?

I read these but an error persists:
How to pass selected image from one fragment to another fragment
Passing image from one fragment to a another fragment and display image in that fragment
I have created an activity which is transferring data and image from one fragment to another, data is parsing successfully but when I am sending image it says
2021-05-16 04:08:52.127 26026-26026/com.example.mcqapp E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /document/image:11600: open failed: ENOENT (No such file or directory)
This is my code for fragment first
if (imageView.getVisibility() == View.VISIBLE) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK && data != null) {
filePath = data.getData();
path_New = filePath.getPath();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(),filePath);
imageView.setImageBitmap(bitmap);
}catch (Exception e){
e.printStackTrace();
}
}
bundle.putString("image",path_New);
second mfragment=new second();
mfragment.setArguments(bundle);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment1, mfragment).commit();
Code in second fragment to receive image:
Bundle bundle = getArguments();
String imagePath = bundle.getString("image");
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageView.setImageBitmap(bitmap);
Alright ,I solved it, i converted uri to string and then in second fragment i converted String to
urifilePath = data.getData();
String path = filePath.toString();
bundle.putString("image",path);
Second Fragment
String imagePath = bundle.getString("image");
Uri myUri = Uri.parse(imagePath);
imageView.setImageURI(myUri);

How to display an image from the Gallery in an ImageView?

I created a button that lets the user choose between "Take picture with camera" and "Select picture from gallery".
When the picture is taken/chosen, I then display it in an ImageView of the next activity which I do by passing the URI of the file created to store the taken/selected picture.
It works as expected when the user takes a picture with his camera but when he selects an image from gallery, no image is shown in the next activity despite both intents (take a picture and select a picture) being coded the same.
My question(s): Why isn't the image displayed in the next activity ONLY when picked from the gallery ? Or how should I proceed to display it ?
Intent to open camera (working fine):
private void openCameraToTakePictureIntent() {
Log.d(TAG, "Method for Intent Camera started");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.emergence.pantherapp.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
Intent to access gallery and pick an image:
private void openGalleryIntent() {
Log.d(TAG, "Method for Intent Gallery started");
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
if (galleryIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.emergence.pantherapp.fileprovider", photoFile);
galleryIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(galleryIntent, PICK_IMAGE);
}
}
}
Then here's the onActivityResult: (currentPhotoPath is the absolute path of the file created to store the image)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == 1) {
Log.d(TAG, currentPhotoPath);
Intent intent = new Intent(this, ModifyPictureActivity.class);
intent.putExtra("USER_IMAGE", currentPhotoPath);
startActivity(intent);
} else if (resultCode == Activity.RESULT_OK && requestCode == 2) {
Log.d(TAG, currentPhotoPath);
Intent intent = new Intent(this, ModifyPictureActivity.class);
intent.putExtra("USER_IMAGE", currentPhotoPath);
startActivity(intent);
}
}
Below is how the image is displayed in the following activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modify_picture);
Intent intent = getIntent();
String imageUri = intent.getStringExtra("USER_IMAGE");
if (imageUri != null) {
Log.d(TAG, imageUri);
} else {
Log.d(TAG, "imageUri was null");
}
image = findViewById(R.id.picture);
image.setImageURI(Uri.parse(imageUri));
}
I made sure to have the READ_EXTERNAL_STORAGE in the manifest and the xml layout is just set to "match_parent" for height and width but I can add them if it's relevant.
Few Intent actions use EXTRA_OUTPUT. Mostly, that is an ACTION_IMAGE_CAPTURE thing.
More typically, an Intent for getting a piece of content (ACTION_PICK, ACTION_GET_CONTENT, ACTION_OPEN_DOCUMENT, ACTION_CREATE_DOCUMENT, ACTION_OPEN_DOCUMENT_TREE, etc.) return a Uri from the content supplier in the Intentdelivered toonActivityResult(). Given your implementation, that would be data.getData()to get thatUri`.
You can then use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. In your case, for example, you could use that InputStream to copy the bytes to a FileOutputStream to make your own local copy of the content.
Note that you only have short-term access to the content identified by the Uri.

Capture Image, Upload To Firebase And Retrieve Java Android Studio

I am very sorry if this may be a question with a simple solution.
What Am I Trying To Do?
Capture an image from a Button
Upload that image to Firebase storage
Retrieve that image in an ImageView
What Is My Trouble So Far?
Takes picture, but crashes when I click the tick.
Hence nothing is being uploaded or being achieved.
My Code
P.N I have looked at lots of other forums and video tutorials but nothing seems to be working. Hopefully someone can help.
public class LeaderboardActivity extends AppCompatActivity {
private static final int CAMERA_REQUEST_CODE = 1;
private static final int REQUEST_TAKE_PHOTO = 1;
private StorageReference mStorage;
private ProgressDialog mProgress;
String mCurrentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
mStorage = FirebaseStorage.getInstance().getReference();
final Button bImage = (Button) findViewById(R.id.bCamera);
final ImageView ivPic = (ImageView) findViewById(R.id.ivPic);
mProgress = new ProgressDialog(this);
bImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
mProgress.setMessage("Uploading Image");
mProgress.show();
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photo").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener < UploadTask.TaskSnapshot > () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Toast.makeText(LeaderboardActivity.this, "Uploading Complete...", Toast.LENGTH_LONG);
}
});
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
}
Error In Android Monitor
Not sure if this will help
02-13 02:30:32.693 2133-2133/com.example.rikhi.chores E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rikhi.chores, PID: 2133
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.rikhi.chores/com.example.rikhi.chores.LoginRegister.InsideMainActivity.LeaderboardActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4089)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at com.example.rikhi.chores.LoginRegister.InsideMainActivity.LeaderboardActivity.onActivityResult(LeaderboardActivity.java:74)
at android.app.Activity.dispatchActivityResult(Activity.java:6932)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132) 
at android.app.ActivityThread.-wrap20(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
I have looked at other people who had the same problem, followed what they said nothing happend, followed the Google Android instructions for this and again same problem.
On button, click remove that intent and just call your
dispatchTakePictureIntetnt() method on Onclick button Listener
Also, check go to your emulator settings, and check your camera
permission is on for your this app and also go to firebase console
and check the rules if, rules are not equal to null made them equal
to null then run your app because !=null rules only work when there
is an authentication method in your app

BitmapFactory: Unable to decode stream: java.io.FileNotFoundException even when file IS actually there

I'm creating a simple app to take a picture. this is my code
Button b1;
ImageView iv;
String TAG = "MAIN ACTIVITY";
File photo;
private Uri mImageUri;
private File createTemporaryFile(String part, String ext) throws Exception {
File externalStorageDirectory = Environment.getExternalStorageDirectory();
File tempDir = new File(externalStorageDirectory + "/cameratest/");
if (!tempDir.exists()) {
tempDir.mkdir();
}
return File.createTempFile(part, ext, tempDir);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
iv = (ImageView) findViewById(R.id.imageView);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
try {
// place where to store camera taken picture
photo = createTemporaryFile("picture", ".jpg");
photo.delete();
} catch (Exception e) {
Log.v(TAG, "Can't create file to take picture!");
Toast.makeText(getApplicationContext(), "Please check SD card! Image shot is impossible!",
Toast.LENGTH_SHORT).show();
}
mImageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(intent, 0);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
Log.d(TAG, mImageUri.toString());
Bitmap bitmap = BitmapFactory.decodeFile(mImageUri.toString());
iv.setImageBitmap(bitmap);
}
}
as you can see i've added eLog.d(TAG, mImageUri.toString()); at the end and in the logcat (as well as the FileNotFoundException) i see this direcory:
03-27 00:43:30.498 30526-30526/myapplication.example.falcoleo.cameratest1 D/MAIN ACTIVITY: file:///storage/emulated/0/cameratest/picture459838058.jpg
03-27 00:43:30.499 30526-30526/myapplication.example.falcoleo.cameratest1 E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: file:/storage/emulated/0/cameratest/picture459838058.jpg: open failed: ENOENT (No such file or directory)
guess if this directory exists?
spoler alert, it does. And it's not like the image is created after the BitmapFactory.decodeFile. I really do not understand what i'm doing wrong. Everything works fine except when it actually has to display the photo, then it just does not display it. just blank. Like WTF m8 i'm just trying to do my job no need to go crazy, you know.
Replace mImageUri.toString() with mImageUri.getPath().
decodeFile expects a path, not an uri string.
file:///storage/emulated/0/cameratest/picture459838058.jpg
Remove file:// because the decodeFile() expects a file system path.
/storage/emulated/0/cameratest/picture459838058.jpg
Use BitmapFactory.decodeStream instead of BitmapFactory.decodeFile.
try ( InputStream is = new URL( file_url ).openStream() ) {
Bitmap bitmap = BitmapFactory.decodeStream( is );
}
Source https://stackoverflow.com/a/28395036/5714364
Ok for me it was the file path was wrong so I needed to get the real filepath.
First
File file = new File(getPath(uri));
public String getPath (Uri uri)
{
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri,
projection,
null,
null,
null);
if (cursor == null)
return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
cursor.close();
return s;
}
Then Back To Uri
Uri newUri = Uri.fromFile(file);
This conversion to file and back to uri did the trick for me. I was receiving simple data from action.SEND.

Capturing Image from camera and displaying it in another activity in android

I am developing an application in which i want to capture the image from the camera and display it in another activity in an image view, my problem is that able to capture the image but after capturing i am redirected to first activity instead to second one.
Here is my Code..
PictureOptions.java
public void buttonCameraOpen(View view)
{
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
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), "Easy Heal");
// 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;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap selectedphoto = null;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && null!=data) {
// Image captured and saved to fileUri specified in the Intent
//selectedphoto = (Bitmap) data.getExtras().get("data");
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);
File f =new File(filePath);
String filename = f.getName();
cursor.close();
selectedphoto = BitmapFactory.decodeFile(filePath);
Intent intent = new Intent(PictureOptions.this,ShowImage.class);
//intent.putExtra("data", selectedphoto);
intent.setData( selectedImage );
startActivity(intent);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
PictureOptions.xml
<Button
android:id="#+id/buttonCameraOpen"
android:layout_width="fill_parent"
android:layout_height="72dp"
android:layout_weight="0.35"
android:onClick="buttonCameraOpen"
android:text="#string/button_camera_open" />
ShowImage.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_image);
ImageView imageview = (ImageView)findViewById(R.id.ImageShow);
Uri imageUri = getIntent().getData();
//Bitmap selectedphoto =(Bitmap)this.getIntent().getParcelableExtra("data");
imageview.setImageURI(imageUri);
}
ShowImage.xml
<ImageView
android:id="#+id/ImageShow"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
I finally found an awesome solution
This library is used to capture image from camera or select from gallery and return back image in File format in onActivityResult method, which can be used further in the application.
Use
EasyImage Library
Uri uriSavedImage=Uri.fromFile(new File("/sdcard/flashCropped.png"));
camera.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(camera, 1);
After clicking the image, check whether it exists or not. Then send the path to the image file to the next activity and display it via Bitmap.
Call the camera intent
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
then on activity for result use this
'case REQUEST_IMAGE_CAPTURE:
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
saveBitmap(imageBitmap);
mimageView1.setImageBitmap(imageBitmap);
mIntent.putExtra("ACTIVITY_CODE", 1);
startActivity(mIntent);
break;
the add this method in ur same class
public void saveBitmap(Bitmap bmp)
{
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +"/DCIM";
try
{
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "time");
cameraUrl=file.getAbsolutePath();
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
}
catch (Exception e) {
Log.e("errr in ","inserting the image at parictular location");
}
}
then call this in ur another activity where u want the image
String valueC = getIntent().getExtras().getString("CAMERA");
Log.v("imageBitmap", ""+valueC);
Bitmap yourSelectedImageC = BitmapFactory.decodeFile(valueC);
mImgV_image.setImageBitmap(yourSelectedImageC);
I have same problem after spending 2 days finally i got the anwer
First activity
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
Intent intent= new Intent(this,SecondActivity.class);
selfiSrc.putExtra("imgurl", uri );
startActivity(intent);
}
SecondActivity
Imageview iv_photo=(ImageView)findViewById(R.id.iv_photo);
Bundle extras= getIntent().getExtras();
if(extras!=null)
{
path = (Uri) extras.get("imgurl");
iv_photo.setImageURI(path);
}
Another way see my answer
Android - how can i transfer ImageView from one activity to another activity?

Categories

Resources