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();
}
Related
I am trying to put an image on my fragment, but the image is not showing up. I am certain that it was working just yesterday but now it is not. Any help is appreciated.
This code is in my Fragment:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mUser = (User) getArguments().getSerializable(ARGS_USER);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_picture_picker, container, false);
mImageView = v.findViewById(R.id.imageView);
mSelectImageButton = v.findViewById(R.id.select_image);
mSelectImageButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMG_REQUEST);
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == IMG_REQUEST && resultCode == Activity.RESULT_OK && data != null){
Uri path = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), path);
mImageView.setImageBitmap(bitmap);
mImageView.setVisibility(View.VISIBLE);
mUser.setProfilePicture(bitmap);
}catch(IOException e){
e.printStackTrace();
}
}
}
Actually you are not using the Volley. Please change the heading of your question. You are accessing the Gallery and showing the image inside the imageView. Use the below code for accessing the image from camera as well as gallery.
if (action.equals("CAMERA")) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, ACTION_REQUEST_CAMERA);
} else {
openCamera();
}
} else if (action.equals("GALLERY")) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, ACTION_REQUEST_GALLERY);
} else {
openGallery();
}
}
private void openCamera(){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
getActivity().startActivityForResult(cameraIntent, ACTION_REQUEST_CAMERA);
}
private void openGallery(){
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
Intent chooser = Intent.createChooser(galleryIntent, "Choose a Picture");
getActivity().startActivityForResult(chooser, ACTION_REQUEST_GALLERY);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("OnActivityResult");
System.out.println("resultCode: "+resultCode+"\n"+"requestCode: "+requestCode);
ImageOperations operations = new ImageOperations();
if (resultCode == RESULT_OK) {
if (requestCode == ACTION_REQUEST_GALLERY) {
System.out.println("select file from gallery ");
Uri selectedImageUri = data.getData();
renderProfileImage(selectedImageUri,operations);
} else if (requestCode == ACTION_REQUEST_CAMERA) {
System.out.println("select file from camera ");
Bitmap photo = (Bitmap) data.getExtras().get("data");
String name = "profile_pic.png";
operations.saveImageToInternalStorage(photo,getActivity(),name);
profile_image.setImageBitmap(photo);
}
}
}
private void renderProfileImage(Uri selectedImageUri,ImageOperations operations) {
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImageUri);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
String name = "profile_pic.png";
operations.saveImageToInternalStorage(bitmap,getActivity(),name);
profile_image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
private class ImageOperations {
public boolean saveImageToInternalStorage(Bitmap image, Context context, String name) {
try {
// Use the compress method on the Bitmap object to write image to
// the OutputStream
FileOutputStream fos = context.openFileOutput("profile_pic.png", Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}
public Bitmap getThumbnail(Context context,String filename) {
String fullPath = Environment.getDataDirectory().getAbsolutePath();
Bitmap thumbnail = null;
// Look for the file on the external storage
try {
if (isSdReadable() == true) {
thumbnail = BitmapFactory.decodeFile(fullPath + "/" + filename);
}
} catch (Exception e) {
Log.e("Image",e.getMessage());
}
// If no file on external storage, look in internal storage
if (thumbnail == null) {
try {
File filePath = context.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
thumbnail = BitmapFactory.decodeStream(fi);
} catch (Exception ex) {
Log.e("getThumbnail()", ex.getMessage());
}
}
return thumbnail;
}
public boolean isSdReadable() {
boolean mExternalStorageAvailable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = true;
Log.i("isSdReadable", "External storage card is readable.");
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
Log.i("isSdReadable", "External storage card is readable.");
mExternalStorageAvailable = true;
} else {
// Something else is wrong. It may be one of many other
// states, but all we need to know is we can neither read nor write
mExternalStorageAvailable = false;
}
return mExternalStorageAvailable;
}
}
action is like what you want to do. ACTION_REQUEST_GALLERY and ACTION_REQUEST_CAMERA use some integer constants like 100 and 101. profileImage is your ImageView.
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.
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
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();
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();
}
}