onActivityResult() does not call - android

The onActivityResult() did not called when I select image from camera or gallery and my activity crashed, my code is below:
private void selectImage() {
final CharSequence[] options = { "cam", "gallery","cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(FragmentActivity4.this);
builder.setTitle("add");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(FragmentActivity4.this);
if (options[item].equals("cam"))
{
if(result){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}}
else if (options[item].equals("gallery"))
{
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
startActivityForResult(chooserIntent, 2);
}
else if (options[item].equals("cancel")) {
ivImage.setImageDrawable(ContextCompat.getDrawable(FragmentActivity4.this, R.drawable.plusrred));
dialog.dismiss();
}
}
});
builder.show();
}
and in my onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode ==Activity.RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
ivImage.setImageBitmap(bitmap);
Bitmap bitmap1 = Bitmap.createScaledBitmap(bitmap,(int)(bitmap.getWidth()*0.03), (int)(bitmap.getHeight()*0.03), true);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.PNG, 0, baos1);
byte[] imgBytes = baos1.toByteArray();
base64String1 = Base64.encodeToString(imgBytes, Base64.DEFAULT);
String path = android.os.Environment.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 0, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = FragmentActivity4.this.getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........", picturePath+"");
ivImage.setImageBitmap(thumbnail);
Bitmap thumbnail1 = Bitmap.createScaledBitmap(thumbnail,(int)(thumbnail.getWidth()*0.03), (int)(thumbnail.getHeight()*0.03), true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbnail1.compress(Bitmap.CompressFormat.PNG,0, baos);
byte[] imgBytes = baos.toByteArray();
base64String1 = Base64.encodeToString(imgBytes,
Base64.DEFAULT);
}
}
My activity extends AppCompatActivity.
Could you please tell me where is the problem?

Here you have
startActivityForResult(chooserIntent, 2);
and in your onActivityResult method you don't include 2 in your if statement. I think the problem is in that.

Your RequestCode is 2.
Change this:
if (requestCode == 1) {
With this:
if (requestCode == 2) {

Related

Android: How to upload photo from ImageView?

Hi guys, how can I upload the image to my filemanager on my webhost when I click the button rent? As of now I don't start on anything because I tried to upload it the way I upload from gallery and It didnt work. Can you help me guys? As of now I cleaned my code and this is it
#Override
public void onClick(View v) {
HashMap postData = new HashMap();
postData.put("txtCarModel", tvCarModel.getText().toString());
postData.put("txtCarType", tvCarType.getText().toString());
postData.put("txtCapacity", tvCapacity.getText().toString());
postData.put("txtPlateNumber", tvPlateNumber.getText().toString());
postData.put("image", toString());
postData.put("txtFuelType", tvFuelType.getText().toString());
postData.put("txtOwner", tvPoster.getText().toString());
if (TextUtils.isEmpty(etResDate.getText().toString())) {
Toast.makeText(this, "Insert reservation date.", Toast.LENGTH_SHORT).show();
return;
}
postData.put("txtResDate", etResDate.getText().toString());
if (TextUtils.isEmpty(etResTime.getText().toString())) {
Toast.makeText(this, "Insert reservation time.", Toast.LENGTH_SHORT).show();
return;
}
postData.put("txtResTime", etResTime.getText().toString());
if (TextUtils.isEmpty(etResLocation.getText().toString())) {
Toast.makeText(this, "Insert pickup location.", Toast.LENGTH_SHORT).show();
return;
}
postData.put("txtResLocation", etResLocation.getText().toString());
postData.put("txtRenter", pref.getString("username","").toString());
PostResponseAsyncTask taskPost = new PostResponseAsyncTask(DetailActivity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
if (s.contains("New records created successfully")) {
Log.d(TAG, s);
Toast.makeText(DetailActivity.this, "Wait for owners approval", Toast.LENGTH_SHORT).show();
Intent in = new Intent(DetailActivity.this, RenterTabs.class);
startActivity(in);
finish();
} else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
});
taskPost.execute("http://carkila.esy.es/rent.php");
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
CustomerRegistration.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);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
// Rorate to portraite
Matrix matrix = new Matrix();
matrix.postRotate(getImageOrientation(f.getAbsolutePath()));
bitmap = Bitmap
.createBitmap(bitmap,0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
// End rotrate to portait
//set Image view
img_user_photo.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath,
null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap bitmap = (BitmapFactory.decodeFile(picturePath));
// Rorate to portraite
Matrix matrix = new Matrix();
matrix.postRotate(getImageOrientation(picturePath));
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
//set Image view
img_user_photo.setImageBitmap(bitmap);
}
}
}
// *****Just call method selectImage() ******
img_user_photo //Image view

