null pointer exception in android - android

I am having a NullPointerException in my android code on this section
String title = titleEt.getText().toString();
String description = descriptionEt.getText().toString();
Log.i("title",title);
Log.i("description",description);
audioRecordPasser.onAudioRecordPass(title, "hiphop", description, fileUri.getPath());
getDialog().dismiss();
The exception is on the line
audioRecordPasser.onAudioRecordPass(title, "hiphop", description, fileUri.getPath());
audioRecordPasser is an interface.
The complete code implementation is
public class UploadFragment extends DialogFragment implements AdapterView.OnItemSelectedListener, View.OnClickListener {
Spinner genres;
ImageView photo;
TextView submit;
String fileName = "";
EditText titleEt, descriptionEt;
private static final String KEY = "choice";
public Uri fileUri; // file url to store image/video
OnAudioRecordPass audioRecordPasser;
public UploadFragment(){
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.fragment_upload, null);
builder.setView(v);
submit = (TextView) v.findViewById(R.id.upload_textView_submit);
genres = (Spinner) v.findViewById(R.id.upload_spinner_genre);
photo = (ImageView) v.findViewById(R.id.upload_imageView_photo);
titleEt = (EditText) v.findViewById(R.id.upload_edittext_title);
descriptionEt = (EditText) v.findViewById(R.id.upload_editText_description);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),
R.layout.ngoma_spinner, getResources().getStringArray(R.array.genres));
dataAdapter
.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
genres.setAdapter(dataAdapter);
genres.setOnItemSelectedListener(this);
submit.setOnClickListener(this);
photo.setOnClickListener(this);
return builder.create();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
private static final int INT_CODE = 1;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.upload_textView_submit:
Log.i("URI", fileUri.getPath());
// audioRecordPasser.onAudioRecordPass(titleEt.getText().toString(),"hiphop",descriptionEt.getText().toString(),fileUri.getPath());
if (validateInput()==false){
Toast.makeText(getActivity(),"Fields cannot be blank.",Toast.LENGTH_SHORT).show();
}
else {
String title = titleEt.getText().toString();
String description = descriptionEt.getText().toString();
Log.i("title",title);
Log.i("description",description);
audioRecordPasser.onAudioRecordPass(title, "hiphop", description, fileUri.getPath());
getDialog().dismiss();
}
break;
case R.id.upload_imageView_photo:
UploadPhotoDialog uploadDialog = new UploadPhotoDialog();
uploadDialog.setTargetFragment(this, INT_CODE);
uploadDialog.show(getActivity().getSupportFragmentManager(), "uploadPhoto");
break;
}
}
/**
* **************************************************************************************************
*/
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static int RESULT_LOAD_IMAGE = 1;
/**
* Select image from gallery
*/
private void selectFromGallery() {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
/**
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "ngoma";
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
/*
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}*/
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// get the file url
//fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Receiving activity result method will be called after closing the camera
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == Activity.RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getActivity().getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getActivity().getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
fileUri = selectedImage;
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
// String picturePath contains the path of selected Image
previewFromGallery(picturePath);
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
Log.i("previewCapturedImage", fileUri.getPath());
photo.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void previewFromGallery(String picturePath) {
photo.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
fileUri = Uri.fromFile(getOutputMediaFile(type));
Log.i("getOutputMediaFileUri", fileUri.getPath());
return fileUri;
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Error creating "
+ IMAGE_DIRECTORY_NAME + " directory.");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).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;
}
public void choiceSelector(String data) {
if (data.equalsIgnoreCase("camera")) {
captureImage();
} else if (data.equalsIgnoreCase("gallery")) {
selectFromGallery();
}
}
public interface OnAudioRecordPass {
public void onAudioRecordPass(String title, String genre, String description, String photouri);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
audioRecordPasser = (OnAudioRecordPass) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnAudioRecordPass");
}
}
private boolean validateInput() {
if (titleEt.getText().toString().equalsIgnoreCase("") || descriptionEt.getText().toString().equalsIgnoreCase("")) {
return false;
} else {
return true;
}
}
}
Everything runs fine.In my logcat, I can see the values of title and desription and fileUri.getPath() variables.What could be the issue?
The logcat content
10-31 15:42:44.032 4101-4101/ngoma.android.shimba.com.ngoma E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.shimba.android.ngoma.activities.MainActivity.onAudioRecordPass(MainActivity.java:516)
at com.shimba.android.ngoma.fragments.UploadFragment.onClick(UploadFragment.java:101)
at android.view.View.performClick(View.java:3511)
at android.view.View$PerformClick.run(View.java:14105)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4440)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
at dalvik.system.NativeStart.main(Native Method)

