I have two ImageView and two buttons. When button pressed - Dialog started. Positive answer - picture from galery, negative - from camera. First i write this in Activity(this code is work good):
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
String path = null;
if (DialogFlag == 0) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case GALLERY_REQUEST:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
path = getRealPathFromURI(selectedImage);
Log.d("myLogs", path);
if (btnID == 1) {
pathOne = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathOne);
ivOne.setImageBitmap(bmImg);
one = bmImg;
} else {
pathTwo = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathTwo);
ivTwo.setImageBitmap(bmImg);
two = bmImg;
}
}
}
}
if (DialogFlag == 1) {
Uri uri;
if (requestCode == CAMERA_RESULT) {
Cursor cursor = getContentResolver().query(
Media.EXTERNAL_CONTENT_URI,
new String[] { Media.DATA, Media.DATE_ADDED,
MediaStore.Images.ImageColumns.ORIENTATION },
Media.DATE_ADDED, null, "date_added ASC");
if (cursor != null && cursor.moveToFirst()) {
do {
uri = Uri.parse(cursor.getString(cursor
.getColumnIndex(Media.DATA)));
path = uri.toString();
} while (cursor.moveToNext());
cursor.close();
}
Log.d("myLogs", path);
if (btnID == 1) {
pathOne = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathOne);
ivOne.setImageBitmap(bmImg);
one = bmImg;
} else {
pathTwo = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathTwo);
ivTwo.setImageBitmap(bmImg);
two = bmImg;
}
}
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case IDD_TWO_BUTTONS:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Зображення з ")
.setCancelable(false)
.setPositiveButton("Галереї",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
DialogFlag = 0;
Intent photoPickerIntent = new Intent(
Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent,
GALLERY_REQUEST);
dialog.cancel();
}
})
.setNeutralButton("Камери",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
DialogFlag = 1;
Intent cameraIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,
CAMERA_RESULT);
dialog.cancel();
}
}
)
.setNegativeButton("Відміна",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
}
);
return builder.create();
default:
return null;
}
}
But when i try to make this in fragment i get some problem.
public class MyDialogFragment extends DialogFragment {
public static MyDialogFragment newInstance(int title) {
MyDialogFragment frag = new MyDialogFragment();
Bundle args = new Bundle();
args.putInt("title", title);
frag.setArguments(args);
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.plus_icon)
.setTitle(title).setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent i =getActivity().getIntent();
i.putExtra("key", true);
getTargetFragment().onActivityResult(getTargetRequestCode(), 101, i);
}
}
)
.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//AddExerciseFragment.doNegativeClick();
Intent i =getActivity().getIntent();
i.putExtra("key", false);
getTargetFragment().onActivityResult(getTargetRequestCode(), 101, i);
}
}
)
.create();
}
}
onActivityResult in AddExerciseFragment
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
String path = null;
switch (requestCode) {
case DIALOG_FRAGMENT:
boolean check = imageReturnedIntent.getBooleanExtra("key", true);
if (check) {
doPositiveClick();
if (resultCode == RESULT_OK && requestCode == GALLERY_REQUEST) {
Uri selectedImage = imageReturnedIntent.getData();
path = getRealPathFromURI(selectedImage);
Log.d("myLogs", path);
if (btnID == 1) {
pathOne = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathOne);
ivOne.setImageBitmap(bmImg);
one = bmImg;
} else {
pathTwo = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathTwo);
ivTwo.setImageBitmap(bmImg);
two = bmImg;
}
}
} else {
doNegativeClick();
Uri uri;
Cursor cursor = getActivity().getContentResolver().query(
Media.EXTERNAL_CONTENT_URI,
new String[] { Media.DATA, Media.DATE_ADDED,
MediaStore.Images.ImageColumns.ORIENTATION },
Media.DATE_ADDED, null, "date_added ASC");
if (cursor != null && cursor.moveToFirst()) {
do {
uri = Uri.parse(cursor.getString(cursor
.getColumnIndex(Media.DATA)));
path = uri.toString();
} while (cursor.moveToNext());
cursor.close();
}
Log.d("myLogs", path);
if (btnID == 1) {
pathOne = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathOne);
ivOne.setImageBitmap(bmImg);
one = bmImg;
} else {
pathTwo = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathTwo);
ivTwo.setImageBitmap(bmImg);
two = bmImg;
}
}
break;
}
}
public void doPositiveClick() {
DialogFlag = 0;
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
// dialog.cancel();
}
public void doNegativeClick() {
DialogFlag = 1;
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_RESULT);
}
void showDialog() {
DialogFragment newFragment = MyDialogFragment
.newInstance(R.string.name);
newFragment.show(getFragmentManager(), "dialog");
}
But i have next:
If i want to set image from galery-it start galery, but i can not choose picture there
From camera i can set picture only once and only for one imageView
when i am in galery and press button "back" - i get error.
Related
I am trying to build an app that captures an image ans saves the image to a custom folder with a custom name but i am unable to perform it.
Here is the code that I have written please go through the code and correct me where i am wrong.
public class MainActivity extends Activity {
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private Builder alertDialogBuilder;
final Context context = this;
String name_str;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
Button searchButton = (Button) this.findViewById(R.id.button2);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
});
}
public void onActivityResult1(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
imageView.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
final Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
//Creating Alert Dialog Box
AlertDialog.Builder askname = new AlertDialog.Builder(MainActivity.this);
final EditText inputname = new EditText(this);
askname.setMessage("Enter Name");
askname.setView(inputname);
askname.setPositiveButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
name_str = inputname.getEditableText().toString();
Toast.makeText(context,name_str,Toast.LENGTH_LONG).show();
dialog.dismiss();
/*if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
//photo = BitmapFactory.decodeByteArray(data,0,data.length);
imageView.setImageBitmap(photo);*/
String file ="/DCIM/VisitingCards/";
File folder = new File(Environment.getExternalStorageDirectory() + file);
System.out.println("File name is :"+folder);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
//ON success
System.out.println("Directory Present");
System.out.println("In Success Case");
try {
FileOutputStream out = new FileOutputStream(folder);
photo.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
//ON failure
System.out.println("Directory not Present");
System.out.println("In Failure Case");
}
System.out.println("Before the Dialog builder");
}
});
askname.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
dialog.dismiss();
}
}); //End of alert.setNegativeButt
askname.show();
}
}
}
you should ask image name before intent and then used putExtra.
hope it may help you
I am creating an android activity for browsing the images from gallery. But it's taking only images from other folders but not images from the Camera folder.
This code in your button on click
Yourbotton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder alertdialog1 =new AlertDialog.Builder(EditProfileActivity.this);
alertdialog1.setMessage("Please select a Profile image");
alertdialog1.setNegativeButton("CAMERA", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,CAMERA_REQUEST);
}
});
alertdialog1.setNeutralButton("GALLERY",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
alertdialog1.setPositiveButton("CLOSE",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
alertdialog1.show();
}
});
This functions in outside of onCreate()
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
edpprofilepic.setScaleType(ScaleType.FIT_XY);
edpprofilepic.setImageBitmap(photo);
imagepath = ImageWrite(photo);
}
else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn,
null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
edpprofilepic.setScaleType(ScaleType.FIT_XY);
edpprofilepic.setImageBitmap(BitmapFactory.decodeFile(picturePath));
imagepath = ImageWrite(BitmapFactory.decodeFile(picturePath));
}
}
public String ImageWrite(Bitmap bitmap1)
{
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, "slectimage.PNG");
try
{
outStream = new FileOutputStream(file);
bitmap1.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
String imageInSD = "/sdcard/slectimage.PNG";
return imageInSD;
}
I think this is helpful to you
this is my program, I think it is no problem about the alertdialogue.
But after I select the photo in my gallery, the picture isn't changed.
It is still the original photo that I set in the ImageView.
Could someboby help me know where the problem is?
public class MainActivity extends Activity{
ImageView img_logo;<br>
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_PICTURE = 1;
private Intent pictureActionIntent = null;
Bitmap bitmap;
Uri selectedImageUri;
String selectedPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img_logo= (ImageView) findViewById(R.id.homepic);
img_logo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startDialog();
}
});
}
private void startDialog() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");
myAlertDialog.setPositiveButton("Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pictureActionIntent = new Intent(
Intent.ACTION_GET_CONTENT, null);
pictureActionIntent.setType("image/*");
pictureActionIntent.putExtra("return-data", true);
startActivityForResult(pictureActionIntent,
GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pictureActionIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(pictureActionIntent,
CAMERA_REQUEST);
}
});
myAlertDialog.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(data.getData() != null){
selectedImageUri = data.getData();
}else{
Log.d("selectedPath1 : ","Came here its null !");
Toast.makeText(getApplicationContext(), "failed to get Image!", 500).show();
}
if (requestCode == 100 && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
selectedPath = getPath(selectedImageUri);
img_logo.setImageURI(selectedImageUri);
Log.d("selectedPath1 : " ,selectedPath);
}
if (requestCode == 10)
{
selectedPath = getPath(selectedImageUri);
img_logo.setImageURI(selectedImageUri);
Log.d("selectedPath1 : " ,selectedPath);
}
}
Toast toast = Toast.makeText(MainActivity.this, "hiiiii", Toast.LENGTH_LONG);
toast.show();
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
Try this way,hope this will help you to solve your problem.
public class MainActivity extends Activity {
ImageView img_logo;
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_PICTURE = 1;
private String imgPath;
private String selectedPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img_logo = (ImageView) findViewById(R.id.homepic);
img_logo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startDialog();
}
});
}
private void startDialog() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");
myAlertDialog.setPositiveButton("Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), GALLERY_PICTURE);
}
}
);
myAlertDialog.setNegativeButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAMERA_REQUEST);
}
}
);
myAlertDialog.show();
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".jpg");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
public String getAbsolutePath(Uri uri) {
if (Build.VERSION.SDK_INT >= 19) {
String id = uri.getLastPathSegment().split(":")[1];
final String[] imageColumns = {MediaStore.Images.Media.DATA};
final String imageOrderBy = null;
Uri tempUri = getUri();
Cursor imageCursor = managedQuery(tempUri, imageColumns,
MediaStore.Images.Media._ID + "=" + id, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
} else {
return null;
}
} else {
String[] projection = {MediaStore.MediaColumns.DATA};
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
private Uri getUri() {
String state = Environment.getExternalStorageState();
if (!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
return MediaStore.Images.Media.INTERNAL_CONTENT_URI;
return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
img_logo.setImageBitmap(BitmapFactory.decodeFile(getImagePath()));
selectedPath = getImagePath();
} else if (requestCode == GALLERY_PICTURE) {
img_logo.setImageBitmap(BitmapFactory.decodeFile(getAbsolutePath(data.getData())));
selectedPath = getAbsolutePath(data.getData());
}
Toast toast = Toast.makeText(MainActivity.this, "hiiiii", Toast.LENGTH_LONG);
toast.show();
}
}
}
Add this <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in AndroidManifest.xml
I can capture an image, either through camera or gallery. I also have two imageviews to set the captured images to it. But I always get the failed binder transaction when I try to start an intent with the passed two compressed bitmaps:
public class PostFragment extends Fragment implements OnClickListener {
View post_view;
Button button1, button0;
ActionBar actionBar;
private Uri mImageCaptureUri;
private ImageView mImageView, mImageView2;
private AlertDialog dialog;
private String imagepath = null;
Bitmap bitmap, bitmap1, bitmap2, bitmap_image1, bitmap_image2;
String krt, krt1, krt2;
private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_FILE = 3;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
post_view = inflater.inflate(R.layout.postoffer_fragment_layout,
container, false);
getActivity().getActionBar().setIcon(R.drawable.ic_offer);
button1 = (Button) post_view.findViewById(R.id.button1);
button1.setOnClickListener(this);
button0 = (Button) post_view.findViewById(R.id.button0);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
captureImageInitialization();
mImageView = (ImageView) post_view.findViewById(R.id.imageView1);
mImageView2 = (ImageView) post_view.findViewById(R.id.imageView2);
return post_view;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
// setText() sets the string value of the TextView
Intent intent = new Intent(getActivity(), OfferInformation.class);
if (krt1 != "" && krt2 != "") {
intent.putExtra("image", krt1);
intent.putExtra("image2", krt2);
startActivity(intent);
}
}
private void captureImageInitialization() {
final String[] items = new String[] { "Take from camera",
"Select from gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(
"android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, PICK_FROM_CAMERA);
} else {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);
}
}
});
dialog = builder.create();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
if (mImageView.getDrawable() == null) {
bitmap1 = BitmapFactory.decodeFile(imagepath);
/*tbd
*/
} else if (mImageView.getDrawable() != null
&& mImageView2.getDrawable() == null) {
mImageView.setTag("2");
/*tbd
*/
}
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
if (mImageView.getDrawable() == null) {
bitmap1 = BitmapFactory.decodeFile(imagepath);
mImageView.setImageBitmap(bitmap1);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, baos1);
byte[] imageBytes1 = baos1.toByteArray();
krt1 = Base64.encodeToString(imageBytes1, Base64.DEFAULT);
} else if (mImageView.getDrawable() != null
&& mImageView2.getDrawable() == null) {
bitmap2 = BitmapFactory.decodeFile(imagepath);
mImageView2.setImageBitmap(bitmap2);
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, baos2);
byte[] imageBytes2 = baos2.toByteArray();
krt2 = Base64.encodeToString(imageBytes2, Base64.DEFAULT);
}
break;
}
}
public String getPath(Uri uri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(uri, proj,
null, null, null);
if (cursor.moveToFirst()) {
;
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
}
Hi I have created an Activity from that I am calling startActivityForResult at the first time it is working below is the code
Dialog box for choosing image from Camera or Gallery
private void selectImage() {
System.out.println("Select Image");
final CharSequence[] items = { "Take Photo",
"Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
final Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
} else if (items[item]
.equals("Choose from Library")) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(
intent, ""), PICK_IMAGE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
It's onActivityForResultSetMethod
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println("onActivityResult");
System.out.println("requestCode : - " + requestCode);
System.out.println("resultCode : - " + resultCode);
System.out.println("data : - " + data);
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
imagePath = getAbsolutePath(data.getData());
bitmap = decodeFile(imagePath);
ivUpload.setScaleType(ImageView.ScaleType.FIT_XY);
ivUpload.setImageBitmap(bitmap);
} else if (requestCode == CAPTURE_IMAGE) {
imagePath = getImagePath();
bitmap = decodeFile(imagePath);
ivUpload.setScaleType(ImageView.ScaleType.FIT_XY);
ivUpload.setImageBitmap(bitmap);
} else {
super.onActivityResult(requestCode, resultCode,
data);
}
}
}
Issue if when i first time called, In image view i am not getting image, and also if i tried it again
Activity's onCreate method is also called don't know but why
Try this way,hope this will help you to solve your problem.
private int PICK_IMAGE=1;
private int CAPTURE_IMAGE=2;
private String imgPath;
private void selectImage() {
System.out.println("Select Image");
final CharSequence[] items = { "Take Photo",
"Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
} else if (items[item]
.equals("Choose from Library")) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_IMAGE) {
ivUpload.setImageBitmap(decodeFile(getAbsolutePath(data.getData())));
ivUpload.setScaleType(ImageView.ScaleType.FIT_XY);
} else if (requestCode == CAPTURE_IMAGE) {
ivUpload.setImageBitmap(decodeFile(getImagePath()));
ivUpload.setScaleType(ImageView.ScaleType.FIT_XY);
}
}
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
public String getAbsolutePath(Uri uri) {
if(Build.VERSION.SDK_INT >= 19){
String id = uri.getLastPathSegment().split(":")[1];
final String[] imageColumns = {MediaStore.Images.Media.DATA };
final String imageOrderBy = null;
Uri tempUri = getUri();
Cursor imageCursor = getContentResolver().query(tempUri, imageColumns,
MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
}else{
return null;
}
}else{
String[] projection = { MediaStore.MediaColumns.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
private Uri getUri() {
String state = Environment.getExternalStorageState();
if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
return MediaStore.Images.Media.INTERNAL_CONTENT_URI;
return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
Note : please not forget this permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Try This : I have done some modification.It is working on my end
public class MainActivity extends Activity {
ImageView viewImage;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.btnSelectPhoto);
viewImage = (ImageView) findViewById(R.id.viewImage);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
#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(), "temp1.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);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "AudioBlog" + 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 thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........",
picturePath + "");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
try this
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
private String imgPath;
private void selectImage() {
AlertDialog.Builder builder = new AlertDialog.Builder(
ProfileActivity.this);
// builder.setTitle("Choose Image Source");
builder.setItems(new CharSequence[] { "Take a Photo",
"Choose from Gallery" },
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent intent1 = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent1.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent1, CAPTURE_IMAGE);
break;
case 1:
// GET IMAGE FROM THE GALLERY
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, ""),
PICK_IMAGE);
break;
default:
break;
}
}
});
builder.show();
}
public Uri setImageUri() {
File file = new File(Environment.getExternalStorageDirectory(), "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
onActivityForResultSetMethod
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
selectedImagePath = getAbsolutePath(data.getData());
System.out.println("path" + selectedImagePath);
imageView.setImageBitmap(decodeFile(selectedImagePath));
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
System.out.println("path" + selectedImagePath);
imageView.setImageBitmap(decodeFile(selectedImagePath));
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of
// 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
As to called onCreate(), please Log.d("~~~",""+savedInstanceState);, it will likely be non-null meaning that Android advices you to restore the application state from the bundle.