How to show preview of the image clicked?

using custom camera how can we show the preview of the fullsize image after the image is being clicked from camera clicked and in preview if we can show whether to accept the image or discard the image before saving it to SD card.(Hint: As used in watsapp)
You will get image in byte[], you can convert this byte[] into bitmap and can show it in ImageView
Bitmap bitmap = BitmapFactory.decodeByteArray(yourbytearray, 0, yourbytearray.length);
The complete code according to your requirement is given below. Just follow this.Here uImage is Bitmap and imageView is the imageview where your image will be displayed.
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(AddownRecipeFromHome.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);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
uImage = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
imageView.setImageBitmap(uImage);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
uImage.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
uImage = (BitmapFactory.decodeFile(picturePath));
Log.e("path of imag", ""+picturePath);
imageView.setImageBitmap(uImage);
}
else if (requestCode == 3) {
try {
Log.e("testing", "return data is " + data.getData());
String filePath = Environment.getExternalStorageDirectory()
+ "/" + TEMP_PHOTO_FILE;
System.out.println("path " + filePath);
uImage = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
uImage.compress(Bitmap.CompressFormat.PNG, 100, bao);
ba = bao.toByteArray();
imageView.setImageBitmap(uImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private File getTempFile() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(),
TEMP_PHOTO_FILE);
try {
file.createNewFile();
} catch (IOException e) {
}
return file;
} else {
return null;
}
}

Android "TAKE PHOTO" - Image which is clicked is getting saved as a corrupt image

I have a button, which opens up a dialog box asking user to either "Take Picture" or "Choose from gallery".
I am facing issues when user "Take photo" , image is getting clicked, and for verification purpose I am setting Bitmap image inside the circularImage view, but when I go to specified location path of the image, either Image is not there or Image is corrupted.
Also I am trying to upload the image to the server using AsyncHttpClient in android but not being able to do it successfully.
Everytime I am getting Java Socket TimeOut Exception.
Below is the code for my Camera Intent Activity
public class AddAnUpdateActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.composeEditText = (EditText) findViewById(R.id.composeEditText);
setContentView(R.layout.add_update);
ProfilePictureImage = (CircularImageView) findViewById(R.id.ProfilePic);
insertVideo = (ImageButton) findViewById(R.id.insertVideoButton);
setBtnListenerOrDisable(insertVideo,mTakeVidOnClickListener, MediaStore.ACTION_VIDEO_CAPTURE);
insertImage = (ImageButton) findViewById(R.id.insertImageButton);
insertImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void setBtnListenerOrDisable(ImageButton btn,
Button.OnClickListener onClickListener,
String intentName) {
if (isIntentAvailable(this, intentName)) {
btn.setOnClickListener(onClickListener);
} else {
btn.setClickable(false);
}
}
private boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(AddAnUpdateActivity.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);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#SuppressLint("Assert")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
Log.d("PhotoImage","file path:"+f);
Log.d("PhotoImage","list of file path:"+ Arrays.toString(f.listFiles()));
for (File temp : f.listFiles()) {
if (temp.getName().equals("Image.jpg")) {
Log.w("PhotoImage","enter in if block");
f = temp;
break;
}
}
try {
Log.w("PhotoImage","enter in else block");
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);
ProfilePictureImage.setImageBitmap(bitmap);
if(bitmap!=null)
{
bitmap.recycle();
bitmap=null;
}
String path = android.os.Environment.getExternalStorageDirectory()+ File.separator+ "Pictures" + File.separator + "Screenshots";
Log.w("PhotoImage","path where the image is stored :"+path);
setFilePath(path);
f.delete();
OutputStream outFile;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
Log.w("PhotoImage","file value:"+String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
setFilePath(picturePath);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.d("PhotoImage path of image from gallery......******************.........", picturePath + "");
ProfilePictureImage.setImageBitmap(thumbnail);
}
else if(requestCode == 3){
handleCameraVideo(data) ;
}
}
}
private void handleCameraVideo(Intent data) {
VideoUri = data.getData();
VideoView.setVideoURI(VideoUri);
//mImageBitmap = null;
} }
private void startActivityFeedActivity() {
Intent i = new Intent(getApplicationContext(), ActivityFeedActivity.class);
startActivity(i);
}
}
I simplified your code .keep reference of file path global
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
globalpath =f.getAbsolutePath(); //String make it global
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
//your onactivityresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File myfile = new File(globalpath);
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(myfile.getAbsolutePath(),
bitmapOptions);
ProfilePictureImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Pictures" + File.separator + "Screenshots";
OutputStream outFile;
File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
myfile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Depending on your Android version and device, the camera intent is to be implemented differently. Check out https://github.com/ralfgehrer/AndroidCameraUtil. The code is tested on 100+ devices.
After take the photo remember to use this:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
to scan the media file in your gallery. If you doesn't do it your photo will appear after some time. You can do it in onClick:
insertImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
}
});