The problem is with the parameter fileUri.getPath()
May be this is not properly initialized and as a result its value is null
Check the value of fileUri variable value before passing it to the function.
This will solve your problem

Related

How to retrieve the images from the particular folder?

I am trying to take picture and save it in a particular folder and retrieve it in a list view. I have done the first part that is show to store it in a particular folder, but I don't know how to retrieve it.
Here the taken images is stored in a hello camera folder which is inside pictures. The below code can also record the video. Please give me the code to retrieve the images only from the particular folder. I need this code because to store the documents with security.
My code for storing images
public class photo extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
Button submit;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
context = this;
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
submit = (Button) findViewById(R.id.button2);
name = (EditText) findViewById(R.id.imagename);
//n1= (EditText) findViewById(R.id.imagename);
// final String Uname = name.getText().toString();
/**
* Capture image button click event
*/
Calendar cal;
cal = Calendar.getInstance();
String currDate = cal.get(Calendar.DATE) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.YEAR);
mydb = this.openOrCreateDatabase(DataProvider.DATABASE_NAME, Context.MODE_PRIVATE, null);
Cursor cs = mydb.rawQuery("select * from '" + DataProvider.TBL_PRE + "'", null);
// cs = getContentResolver().query(DataProvider.PRE_URI, null,DataProvider.DATE+"="+currDate, null, null);
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String err = val();
if (err.length() <= 0) {
String uname = name.getText().toString();
System.out.println("++uname--->" + uname);
ContentValues values = new ContentValues();
values.put(DataProvider.NAME1, uname);
getContentResolver().insert(DataProvider.PRE_URI, values);
System.out.println("\n values" + values.toString());
startActivity(new Intent(photo.this, preview.class));
overridePendingTransition(R.anim.pull_in_left, R.anim.push_out_right);
}
else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Alert");
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setMessage(err);
alertDialog.show();
}
}
});
/*submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String err = val();
if (err.length() <= 0) {
String uname = name.getText().toString();
System.out.println("uname--->" + uname);
ContentValues values = new ContentValues();
values.put(DataProvider.NAME1, uname);
System.out.println("^^^"+uname);
//values.put(DataProvider.DATE, date.getText().toString());
getContentResolver().insert(DataProvider.PRE_URI, values);
System.out.println("\n values" + values.toString());
Intent i = new Intent(photo.this, preview.class);
startActivity(i);}
}
});
*/
/**
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/**
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Recording video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Previewing recorded video
*/
private void previewVideo() {
try {
// hide image preview
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(photo.this,preview.class));
overridePendingTransition(R.anim.pull_in_left,R.anim.push_out_right);
finish();
System.exit(0);
}
public String val() {
String err = "";
if (name.getText().toString().length() <= 0) {
err += "Enter the Name \n";
}
return err;
}
}
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Previewing recorded video
*/
private void previewVideo() {
try {
// hide image preview
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(photo.this,preview.class));
overridePendingTransition(R.anim.pull_in_left,R.anim.push_out_right);
finish();
System.exit(0);
}
public String val() {
String err = "";
if (name.getText().toString().length() <= 0) {
err += "Enter the Name \n";
}
return err;
}
}
try this
private void getImages() {
String[] filenames = new String[0];
File path = new File(Environment.getExternalStorageDirectory() + "/Favorite");// add here your fo;der name
if (path.exists()) {
filenames = path.list();
}
for (int i = 0; i < filenames.length; i++) {
imagesPathArrayList.add(path.getPath() + "/" + filenames[i]);
Log.e("FAV_Images", imagesPathArrayList.get(i));
//Bitmap mBitmap = Bitmap.decodeFile(path.getPath()+"/"+ fileNames[i]);
///Now set this bitmap on imageview
}
}
don't forget to add permission in manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

How to display capture image from camera and display in imageview from file path? [duplicate]

