I was trying to select an image from a device folder but it an error in the logcat like this:
(https://i.stack.imgur.com/0yFm8.jpg)
(https://i.stack.imgur.com/owWL4.jpg)
This error doesn't always come out and sometimes it changes, but it's always about running out of memory
This is the code with which I choose an image in the gallery:
public void inserimentoImmagine() {
addImage = findViewById(R.id.aggiuntaFoto);
addImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (ActivityCompat.checkSelfPermission(AggiuntaAnimaleManuale.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AggiuntaAnimaleManuale.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PICK_FROM_GALLERY);
} else {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PICK_FROM_GALLERY:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
} else {
//do something like displaying a message that he didn`t allow the app to access gallery and you wont be able to let him select from gallery
}
break;
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
if (data == null) {
//Display an error
return;
}
Uri imgUri= data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor=getContentResolver().query(
imgUri, filePathColumn, null, null, null
);
String picturePath;
Bitmap bitmap;
if (cursor != null && cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
bitmap = BitmapFactory.decodeFile(picturePath);
image.setImageBitmap(bitmap);
}
}
}
}
I am recording/selecting a video in my RecordVideo.java activity. Once the video is recorded/selected the I press the upload button and go to the PostActivity.java file. But once I'm in there for some reason onActivityResult isn't being called. I tried to toast and Log.d for some type of error or info but nothing came up.
I checked the answer on here to the same problem I'm having but none of them worked for me.
Can someone please help ?
RecordVideo.java:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_CODE_VIDEO_CAPTURE && resultCode == RESULT_OK && data.getData() != null) {
videoUri = data.getData();
videoView.setVideoURI(videoUri);
videoView.start();
} else if (requestCode == 5 && resultCode == RESULT_OK && data != null && data.getData() != null) {
videoUri = data.getData();
videoView.setVideoURI(videoUri);
videoView.start();
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadUserVideo(Uri videoUri) {
if (videoUri != null) {
Intent intent = new Intent(RecordVideo.this, PostActivity.class);
intent.putExtra("videoUri", videoUri.toString());
startActivity(intent);
finish();
} else {
Toast.makeText(this, "It's null", Toast.LENGTH_SHORT).show();
}
}
PostActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
Bundle extras = getIntent().getExtras();
if (extras != null) {
//videoUri = extras.getInt(videoUri);
videoUri = Uri.parse(extras.getString("videoUri"));
//Toast.makeText(this, "It's not null", Toast.LENGTH_SHORT).show();
} else {
// handle case
Toast.makeText(this, "Post null", Toast.LENGTH_SHORT).show();
}
videoView = findViewById(R.id.video_added);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
close = findViewById(R.id.close);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(PostActivity.this, MainActivity.class));
finish();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Log.d("TAG3", "I'm here." + requestCode);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
videoUri = data.getData();
videoView.setVideoURI(videoUri);
videoView.start();
Toast.makeText(this, "No problem.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "A problem.", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
In the below code I'm picking an image from gallery:
Intent choosePicture = new Intent();
choosePicture.setType("image/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
choosePicture.setAction(Intent.ACTION_OPEN_DOCUMENT);
}
else {
choosePicture.setAction(Intent.ACTION_GET_CONTENT);
}
startActivityForResult(choosePicture, 1);
And in onActivityResults(..):
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Context context = getContext();
Activity activity = getActivity();
View view = getView();
if (context == null || activity == null || view == null) {return;}
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Bitmap mImageBitmap = null;
try {
imageUri = Uri.fromFile(new File(currentPhotoPath));
mImageBitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(),
imageUri);
} catch (IOException e) {
e.printStackTrace();
}
ImageButton imageButton = view.findViewById(R.id.imgBtn_photo);
if (mImageBitmap != null) {
imageButton.setImageBitmap(scaleBitmap(mImageBitmap));
}
}
break;
case 1:
if (resultCode == RESULT_OK && data != null) {
ImageButton ib = view.findViewById(R.id.imgBtn_photo);
imageUri = data.getData();
Bitmap bitmapImage;
try {
bitmapImage = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), imageUri);
if (bitmapImage.getHeight() > 1000) {
ib.setImageBitmap(scaleBitmap(bitmapImage));
} else {
ib.setImageBitmap(bitmapImage);
}
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
}
And this is working.
The problem is that if the user delete the photo from his gallery, the app will crash.
How can I store the image to android/data/packagename and get that path, to store it in the DB?
Thanks!
My android app has three buttons On click all the button do the same work,
And the code is so long I don't want to copy the code 3 time.
So, how can I do this using a method?
This the code of one button
public void onClick(View v) {
switch (v.getId()) {
case R.id.Btn1:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1); //Gallery acessing
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
super.setContentView(R.layout.activity_view);
selectedImage = (ImageView) findViewById(R.id.selectedImage); //Onresult redarct to anothr activity
}
Uri photoUri = data.getData();
if (photoUri != null) {
try {
currentImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
selectedImage.setImageBitmap(currentImage);
} catch (Exception e) {
e.printStackTrace();
Intent myIntent = new Intent(this, ViewActivity.class);
startActivity(myIntent); //switch activity
}
}}
}
You can try the below code. I have created a public method doSomething() which is called on each button click so it performs the same function whenever it is called.
public void onClick(View v) {
switch (v.getId()) {
case R.id.Btn1:
doSomething();
break;
case R.id.Btn2:
doSomething();
break;
}
}
public void doSomething(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1); //Gallery acessing
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
super.setContentView(R.layout.activity_view);
selectedImage = (ImageView) findViewById(R.id.selectedImage); //Onresult redarct to anothr activity
}
Uri photoUri = data.getData();
if (photoUri != null) {
try {
currentImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
selectedImage.setImageBitmap(currentImage);
} catch (Exception e) {
e.printStackTrace();
Intent myIntent = new Intent(this, ViewActivity.class);
startActivity(myIntent); //switch activity
}
}}
}
private View.OnClickListener myClickListener = new View.OnClickListener(){
public void onClick(View view){
//do all the work here
}
}
then set it in you Views
view1.setOnClickListener(myClickListener);
view2.setOnClickListener(myClickListener);
//... etc
You can Use performClick of first button in other views click.
Button button1 = findViewById(R.id.Btn1)
case R.id.Btn2:
button1.performClick()
I am taking image from camera as well as from gallery,after getting the image, I want to show the image in imageview.
Image that is captured by camera successfully is shown in imageview but when I want to select it from gallery it does not show the image and it also does not show any error. It was working properly but later I add camera feature in activity, it's not working well.
public class DoReport extends AppCompatActivity {
private EditText subject,detail;
private ImageView pic;
private ImageView iv;
private Spinner depart;
private String depat,sub,det;
//for image
private Bitmap selectedImage;
public static String image;
private Uri imageUri;
public final static int PHOTO_FROM_MEMORY_REQUESTED = 10;
static final int REQUEST_IMAGE_CAPTURE = 1;
String userChoosenTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_do_report);
subject = (EditText) findViewById(R.id.subject);
detail = (EditText) findViewById(R.id.detail);
depart = (Spinner) findViewById(R.id.Depat_Edit);
iv=(ImageView)findViewById(R.id.ImgView);
}
public void onBackClick(View v) {
Intent intent=new Intent(this,UserView.class);
startActivity(intent);
finish();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent=new Intent(this,UserView.class);
startActivity(intent);
finish();
}
//to pic the image from galery
//this is new <code>
public void imgBtn(View v) {
selectImage();
}
private void updateSelectedPicture(Uri uri) {
try {
imageUri = uri;
InputStream imageStream = getContentResolver().openInputStream(imageUri);
selectedImage = BitmapFactory.decodeStream(imageStream);
iv.setImageDrawable(new BitmapDrawable(selectedImage));
image=encode(selectedImage);
} catch(FileNotFoundException ex) {
Log.e("File not found", "Cannot find background file under received URI");
}
}
public static String encode(Bitmap image) {
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", imageEncoded);
return imageEncoded;
}
public void submit(View v) {
depat=depart.getSelectedItem().toString();
sub=subject.getText().toString();
det=detail.getText().toString();
if(sub.isEmpty()) {
subject.setError("subject is required");
} else if(det.isEmpty()) {
detail.setError("subject is required");
} else {
login_database(depat, sub, det, image);
}
}
private void login_database(final String depat, final String sub,final String det,final String pic) {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, Static.user_connect,//changes required
new Response.Listener<String>() {
public void onResponse(String response) {
if ((response.contains("successful"))) {
Toast.makeText(DoReport.this, "Successful Submitted",Toast.LENGTH_LONG).show();
Intent i = new Intent (DoReport.this,UserView.class);
startActivity(i);
finish();
} else {
Toast.makeText(DoReport.this, "Some error occured", Toast.LENGTH_LONG).show();//changes required
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DoReport.this, error.toString(), Toast.LENGTH_SHORT).show();
Log.d("ERROR", toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("key", "3");//changes required
map.put("Depat", depat);
map.put("Detail", det);
map.put("Pic", pic);
map.put("Subject", sub);
map.put("U_id",Static.id);
return map;
}
};
queue.add(request);
}
/*//////////////////////////////////////////////////////////////////////////////////////////
code for selecting image from camera or gallery
*////////////////////////////////////////////////////////////////////////////////////////
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode== REQUEST_IMAGE_CAPTURE) {
try {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(imageBitmap);
image = encode(imageBitmap);//this line is added to encode
} else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}
}
catch (Exception e){ Toast.makeText(DoReport.this, e.toString(), Toast.LENGTH_LONG).show();}
}
}
///////////////it will show the dialogue box
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(DoReport.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(DoReport.this);
if (items[item].equals("Take Photo")) {
userChoosenTask="Take Photo";
dispatchTakePictureIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask="Choose from Library";
gallery();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void gallery() {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PHOTO_FROM_MEMORY_REQUESTED);
}
}
only change onActivityResult method remove else if block form id condition like below code...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode== REQUEST_IMAGE_CAPTURE) {
try {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(imageBitmap);
image = encode(imageBitmap);//this line is added to encode
}
}
catch (Exception e){ Toast.makeText(DoReport.this, e.toString(), Toast.LENGTH_LONG).show();}
}
else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}
}
selectedImage = BitmapFactory.decodeStream(imageStream);
You should check if selectedImage -the bitmap- is null.
I bet selectedImage==null.
This happens if the bitmap would become too big for available memory.
You should scale it down while loading from stream.
Remember: from the camera you only obtain a thumbnail. Thats the difference.
Here's my code to set a rounding photo from gallery or camera into ImageButton and it works perfectly :
public class EditProfileActivity extends AppCompatActivity {
ImageButton btnValidate,btnCancel,imgProfile;
TextView tvEditPhoto;
RoundImage roundedImage;
private String userChoosenTask;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btnCancel = findViewById(R.id.toolbar_back_btn);
btnValidate = findViewById(R.id.toolbar_validate_btn);
imgProfile = findViewById(R.id.user_profile_photo_edit);
tvEditPhoto = findViewById(R.id.user_profile_name_edit);
//Rounding image
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.profile);
roundedImage = new RoundImage(bm);
imgProfile.setImageDrawable(roundedImage);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
btnValidate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
imgProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
tvEditPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PictureUtility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Take Photo"))
cameraIntent();
else if(userChoosenTask.equals("Choose from Library"))
galleryIntent();
} else {
//code for deny
Toast.makeText(EditProfileActivity.this, "Oups ! vous n'avez pas la permission.", Toast.LENGTH_LONG).show();
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(EditProfileActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result= PictureUtility.checkPermission(EditProfileActivity.this);
if (items[item].equals("Take Photo")) {
userChoosenTask="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//resize picture
Bitmap bmw = Bitmap.createScaledBitmap(thumbnail, 120, 120, false);
//rounding picture
roundedImage = new RoundImage(bmw);
imgProfile.setImageDrawable(roundedImage);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
Bitmap bmw = Bitmap.createScaledBitmap(bm, 120, 120, false);
roundedImage = new RoundImage(bmw);
imgProfile.setImageDrawable(roundedImage);
}
}
In your code, try to add createScaledBitmap to resize your photo like this:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
//add this line and use the new bitmap resized
Bitmap imageBitmapResized = Bitmap.createScaledBitmap(imageBitmap , 120, 120, false);
iv.setImageBitmap(imageBitmapResized );
image = encode(imageBitmapResized );//this line is added to encode
} else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}