how to get the image path from this code

I have a imageview and clicking on it displays a dialog box and when clicked on each dialog item I can see a camera invoked or gallery invoked. But now after I get the image on the imageview how can I get the path of the image as an extra may be.
image_view = new ImageView(this);
image_view.setId(field_id);
image_view.setImageDrawable(getResources().getDrawable(
R.drawable.ic_launcher));
image_view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
selectImage();
}
});
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
Dynamic_layout.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);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "image1.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
} else if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("image1.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = 20;
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
image_view.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "PHOTO" + File.separator + "default";
// f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath,
null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = 20;
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath,
bitmapOptions));
Log.w("path of image in gallery", picturePath + "");
image_view.setImageBitmap(thumbnail);
}
}
}
Create a global variable String imagePath (outside onCreate) so all methods can access it.
Use this variable to get your path, so it can be used in the entire class :
try {
//add this
imagePath= f.getAbsolutePath();
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = 20;
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
Now you can use imagePath anywhere in the class.

attaching image using camera in android

I am working on a project where I have two choices, either I click a photo and the same image is attached to the mail and can be sent. The second is I select the image from the gallery and the image selected is sent as an attachment in the mail.I am able to do the later part but have problem in attaching image after clicking it using camera.
public class MainActivity extends Activity implements OnClickListener {
Button select;
ImageView photo;
EditText et_subject, et_message;
TextView tv_attach;
String subject, message;
private static final int PICK_IMAGE = 100;
Uri URI = null;
Uri URI1= null;
int columnindex;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
select = (Button)findViewById(R.id.button1);
photo = (ImageView)findViewById(R.id.imageView1);
et_subject = (EditText)findViewById(R.id.editText1);
et_message = (EditText)findViewById(R.id.editText2);
tv_attach = (TextView)findViewById(R.id.textView1);
photo.setOnClickListener(this);
select.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.imageView1:
selectImage();
break;
case R.id.button1:
subject = et_subject.getText().toString();
message = et_message.getText().toString();
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"example#xyz.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
if (URI != null || URI1 != null)
emailIntent.putExtra(Intent.EXTRA_STREAM, URI);
startActivity(emailIntent);
break;
default:
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds options to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.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);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
photo.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
URI1 = Uri.parse("file://" + path);
//f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
URI = Uri.parse("file://" + picturePath);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........", picturePath+"");
photo.setImageBitmap(thumbnail);
}
}
}
}
I've tried something but seems I'm wrong.
Please help me what can be done? Can anybody make changes in the code that I've used?
I tried it and it worked for me, hope it helps!
mail_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0){
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"fake#fake.edu"});
i.putExtra(Intent.EXTRA_SUBJECT,"On The Job");
//Log.d("URI#!##!#!###!", Uri.fromFile(pic).toString() + " " + pic.exists());
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic));
i.setType("image/png");
startActivity(Intent.createChooser(i,"Share you on the jobing"));
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
thumbnail = (Bitmap) data.getExtras().get("data");
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(thumbnail);
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
pic = new File(root, "pic.png");
FileOutputStream out = new FileOutputStream(pic);
thumbnail.compress(CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
} catch (IOException e) {
Log.e("BROKEN", "Could not write file " + e.getMessage());
}
}
}

Categories

Resources