This question already has answers here:
Capture Image from Camera and Display in Activity
(19 answers)
Closed 6 years ago.
My problem after taking a photo and then createImageFile .. onActivityResult, photo does not appear on img_photo. how to make appear in img_photo ?
img_photo = (ImageView) findViewById(R.id.imgPhoto);
// take a photo from camera
imgBtnCamera = (ImageButton) findViewById(R.id.imgBtnCamera);
imgBtnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
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(PhotoSubmitActivity.this,
"com.example.android.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
});
Create image file
// Create image file
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;
}
onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
Log.v("This is totally working", "Yeah!");
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
img_photo.setScaleType(ImageView.ScaleType.CENTER_CROP);
img_photo.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I attended training on this link Taking Photos Simply
i had same problem too.but i solved it.
#Driyanto Saputro see in my code where i placed a comment for save Captured image in ImageView.
also Note : i am working on Custom Camera not Using Existing Camera.
i paste my code below to Save Captured image in imageView.
public void CaptureImage() {
mCamera.takePicture(null, null, new Camera.PictureCallback() {
private File imageFile;
#Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
// Convert byte array into bitmap
final Bitmap originalBitmap = MainActivity.decodeSampledBitmapFromByte(getApplicationContext(), data);
// Rotate Image
Matrix rotateMatrix = new Matrix();
final Bitmap rotatedBitmap;
if (mCameraId == CAMERA_FACING_FRONT) {
rotateMatrix.postRotate(270);
} else {
rotateMatrix.postRotate(90);
}
rotatedBitmap = Bitmap.createBitmap(originalBitmap, 0, 0, originalBitmap.getWidth(), originalBitmap.getHeight(), rotateMatrix, false);
final File imageFolder;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
imageFolder = new File(Environment.getExternalStorageDirectory() + "/CameraApp/Images");
} else {
imageFolder = new File(Environment.getExternalStorageDirectory() + "/CameraApp/Images");
}
boolean success = true;
if (!imageFolder.exists()) {
success = imageFolder.mkdirs();
}
if (success) {
java.util.Date date = new java.util.Date();
imageFile = new File(imageFolder.getAbsolutePath() + File.separator + getFileNameCustomFormat() + " " + "Image.jpg");
SavedImagePath = getFileNameCustomFormat() + " " + "Image.jpg";
// imageFile.createNewFile();
} else {
Toast.makeText(getBaseContext(), "Image Not saved", Toast.LENGTH_SHORT).show();
return;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// Save image into gallery
if (rotatedBitmap != null) {
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
}
FileOutputStream file_out = new FileOutputStream(imageFile);
file_out.write(outputStream.toByteArray());
file_out.close();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, imageFile.getAbsolutePath());
getApplicationContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Toast.makeText(getApplicationContext(), "Photo Captured", Toast.LENGTH_SHORT).show();
// Code For Captured Image Save in a ImageView.
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
String imagePath = imageFolder.getAbsolutePath() + File.separator + SavedImagePath;
Uri myURI = Uri.parse(imagePath);
imgBtnThumbnail.setImageURI(myURI);
Toast.makeText(getApplicationContext(), "Photo Saved on ImageView", Toast.LENGTH_SHORT).show();
}
});
mCamera.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
I hope it will help You.(:
Try this way it will help
public class MainActivity extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
private Uri fileUri; // file url to store image/video
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
/**
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/**
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Recording video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Previewing recorded video
*/
private void previewVideo() {
try {
// hide image preview
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
http://www.androidhive.info/2013/09/android-working-with-camera-api/

Saving images to a file android

I need help with my issue of saving a picture . I am using adobe photo sdk to edit my image. Documentation link(https://creativesdk.adobe.com/docs/android/#/articles/imageediting/index.html). They say use .withOutput(Uri) to save the image which i created but get my image with an error.
public class MainActivity extends AppCompatActivity {
private static final int IMG_CODE_EDIT = 263;
private Button mPickbtn;
private Button mCapturebtn;
private static int RESULT_LOAD_IMAGE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private String mCurrentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPickbtn = (Button) findViewById(R.id.pick_image);
mCapturebtn = (Button) findViewById(R.id.button2);
Intent cdsIntent = AdobeImageIntent.createCdsInitIntent(getBaseContext(), "CDS");
startService(cdsIntent);
}
public void takePicture(View view) {
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
public void onClick(View view) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Gets the gallery image uri
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != 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 picturePath = cursor.getString(columnIndex);
cursor.close();
editPic(selectedImage);
}
//picture from camera
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Uri mPicTaken = data.getData();
editPic(mPicTaken);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
if (resultCode == RESULT_OK) {
switch (requestCode) {
/* 4) Make a case for the request code we passed to startActivityForResult() */
case 263:
/* 5) Show the image! */
Uri editedImageUri = data.getData();
Intent intent = new Intent("com.ayyogames.photoapp.Share");
intent.putExtra("imageUri", editedImageUri);
startActivity(intent);
break;
}
}
}
public void editPic(Uri uri) {
// 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.ayyogames.photoapp.fileprovider",
photoFile);
Intent intent = new AdobeImageIntent.Builder(this)
.setData(uri)
.withOutputSize(MegaPixels.Mp10)
.withOutputQuality(100)
.withOutput(photoURI)
.build();
startActivityForResult(intent, IMG_CODE_EDIT);
}
}
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 = "file:" + image.getAbsolutePath();
return image;
}
Share Class
public class Share extends AppCompatActivity {
private ImageView mEditedImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
mEditedImageView = (ImageView) findViewById(R.id.editedImageView);
Intent intent = getIntent();
Uri uri = intent.getParcelableExtra("imageUri");
mEditedImageView.setImageURI(uri);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu,menu);
return true;
}
}
The Image Editor developer guide currently says that you should pass a Uri to withOutput(), but this is incorrect.
Try passing a File:
/* 1) Change the argument to your desired location */
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "test.jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Intent imageEditorIntent = new AdobeImageIntent.Builder(this)
.setData(imageUri)
.withOutput(file) /* 2) Pass the File here */
.build();
Your argument to the File constructor should be altered to whatever location you desire.

