Android Complete Action Using - android

Hi I have this button and when I click on it I'd like to launch a Complete Action Using window that would allow me to choose between Camera & Gallery.
Is there an easier way to implement this other than creating a dialog.

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
context.getString(R.string.Select_an_Option_to_add_Photo))
.setCancelable(true)
.setPositiveButton(context.getString(R.string.Camera),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
Intent action = new Intent(
"android.media.action.IMAGE_CAPTURE");
action.putExtra(
MediaStore.EXTRA_OUTPUT,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
.toString());
startActivityForResult(action, 8);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
})
.setNegativeButton(context.getString(R.string.Gallery),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
try {
Intent photoPickerIntent = new Intent(
Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
alert = builder.create();
Now
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == 8) {
Bitmap photoBitMap = (Bitmap) data.getExtras().get("data");
Bitmap usableBMP = Bitmap.createScaledBitmap(photoBitMap, 68, 80,
true);
//This is my ImageView Object
cameraButton.setImageBitmap(usableBMP);
cameraButton.setScaleType(ScaleType.CENTER_INSIDE);
} else if (resultCode == RESULT_OK) {
Uri chosenImageUri = data.getData();
try {
//Here I scale my Bitmap as desired
photoBitMap = Media.getBitmap(this.getContentResolver(),
chosenImageUri);
Bitmap usableBMP = Bitmap.createScaledBitmap(photoBitMap, 68,
80, true);
//this is my ImageView Object
cameraButton.setImageBitmap(usableBMP);
cameraButton.setScaleType(ScaleType.CENTER_INSIDE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Related

onActivityResult : android.net.Uri android.content.Intent.getData()' on a null object reference

Its work perfectly when i click image from the camera or back press from camera.
Ii also works perfectly when i select an image from the gallery but it occurs error when i back press from the gallery without selecting any image at this line filePath = data.getData();.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.net.Uri android.content.Intent.getData()' on a null
object reference
private void changeProfileImage() {
try {
PackageManager pm = getPackageManager();
int hasPerm = pm.checkPermission(Manifest.permission.CAMERA, getPackageName());
if (hasPerm == PackageManager.PERMISSION_GRANTED) {
final CharSequence[] options = {"Take Photo", "Choose From Gallery", "Cancel"};
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(AddProduct.this);
builder.setTitle("Select Option");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
dialog.dismiss();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, PICK_IMAGE_CAMERA);
} else if (options[item].equals("Choose From Gallery")) {
dialog.dismiss();
Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, PICK_IMAGE_GALLERY);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
} else Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_CAMERA) {
try {
bitmap = (Bitmap) data.getExtras().get("data");
pro_img.setImageBitmap(bitmap);
img = getEncoded64ImageStringFromBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == PICK_IMAGE_GALLERY) {
try {
filePath = data.getData();
if (filePath != null) {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
pro_img.setImageBitmap(bitmap);
img = getEncoded64ImageStringFromBitmap(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Yes, If you not selected any Image and simply come back from the Gallery , It will return null in the Intent Data. Check data!=null before taking getData()
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_CAMERA) {
try {
bitmap = (Bitmap) data.getExtras().get("data");
pro_img.setImageBitmap(bitmap);
img = getEncoded64ImageStringFromBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == PICK_IMAGE_GALLERY) {
try {
if(data!=null)
{ // user selects some Image
filePath = data.getData();
if (filePath != null) {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
pro_img.setImageBitmap(bitmap);
img = getEncoded64ImageStringFromBitmap(bitmap);
}
}
else
{ // user simply backpressed from gallery
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Upload image to server from gallary or camera android

i have a Activity for Upload image from gallary or camera to server.image upload from camera is fine but upload from gallary is not done.i have a error showing
BitmapFactory﹕ Unable to decode stream: FileNotFoundException
i want to do when i pick up the image from gallary it is shown in other Activity on image view.
i don't know how to get fileuri for gallary please help me.
my code:
loadimage = (ImageView) findViewById(R.id.profilpic);
loadimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
/* Intent i = new Intent(Tab1.this, ImageMain.class);
startActivity(i);*/
// selectImageFromGallery();
AlertDialog.Builder builder = new AlertDialog.Builder(Tab1.this);
builder.setMessage("Select Image From")
.setCancelable(true)
.setPositiveButton("camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
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_REQUEST);
}
})
.setNegativeButton("gallary", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
Hear is my onActiivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
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==RESULT_LOAD_IMAGE){
if (resultCode==RESULT_OK){
launchUploadActivity(true);
}
}
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(Tab1.this,UploadAvtivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
Here is the Code piece for Taking a Picture through Default Camera (here I implemented Intent to to fetch the image). After that store it to SD card(here a new file will be created and the newly taken image will be stored ); and if you don't want to store then remove the saving part from code. After that you can use the file path for your upload purpose. You can then refer it and change to get the path as your wish.
In the class area put these lines
final int TAKE_PHOTO_REQ = 100;
String file_path = Environment.getExternalStorageDirectory()
+ "/recent.jpg";//Here recent.jpg is your image name which will going to take
After that invoke the camera by putting these line in calling method.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PHOTO_REQ);
then add this method in your Activity to get the picture and save it to sd card and you can invoke your upload method from here to upload the image by knowing its path.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PHOTO_REQ: {
if (resultCode == TakePicture.RESULT_OK && data != null) {
Bitmap srcBmp = (Bitmap) data.getExtras().get("data");
// ... (process image if necesary)
imageView.setImageBitmap(srcBmp);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
srcBmp.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
// you can create a new file name "test.jpg" in sdcard folder.
File f = new File(file_path);
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// write the bytes in file
FileOutputStream fo = null;
try {
fo = new FileOutputStream(f);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// remember close de FileOutput
try {
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("take-img", "Image Saved to sd card...");
// Toast.makeText(getApplicationContext(),
// "Image Saved to sd card...", Toast.LENGTH_SHORT).show();
break;
}
}
}
}
Hope this will be helpful for you and others too .. thanks

Encoding and saving image to sd card

I have a problem where I have to take an Image from the gallery and save it to the memory card after compressing it. I am able to pick the image from the gallery and even save it. But somehow there seems to be some coding mistake due to which I can not open the Image. Here is the code:
public class MainActivity extends Activity {
ImageView image;
Button save, add;
String fileName;
final Context context = this;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save = (Button)findViewById(R.id.buttonSave);
add = (Button)findViewById(R.id.buttonAdd);
image = (ImageView)findViewById(R.id.imageView);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}
});
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.rename_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editRename);
alertDialogBuilder
.setTitle("Save Image")
.setMessage("Enter name")
.setNegativeButton("Save", new DialogInterface.OnClickListener() {
//
#Override
public void onClick(DialogInterface dialog, int which) {
fileName = userInput.getText().toString();
Log.d("Name" , fileName);
saveFile(null, fileName);
Toast.makeText(getApplicationContext(), "Image saved", Toast.LENGTH_SHORT).show();
}
})
.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
Toast.makeText(getApplicationContext(), "Image save cancelled", Toast.LENGTH_SHORT).show();
}
});
AlertDialog build = alertDialogBuilder.create();
build.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
Uri targetUri = data.getData();
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
image.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void saveFile(Bitmap images, String fileName) {
BitmapDrawable drawable = (BitmapDrawable) image.getDrawable();
bitmap = drawable.getBitmap();
File sdCard = Environment.getExternalStorageDirectory();
File pic = new File(sdCard , fileName + ".jpeg");
boolean success = false;
FileOutputStream outStream;
try {
outStream = new FileOutputStream(pic);
//bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
}
}

onActivityResult not called when launching camera intent?

I have an activity where click of button camera activity is launched . Sometimes onActivityResult is called and sometimes not . Even after restarting the device the onActivityResult is not called nor does it restart the current activity . Any solution to this weird behavior ?
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
String imageUri = data.toURI();
Uri uri = Uri.parse(imageUri);
try {
mBitmap = Media.getBitmap(getContentResolver(), uri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// if result is ok returns the bitmap
// mBitmap = (Bitmap) data.getExtras().get("data");
mImageView.setImageBitmap(mBitmap);
new Thread(postTheImage).start();
} else {
Toast.makeText(getApplicationContext(), "Error during capturing the image", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.capture_image_button) {
// Open the camera to capture the image
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
You are not providing the camera activity with the information it requires. You need to supply it a file URI.
Please refer to the following
onActivityResult returned from a camera, Intent null

camera activity gives null pointer exception

in my camera intent:
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
this part gives me a null pointer exception.
can anyone explain why and what need to be changed??
button_1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
startActivityForResult(intent, TAKE_PICTURE);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
}
Try the following,
public class Camera extends Activity
{
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
WebView webview;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent cameraIntent = new Intent(ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
Random randomGenerator = new Random();randomGenerator.nextInt();
String newimagename=randomGenerator.toString()+".jpg";
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + newimagename);
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//write the bytes in file
try {
fo = new FileOutputStream(f.getAbsoluteFile());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
uri=f.getAbsolutePath();
//this is the url that where you are saved the image
}
}

Categories

Resources