post image and video on twitter using fabric lib in android - android

i post the tweet(text) successfully but can not post image and video.
my PostActivity.java
public class PostActivity extends Activity implements View.OnClickListener{
TwitterApiClient twitterApiClient;
private EditText mShareEditText;
private TextView userName;
private ImageView imgPreview;
private VideoView videoPreview;
private Button btn_tweet, btn_capture;
private ProgressDialog pDialog;
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;
private Uri fileUri;
private static final String IMAGE_DIRECTORY_NAME = "Hello Twitter";
static File mediaFile;
static File mediaStorageDir;
TypedFile typedFile;
TwitterSession session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mShareEditText = (EditText) findViewById(R.id.share_text);
userName = (TextView) findViewById(R.id.user_name);
imgPreview = (ImageView)findViewById(R.id.imageView);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
/* register button click listeners */
btn_tweet = (Button)findViewById(R.id.btn_tweet);
btn_tweet.setOnClickListener(this);
btn_capture = (Button)findViewById(R.id.btn_Capture);
btn_capture.setOnClickListener(this);
session = Twitter.getSessionManager()
.getActiveSession();
twitterApiClient = TwitterCore.getInstance().getApiClient(session);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_tweet:
getTwitterData(session);
break;
case R.id.btn_Capture:
selectImage();
break;
}
}
public void getTwitterData(final TwitterSession session) {
typedFile = new TypedFile("image/jpeg", mediaFile);
MyTwitterApiClient tapiclient = new MyTwitterApiClient(session);
tapiclient.getCustomService().upload(typedFile, new Callback<TwitterMedia>() {
#Override
public void success(Result<TwitterMedia> result) {
Toast.makeText(getApplicationContext(),"upload image",Toast.LENGTH_LONG).show();
}
#Override
public void failure(TwitterException e) {
}
});
tweet();
}
public void tweet() {
String strMessage = mShareEditText.getText().toString();
StatusesService statusesService = twitterApiClient.getStatusesService();
statusesService.update(strMessage, null, null, null, null, null, null, null, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> tweetResult) {
Toast.makeText(getApplicationContext(),"Successfully Post on twitter",Toast.LENGTH_LONG).show();
}
#Override
public void failure(TwitterException e) {
e.printStackTrace();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
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();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* 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");
}
/**
* 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();
}
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
public static File getOutputMediaFile(int type){
// External sdcard location
mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
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;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Tack Video","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(PostActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
} else if (options[item].equals("Tack Video")) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
}
i have display image and video on imageview and videoview by using camera(capture).
plz help me
thanks in advance

Please check for Image upload using Fabric
Fabric Compose Tweet

your code has missing parts. could you add MyTwitterApiClient class and check this out for media upload : http://twitter4j.org/en/index.html

Related

cannot fetch images using camera android

The application, is supposed to get an image from Camera or Gallery (user's choice) then, upload it to server.
There's no problem with getting an image from the gallery and uploading it to server.
The problem here is retrieving an image taken by the camera !
public class UploadActivity extends AppCompatActivity implements View.OnClickListener {
private Button UploadBn;
private ImageButton ChooseBn, CameraBn;
private EditText NAME;
private ImageView imgView;
private CameraPhoto cameraPhoto;
private GalleryPhoto galleryPhoto;
final int CAMERA_REQUEST=13323;
final int GALLERY_REQUEST=22131;
private String selectedPhoto;
private Bitmap bitmap = null;
private String UploadUrl="http://localhost/webapp/getImg.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
NAME=(EditText)findViewById(R.id.name);
UploadBn=(Button)findViewById(R.id.uploadBn);
ChooseBn=(ImageButton) findViewById(R.id.ivGallery);
CameraBn=(ImageButton) findViewById(R.id.ivCamera);
imgView=(ImageView)findViewById(R.id.imageView);
cameraPhoto = new CameraPhoto(getApplicationContext());
galleryPhoto = new GalleryPhoto(getApplicationContext());
ChooseBn.setOnClickListener(this);
UploadBn.setOnClickListener(this);
CameraBn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.ivGallery:
selectImageGalerie();
break;
case R.id.uploadBn:
if(NAME==null || imgView.getDrawable()==null)
Toast.makeText(this,"select an image, give it a name",Toast.LENGTH_LONG).show();
else
uploadImage();
break;
case R.id.ivCamera:
selectImageCamera();
break;
}
}
private void selectImageGalerie() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,GALLERY_REQUEST);
}
private void selectImageCamera() {
try {
startActivityForResult(cameraPhoto.takePhotoIntent(), CAMERA_REQUEST);
cameraPhoto.addToGallery();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Somathing Wrong while taking photos", Toast.LENGTH_SHORT).show();
}
}
private String imageToString(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
byte[] imgBytes=byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgBytes, Base64.DEFAULT);
}
private void uploadImage() {
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
StringRequest stringRequest=new StringRequest(Request.Method.POST, UploadUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
Toast.makeText(UploadActivity.this, response , Toast.LENGTH_LONG).show();
imgView.setImageResource(0);
imgView.setVisibility(View.GONE);
NAME.setText("");
NAME.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
loading.dismiss();
Toast.makeText(UploadActivity.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<>();
params.put("name",NAME.getText().toString().trim()+".jpg");
params.put("encoded",imageToString(bitmap));
return params;
}
};
MySingleton.getInstance(UploadActivity.this).addToRequestQue(stringRequest);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode==RESULT_OK && data != null){
if(requestCode==GALLERY_REQUEST) {
Uri path = data.getData();
galleryPhoto.setPhotoUri(path);
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), path);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(requestCode==CAMERA_REQUEST) {
String photoPath=cameraPhoto.getPhotoPath();
selectedPhoto=photoPath;
try {
Log.d("BITMAP ==", "AWEL EL TRY");
bitmap= ImageLoader.init().from(photoPath).requestSize(300,300).getBitmap();
imgView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),"Something Wrong while choosing photos",Toast.LENGTH_SHORT).show();
}
}
imgView.setImageBitmap(bitmap);
imgView.setVisibility(View.VISIBLE);
NAME.setVisibility(View.VISIBLE);
Log.d("BITMAP ==", "E5ER EL TRY");
}
}
}
After performing some tests, I found out that the variable data is null so it skips all the if() statement in the onActivityResult() method.
It doesn't make sense, why would the camera not return a value even though I took a picture !
why would the camera not return a value even though I took a picture
If you provide EXTRA_OUTPUT on the Intent, ACTION_IMAGE_CAPTURE does not need to return a result. I assume that is what takePhotoIntent() does.
Moreover, the rest of your code for the requestCode==CAMERA_REQUEST branch does not use the data Uri anyway.
Hello for a quick fix try the provided code and for more in-depth learning read this https://developer.android.com/training/camera/photobasics.html
Call captureImage() method instead of selectImageCamera() on R.id.uploadBn button click.
private Uri fileUri; // file url to store image/video
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "MyPhotos";
Capturing Camera Image will lauch camera app request 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);
}
Creating file uri to store image/video
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
Returning image
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");
}
return mediaFile;
}
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
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();
}
}
}
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);
imgView.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}

Cannot Upload Image From Gallery in Android Studio

I want to upload image from gallery in my android app. When I click on button, the gallery should be opened. After selecting image, I want to open another activity named UploadActivity. There the thumbnail of the image should be previewed. The Upload Button will below the thumbnail.
But when I Choose photo from gallery, then the thumbnail of the image are not previewing. I am unable to upload the photo also. My Code goes here: (Scan.Java)
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int SELECT_IMAGE = 2;
private Uri fileUri; // file url to store image/video
ImageView dummy;
private Button btnCapturePicture;
private Button btnGallery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scan);
dummy = (ImageView) findViewById(R.id.dummyphoto);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnGallery = (Button) findViewById(R.id.btnGallery);
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
btnGallery.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
openGallery();
}
});
// 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;
}
}
/**
* Launching camera app to capture image
*/
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);
}
/**
* Launching Gallery to Choose Image
*/
private void openGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(Intent.createChooser(intent, "Select Image"),SELECT_IMAGE);
}
/**
* 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 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");
}
/**
* 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
// launching upload activity
launchUploadActivity(true);
} 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 == SELECT_IMAGE)
{
if (resultCode == Activity.RESULT_OK)
{
if (data != null)
{
launchUploadActivity(true);
}
} else if (resultCode == Activity.RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(Scan.this, UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
UploadActivity.Java Code goes here:
private ProgressBar progressBar;
private String filePath = null;
private TextView txtPercentage;
private ImageView imgPreview;
private Button btnUpload;
long totalSize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
txtPercentage = (TextView) findViewById(R.id.txtPercentage);
btnUpload = (Button) findViewById(R.id.btnUpload);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
// Receiving the data from previous activity
Intent i = getIntent();
// image path that is captured in previous activity
filePath = i.getStringExtra("filePath");
// boolean flag to identify the media type, image
boolean isImage = i.getBooleanExtra("isImage", true);
if (filePath != null) {
// Displaying the image on the screen
previewMedia(isImage);
} else {
Toast.makeText(getApplicationContext(),
"Sorry, file path is missing!", Toast.LENGTH_LONG).show();
}
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// uploading the file to server
new UploadFileToServer().execute();
}
});
}
/**
* Displaying captured image on the screen
* */
private void previewMedia(boolean isImage) {
// Checking whether captured media is image
if (isImage) {
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// down sizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
imgPreview.setImageBitmap(bitmap);
} else {
imgPreview.setVisibility(View.GONE);
}
}
/**
* Uploading the file to server
* */
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
Here is Logcat:
E/MainActivity: Response from server: java.io.FileNotFoundException: /mnt/sdcard/Pictures/master/IMG_20170127_152930.jpg: open failed: ENOENT (No such file or directory)
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "IMG_20170127_152930.jpg");
//Try this.
After these changes i suggested below I hope your problem will be solved:
Remove these two lines from openGallery() because I think they are redundant.
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
They are needed when we use Intent.ACTION_PICK. So after editing openGallery() looks like:
private void openGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"),SELECT_IMAGE);
}
Add this statement in your onActivityResult() :
fileUri = data.getData();
so it looks:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
...
else if (requestCode == SELECT_IMAGE)
{
if (resultCode == Activity.RESULT_OK)
{
if (data != null)
{
fileUri = data.getData(); //added this line
launchUploadActivity(true);
}
} else if (resultCode == Activity.RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
Same applies to the camera intent also.
Request EXTERNAL_STORAGE permission and also run time permission if your target Android version is 6.0 or above.
EDIT:
Sorry couple of things I have not mentioned those are required are given bellow:
You may like to send the Uri instead of path this way:
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(this, UploadActivity.class);
i.setData(fileUri);
// i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
And then in UploadActivity do the following:
...
private InputStream mInputStream; // Use this stream to create bitmap and upload to server
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// Receiving the data from previous activity
Intent i = getIntent();
try {
mInputStream = getContentResolver().openInputStream(i.getData());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
...
}
...
...
private void previewMedia(boolean isImage){
if (isImage) {
imgPreview.setVisibility(View.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeStream(mInputStream,null,options);
imgPreview.setImageBitmap(bitmap);
} else {
imgPreview.setVisibility(View.GONE);
}
}
...
This works for me and hope will work on you too.

Capture and display image with custom camera app

It's bugging me for few days know. Problem is that I don't know if I'm going in right direction.
My starting activity is ImageDisplay class which calls startActivityForRestult for CustomCamera activity. After picture is taken user is returned to ImageDisplay and capture image should be displayed, but its not. What am I doing wrong?
Second thing, I guess its really important, at which point camera should be released?
ImageDisplay:
public class ImageDisplay extends Activity{
ImageView imageHolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.al_imagedisplay);
imageHolder = (ImageView) findViewById(R.id.imageView1);
Intent intent = new Intent(this, CustomCamera.class);
startActivityForResult(intent, 0);
}
#Override
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) {
Bitmap photo = (Bitmap) data.getExtras().get("result");
imageHolder.setImageBitmap(photo);
}
}
}
CustomCamera:
public class CustomCamera extends Activity {
private Camera mCamera;
private NewItemSurfaceView mPreview;
Button captureButton;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
public static final String MY_CAMERRA_APP = "MyCameraApp";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.al_newitem_camera);
captureButton = (Button) findViewById(R.id.buttonClick);
// Create an instance of Camera
mCamera = getCameraInstance();
mCamera.setDisplayOrientation(90);
// Create our Preview view and set it as the content of our activity.
mPreview = new NewItemSurfaceView(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.flCamera);
preview.addView(mPreview);
// Add a listener to the Capture button
captureButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
});
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null) {
Log.d("Camera error",
"Error creating media file, check storage permissions: ");
return;
}
Log.i("Picture", pictureFile.toString());
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("Camera error", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Camera error", "Error accessing file: " + e.getMessage());
}
Intent returnIntent = new Intent();
returnIntent.putExtra("result", pictureFile);
setResult(RESULT_OK, returnIntent);
finish();
}
};
/** 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_DCIM),
"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.i("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 if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
modify onActivityResult method like this
#Override
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) {
String photoPath = (String) data.getExtras().get("result");
imageHolder.setImageBitmap(BitmapFactory.decodeFile("photoPath"));
}
}
Do some modification in your onPictureTaken method like this
Intent returnIntent = getIntent();
returnIntent.putExtra("result", pictureFile.getAbsolutePath());
setResult(RESULT_OK, returnIntent);
finish();

Just recorded Video/Audio is not played with some devices. Getting "sorry, video cannot be played", but same video played in gallery

Just recorded Video/Audio is not played with some devices. Getting "sorry, video cannot be played", but same video played in gallery.Just recorded Video/Audio is not played with some devices. Getting "sorry, video cannot be played", but same video played in gallery.
below is my code
public class CaptureImageActivity 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 = "ICS Camera";
private Uri fileUri; // file url to store image/video
private ImageView imgPreview;
private VideoView videoPreview;
private TextView cancel, send;
private Intent intent1;
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
HomeActivity.myempid = 1;
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_capture_image);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
cancel = (TextView) findViewById(R.id.cancel);
send = (TextView) findViewById(R.id.send);
int mode = getIntent().getIntExtra(
ApplicationConstants.IntentKeys.KEY_MODE, 0);
try {
if (HomeActivity.camera != null) {
HomeActivity.camera.release();
HomeActivity.camera = null;
}
} catch (Exception e) {
e.printStackTrace();
}
if (mode == 0)
captureImage();
else
recordVideo();
/*
* Capture image button click event
*/
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
CaptureImageActivity.this.finish();
}
});
/*
* Record video button click event //
*/
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent picMessageIntent = new Intent(
android.content.Intent.ACTION_SEND);
picMessageIntent.setType("image/jpeg");
File downloadedPic = new File(fileUri.getPath());
System.out.println("PATH " + fileUri.getPath());
picMessageIntent.putExtra(Intent.EXTRA_STREAM,
Uri.fromFile(downloadedPic));
startActivity(picMessageIntent);
// CaptureImageActivity.this.finish();
}
});
// 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() {
intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent1.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent1, 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() {
intent1 = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent1.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent1.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image
// file
// name
// start the video capture Intent
startActivityForResult(intent1, 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) {
System.out.println("RESULT CANCELED");
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
CaptureImageActivity.this.finish();
} 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
// sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
// Uri.parse(fileUri.getPath())));
System.out.println("RESULT OK");
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
finish();
} else {
System.out.println("FAIL");
// 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);
System.out.println(bitmap);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/*
* Previewing recorded video
*/
private void previewVideo() {
try {
System.out.println("PATH " + fileUri.getPath());
getContentResolver().notifyChange(Uri.parse(fileUri.getPath()),
null);
MediaController mc = new MediaController(this);
mc.setAnchorView(videoPreview);
// mc.setMediaPlayer(videoPreview);
// hide image preview
// videoPreview.setOnPreparedListener(new OnPreparedListener() {
//
// public void onPrepared(MediaPlayer mp) {
// // TODO Auto-generated method stub
// mp.start();
// }
// });
imgPreview.setVisibility(View.GONE);
// getWindow().clearFlags(
// WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
// WindowManager.LayoutParams.FLAG_FULLSCREEN);
videoPreview.setVisibility(View.VISIBLE);
// 02-15 11:51:52.973: I/System.out(17840): PATH
// /mnt/sdcard/Pictures/ICS Camera/VID_20140215_115133.mp4
videoPreview.setVideoPath(fileUri.getPath());
// videoPreview.setVideoURI(Uri.parse(Provoder.CONTENT_URI_BASE
// + Uri.encode(fileUri.getPath())));
videoPreview.setMediaController(mc);
videoPreview.requestFocus();
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;
}
}
Solved my issue by using below code
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import com.kubical.ES.R;
import com.kubical.ES.util.ApplicationConstants;
public class CaptureImageActivity 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 ImageView imgPreview;
private VideoView videoPreview;
private TextView cancel, send;
private Intent intent1;
private String filePath;
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
HomeActivity.myempid = 1;
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_capture_image);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
cancel = (TextView) findViewById(R.id.cancel);
send = (TextView) findViewById(R.id.send);
int mode = getIntent().getIntExtra(
ApplicationConstants.IntentKeys.KEY_MODE, 0);
try {
if (HomeActivity.camera != null) {
HomeActivity.camera.release();
HomeActivity.camera = null;
}
} catch (Exception e) {
e.printStackTrace();
}
if (mode == 0)
captureImage();
else
recordVideo();
/*
* Capture image button click event
*/
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
CaptureImageActivity.this.finish();
}
});
/*
* Record video button click event //
*/
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent picMessageIntent = new Intent(
android.content.Intent.ACTION_SEND);
picMessageIntent.setType("image/jpeg");
File downloadedPic = new File(filePath);
System.out.println("PATH " + filePath);
picMessageIntent.putExtra(Intent.EXTRA_STREAM,
Uri.fromFile(downloadedPic));
startActivity(picMessageIntent);
// CaptureImageActivity.this.finish();
}
});
// 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() {
intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent1, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/*
* Recording video
*/
private void recordVideo() {
intent1 = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intent1, 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) {
previewCapturedImage(data);
} else if (resultCode == RESULT_CANCELED) {
System.out.println("RESULT CANCELED");
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
CaptureImageActivity.this.finish();
} 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) {
previewVideo(data);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
finish();
} else {
System.out.println("FAIL");
// 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(Intent data) {
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;
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]);
filePath = cursor.getString(columnIndex);
System.out.println("PATH IS " + filePath);
cursor.close();
final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
System.out.println(bitmap);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/*
* Previewing recorded video
*/
private void previewVideo(Intent data) {
try {
Uri contentUri = data.getData();
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null,
null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
filePath = cursor.getString(column_index);
MediaController mc = new MediaController(this);
mc.setAnchorView(videoPreview);
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(filePath);
videoPreview.setMediaController(mc);
videoPreview.requestFocus();
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}

android camera creates file with 0kb in external sd card folder on camera cancle

a bit issue in my code, please help me to overcome this
i have an activity which captures an image & saves in app folder which is working fin. on click save button it saves the image in folder but when user cancle camera activity then 0kb file is created as well in folder, how to avoid this
here is my code related to camera activity
public class camera extends Activity {
private static final int ACTION_TAKE_PHOTO_B = 1;
private static final String BITMAP_STORAGE_KEY = "viewbitmap";
private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
private ImageView mImageView;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private File getAlbumDir() {
String path = Environment.getExternalStorageDirectory().toString();
File filenamedemo = new File(path + "/ImageFolder/");
String name = String.valueOf(filenamedemo);
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
if (name != null) {
if (!filenamedemo.mkdirs()) {
if (!filenamedemo.exists()) {
return null;
}
}
}
} else {
}
return filenamedemo;
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date(0));
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX,
albumF);
return imageF;
}
private File setUpPhotoFile() throws IOException {
File f = createImageFile();
mCurrentPhotoPath = f.getAbsolutePath();
return f;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(
"android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = null;
try {
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
takePictureIntent
.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
startActivityForResult(takePictureIntent, ACTION_TAKE_PHOTO_B);
}
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;
}
}
private void handleBigCameraPhoto() {
if (mCurrentPhotoPath != null) {
// setPic();
// galleryAddPic();
mCurrentPhotoPath = null;
Intent viewint = new Intent(camera.this, TashPatti.class);
startActivity(viewint);
finish();
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dispatchTakePictureIntent();
/*
* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
* mAlbumStorageDirFactory = new FroyoAlbumDirFactory(); } else {
* mAlbumStorageDirFactory = new BaseAlbumDirFactory(); }
*/
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ACTION_TAKE_PHOTO_B) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "picture saved.", Toast.LENGTH_LONG)
.show();
handleBigCameraPhoto();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
Toast.makeText(this, "User cancelled the image capturing.",
Toast.LENGTH_LONG).show();
} else {
// Video capture failed, advise user
Toast.makeText(this, "image capture failed.", Toast.LENGTH_LONG)
.show();
}
}
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY,
(mImageBitmap != null));
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
mImageView.setImageBitmap(mImageBitmap);
mImageView
.setVisibility(savedInstanceState
.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ? ImageView.VISIBLE
: ImageView.INVISIBLE);
}
}
any help will appreciatd,
thank you :)
i solved my issue by deleting the 0 size file, in onActivitiResult(),
i got what i want but it is not clear to me why my code creates 0 size file after cancle operation ??
refrence for others ,enjoy coding
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ACTION_TAKE_PHOTO_B) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "picture saved.",
Toast.LENGTH_LONG).show();
Bitmap photo = (Bitmap) data.getExtras().get("data");
byte[] byteData = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, baos);
byteData = baos.toByteArray();
//handleBigCameraPhoto();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
Toast.makeText(this, "User cancelled the image capturing.",
Toast.LENGTH_LONG).show();
} else {
// Video capture failed, advise user
Toast.makeText(this, "image capture failed.",
Toast.LENGTH_LONG).show();
}
//this code delete the file if itz size is 0, 0 size occers wheen user cancles the
//camera activity so to avoid 0 size file in our folder we are deleting it
File file= filePath;
Log.i("lengthhh", Long.toString(file.length()));
if(file.exists() && file.length()==0)
{
file.delete();
}
Intent viewint=new Intent(camera.this, TashPatti.class);
startActivity(viewint); finish();
}
}

Categories

Resources