Capturing and storing multiple images in android [duplicate]

I seem to be having trouble creating a Bitmap from fileUri.
I would like to be able to set this Bitmap to an Imageview for previewing the image, and later adding elements to the image.
Any ideas why the image does not get set properly?
public class FeedActivity extends Fragment implements OnClickListener {
ImageView m_ImageView;
ImageButton btnCamera, btnGallery;
private final String TAG_CAMERA_FRAGMENT = "camera_fragment";
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private Uri fileUri;
public static final int MEDIA_TYPE_IMAGE = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_feed, container, false);
m_ImageView = (ImageView) view
.findViewById(R.id.imageViewFeed);
btnCamera = (ImageButton) view.findViewById(R.id.btn_Camera);
btnCamera.setOnClickListener(this);
btnGallery = (ImageButton) view.findViewById(R.id.btn_Gallery);
btnGallery.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_Camera:
Log.e("CAMERA", "CAMERA BUTTON PRESSED");
takePicture();
break;
case R.id.btn_Gallery:
Log.e("Gallery", "GALLERY BUTTON PRESSED");
break;
}
}
public void takePicture() {
// 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);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == getActivity().RESULT_OK) {
Log.e("ONACTIVITYRESULT",
"-----------------RESULT_OK----------------");
Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath());
m_ImageView.setImageBitmap(bitmap);
// Bundle bundle = new Bundle();
// bundle.putParcelable("URI", fileUri);
//
// Fragment fragment = new PictureEditActivity();
// fragment.setArguments(bundle);
//
// getFragmentManager()
// .beginTransaction()
// .replace(R.id.contentFragment, fragment,
// TAG_CAMERA_FRAGMENT).commit();
if (fileUri != null) {
Log.e("CAMERA", "Image saved to:\n" + fileUri);
Log.e("CAMERA", "Image path:\n" + fileUri.getPath());
}
} else if (resultCode == getActivity().RESULT_CANCELED) {
Log.e("ONACTIVITYRESULT",
"-----------------RESULT_CANCELLED----------------");
} else {
}
}
}
/** Create a file Uri for saving an image or video */
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),
"Pixagram");
// 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("Pixagram", "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;
}
}
It appears as if I have found a solution.
http://www.androidhive.info/2013/09/android-working-with-camera-api/
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
m_ImageView.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}

Why can't some images be displayed on ImageView (Android)?

