Android studio, pick picture form files, pictures are grey out - java

I have managed to get some code working for picking a pictures from mobile stored files to the imageView, but I am not sure why all the images files are grey out, and I cannot select them.
I have searched for a solution, but I couldn't find anything, so any advice will be appreciated.
methods for selecting a picture:
public void chooseImage (View objectView){
try {
Intent objectIntent = new Intent();
objectIntent.setType("iv_addBday/*");
objectIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(objectIntent, PICK_IMAGE_REQUEST);
}
catch (Exception e){
}
}
protected void onActivityResult (int requestCode, int resultCode, #Nullable Intent data){
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
imageFilePath = data.getData();
imageToStore = MediaStore.Images.Media.getBitmap(getContentResolver(), imageFilePath);
imageView.setImageBitmap(imageToStore);
}
} catch (IOException e) {
e.printStackTrace();
}
}
example

What about :
public void chooseImage (View objectView){
try {
Intent objectIntent = new Intent();
objectIntent.setType("image/*");
objectIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(objectIntent, PICK_IMAGE_REQUEST);
}
catch (Exception e){
}
}

Related

Bitmap is null while capturing image from camera

My code is working perfectly fine in API level <= 19 but in greater version I am getting bitmap null.
public void SelectImage() {
final CharSequence[] items = {"Camera", "Gallery", "Cancel"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.add_image);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if (items[i].equals("Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(mainActivity.getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_CAMERA);
}
} else if (items[i].equals("Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, SELECT_FILE);
} else if (items[i].equals("Cancel")) {
dialog.dismiss();
}
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
place = PlacePicker.getPlace(data, mainActivity);
etAddress1.setText(place.getAddress());
}
} else if (resultCode == Activity.RESULT_OK && data != null) {
Glide.with(this).load(data.getData()).into(ivprofile);
Bitmap bm = null;
try {
bm = MediaStore.Images.Media.getBitmap(mainActivity.getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] b = baos.toByteArray();
base64img = Base64.encodeToString(b, Base64.NO_WRAP);
}
}
Here my bm is null why this happening am i using the older code version or is there anything else.. Thanks in advance.
Actually, there is a library which works with every phone and every android version. If you need to solve you problem here is an answer. EasyImage did the job!
do not forget to handle permissions api 23 and up !

How to open Gallery to pick an image?

I am looking for a way to open onClick the gallery to pick an Picture.
I want to use that local "uploaded" picture in a listview of pictures.
Can someone help and explain me how to do that. I am a beginner in Android Developing.
public void pickImage() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PICK_PHOTO_FOR_AVATAR);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PHOTO_FOR_AVATAR && resultCode == Activity.RESULT_OK) {
if (data == null) {
//Display an error
return;
}
InputStream inputStream = context.getContentResolver().openInputStream(data.getData());
//Now you can do whatever you want with your inpustream, save it as file, upload to a server, decode a bitmap...
}
}
Here is a code i used in my app
Intent pickImageIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickImageIntent, PICKIMAGE_REQUESTCODE);
And at the onActivity result method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICKIMAGE_REQUESTCODE) {
if (resultCode == RESULT_OK) {
Uri imageUri = data.getData();
InputStream inputStream = null;
try {
inputStream = getContentResolver().openInputStream(imageUri);
bitmap = BitmapFactory.decodeStream(inputStream);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "onActivityResult: error closing InputStream during reading image from the phone external storage");
}
}
}

Getting a file's location in android studio

Im trying to pick a file in a file explorer using intent.
here is my code:
Intent intent = new Intent();
intent.setAction(intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE );
it works fine and picks a file but I need to get the picked file's location. what should I do?
Once you select a file this method will be called automatically.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
}
}
Try this
It will give you the bitmap
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
and here data.getData() gives you the uri

Android app crop photo