When I pick an image from my gallery, screenshots are shown but some images taken from camera aren't shown.
To be more specific, images taken using the system Camera app can't be shown while the ones taken using Camera360 can.
I wonder if there's any problem with my code. If there isn't, maybe it's because of my phone?
Thanks in advance. Sorry, my English isn't very good.
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
private ImageView img;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_image);
((Button) findViewById(R.id.Button01))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
SELECT_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
img = (ImageView) findViewById(R.id.ImageView01);
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
Drawable image;
try {
InputStream inputStream = getContentResolver()
.openInputStream(selectedImageUri);
image = Drawable.createFromStream(inputStream, "file///"
+ selectedImagePath.toString());
} catch (FileNotFoundException e) {
image = getResources().getDrawable(R.drawable.ic_launcher);
}
img.setImageDrawable(null);
img.setImageDrawable(image);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Oh, I found the problem. My image is too large. Updated code with several improvements below:
private static Context context;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private static final int SELECT_PICTURE = 3;
private String selectedImagePath;
private static String imageFilePath;
private static String videoFilePath;
private Uri fileUri;
private Bitmap bitmap;
private Button btnGallery, btnCamera;
private Intent selectPictureIntent;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_image);
context = this;
btnGallery = (Button) findViewById(R.id.Button01);
btnCamera = (Button) findViewById(R.id.Button02);
btnGallery.setOnClickListener(this);
btnCamera.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
Log.d("bitmap", selectedImageUri.getScheme());
selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
// Selected image is local image
Bitmap b = new BitmapDrawable(context.getResources(),
selectedImagePath).getBitmap();
int i = (int) (b.getHeight() * (512.0 / b.getWidth()));
bitmap = Bitmap.createScaledBitmap(b, 512, i, true);
} else {
// Selected image is Picasa image
loadPicasaImageFromGallery(selectedImageUri);
}
ImageView img = (ImageView) findViewById(R.id.ImageView01);
img.setImageBitmap(bitmap);
}
}
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
addImageToGallery(imageFilePath, context);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Video captured and saved to fileUri specified in the Intent
addVideoToGallery(videoFilePath, context);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
} else {
// Video capture failed, advise user
}
}
}
public Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor = getContentResolver()
.openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor
.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
} else
return uri.getPath();
}
private void loadPicasaImageFromGallery(final Uri uri) {
String[] projection = { MediaColumns.DATA, MediaColumns.DISPLAY_NAME };
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(MediaColumns.DISPLAY_NAME);
if (columnIndex != -1) {
new Thread(new Runnable() {
// NEW THREAD BECAUSE NETWORK REQUEST WILL BE MADE THAT WILL
// BE A LONG PROCESS & BLOCK UI
// IF CALLED IN UI THREAD
public void run() {
try {
Bitmap bm = android.provider.MediaStore.Images.Media
.getBitmap(getContentResolver(), uri);
int i = (int) (bm.getHeight() * (512.0 / bm
.getWidth()));
bitmap = Bitmap
.createScaledBitmap(bm, 512, i, true);
// THIS IS THE BITMAP IMAGE WE ARE LOOKING FOR
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
}
}
cursor.close();
}
/** Create a file Uri for saving an image or video */
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),
"MappyDiary");
// 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("MappyDiary", "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) {
imageFilePath = mediaStorageDir.getPath() + File.separator + "IMG_"
+ timeStamp + ".jpg";
mediaFile = new File(imageFilePath);
} else if (type == MEDIA_TYPE_VIDEO) {
videoFilePath = mediaStorageDir.getPath() + File.separator + "VID_"
+ timeStamp + ".mp4";
mediaFile = new File(videoFilePath);
} else {
return null;
}
return mediaFile;
}
public static void addImageToGallery(final String filePath,
final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
values);
}
public static void addVideoToGallery(final String filePath,
final Context context) {
ContentValues values = new ContentValues();
values.put(Video.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Video.Media.MIME_TYPE, "video/mp4");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Video.Media.EXTERNAL_CONTENT_URI,
values);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.Button01:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
selectPictureIntent = Intent
.createChooser(intent, "Select Picture");
startActivityForResult(selectPictureIntent, SELECT_PICTURE);
break;
case R.id.Button02:
// create Intent to take a picture and return control to the calling
// application
Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent2.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent2, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
default:
break;
}
}

Categories

Resources