I have a question.
This is the code that my application already have and it works like this : takes photo >crop > upload.
I don't want to crop the photo .How can I do this? Just deleting the dispatchCropImageIntent method?
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(this.getClass().getSimpleName(), "onActivityResult");
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
File imageFile = new File(mCurrentPhotoPath);
if (imageFile.exists()) {
dispatchCropImageIntent(Uri.fromFile(imageFile));
}
} else if (requestCode == REQUEST_IMAGE_FROM_GALLERY_SELECT) {
dispatchCropImageIntent(data.getData());
} else if (requestCode == REQUEST_PICTURE_CROP) {
String filePath = Environment.getExternalStorageDirectory()
+ "/temporary_holder.jpg";
setCurrentBitmap(BitmapFactory.decodeFile(filePath));
} else if(requestCode == CAMERA_ACTIVITY_CODE){
// Get path
String path = data.getStringExtra(CustomCamera.OUT_PATH);
// Read file
byte[] imgData = AppFS.readFileFromPath(path);
if (imgData != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(imgData , 0, imgData.length);
// TODO: Do something with the image, it should be okay
//((ImageView)findViewById(R.id.img)).setImageBitmap(bitmap);
} else {
Log.e("Main", "Data is null");
}
}
}
else{
onBackPressed();
}
}
And :
private void dispatchCropImageIntent(Uri uri) {
Intent cropImageIntent = new Intent("com.android.camera.action.CROP");
cropImageIntent.setDataAndType(uri, "image/*");
cropImageIntent.putExtra("crop", "true");
cropImageIntent.putExtra("noFaceDetection", true);
cropImageIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
// retrieve data on return
cropImageIntent.putExtra("return-data", true);
File f = new File(Environment.getExternalStorageDirectory(),
"/temporary_holder.jpg");
try {
f.createNewFile();
} catch (IOException ex) {
Log.e("io", ex.getMessage());
}
uri = Uri.fromFile(f);
cropImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(cropImageIntent, REQUEST_PICTURE_CROP);
}
If I understand you correctly,you want to make your app working like this: takes photo > upload. So, you need to replace dispatchCropImageIntent() with setCurrentBitmap() or upload methond.

onActivityResult not working on API 23

The onActivityResult method returns blank data or is not called when picking an image from Gallery. My implementation works fine on API 16, 17...22 but I am having problems with API 23. I read this article: https://guides.codepath.com/android/Accessing-the-Camera-and-Stored-Media , about permissions.
My client has tested the app on 3 phones running Android 6
and they all have the same behavior when picking a image. You can see an activity screenshot, there are 3 ImageButtons (a big one, and 2 small ones), when user clicks on an ImageButton the gallery is triggered for picking an image, when user picks an image the ImageButton just gets grey instead of showing the picked image.
////onclick method///photo2 is a imagebutton////SELECT_PICTURE2 is the code
photo2_evento.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, "Escoge
una imagen"), SELECT_PICTURE2);
startActivityForResult(intent, SELECT_PICTURE2);
}
});
///onactivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
try{
Uri selectedImageUri = data.getData();
if (requestCode == SELECT_PICTURE1) {
photo1_path = getRealPathFromURI(selectedImageUri);
photo1_evento.setImageBitmap(decodeSampledBitmapFromResource(photo1_path, 400, 400));
}else if(requestCode == SELECT_PICTURE2){
photo2_path = getRealPathFromURI(selectedImageUri);
photo2_evento.setImageBitmap(decodeSampledBitmapFromResource(photo2_path, 100, 100));
}else if(requestCode == SELECT_PICTURE3){
photo3_path = getRealPathFromURI(selectedImageUri);
photo3_evento.setImageBitmap(decodeSampledBitmapFromResource(photo3_path, 100, 100));
}
}catch(Exception e){
e.printStackTrace();
}catch (OutOfMemoryError e) {
e.printStackTrace();
Toast.makeText(getBaseContext(),"memory error", Toast.LENGTH_LONG).show();
}
}
}
////decodeSampledBitmapFromResource is just a method provided by Google Android for sizing images.
////this method is for getting the URI path, I got this code from stackoverflow
public String getRealPathFromURI(Uri contentUri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = null;
try {
if (Build.VERSION.SDK_INT > 19) {
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
cursor = Publicar_Eventos.this.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[] { id }, null);
} else {
cursor = Publicar_Eventos.this.getContentResolver().query(contentUri,
projection, null, null, null);
}
} catch (Exception e) {
e.printStackTrace();
}catch (OutOfMemoryError e) {
e.printStackTrace();
Toast.makeText(getBaseContext(),"error de memoria", Toast.LENGTH_LONG).show();
}
String path = null;
try {
int column_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
} catch (NullPointerException e) {
e.printStackTrace();
}
return path;
}

Categories