imageView not display an image from external storage - java

so am trying to make an app and part of the app i have to upload a picture from the phone and display it in imageview and keep the picture on it , i searched and i found a way in a video. the problem is the imageview didnt display the picture . i try many things like change in the code or even change in the xml file like make the imageview wrap content and remove the scaleType but the same no thing change , i understand like 80% from the code but in the last method I get lost so if anyone can help me i will be grateful
java code
public class AddCategory extends AppCompatActivity {
private static final int PERMISSION_REQUEST = 0 ;
private static final int RESULT_LOAD_IMAGE = 0 ;
ImageView imageView ;
Button btn ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
imageView = findViewById(R.id.imageAddCategory) ;
btn = findViewById(R.id.add_po);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= 23 && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},PERMISSION_REQUEST);
}
if (Build.VERSION.SDK_INT >= 23 && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED){
Intent ii = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(ii,RESULT_LOAD_IMAGE);
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case PERMISSION_REQUEST:
if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
Toast.makeText(this," PERMISSION GRANTED" ,Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this," PERMISSION NOT GRANTED" ,Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (resultCode == RESULT_OK) {
assert data != null;
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATE_ADDED};
assert selectedImage != null;
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn
, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
}
}
}
}

Related

Android Studio : READ_EXTERNAL_STORAGE permission causes an error

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);
}
}
}
}

Cannot Load image in imageView from gallery

I want to load an image in an image view from the gallery on the phone and I have
written the code
java:
public class MainActivity extends AppCompatActivity {
private static int RESULT_LOAD_IMAGE = 1;
Button btnTry , btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = findViewById(R.id.btnAdd);
btnTry = findViewById(R.id.btnTry);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//The integer argument is a "request code" that identifies your request. When you receive the result Intent,
// the callback provides the same request code so that your app can properly identify the result and determine how to handle it.
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i ,RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && requestCode == RESULT_OK && null != data){
Uri selectImage = data.getData();
String[] filePathcolumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectImage , filePathcolumn , null , null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathcolumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView ivMemeImage = findViewById(R.id.ivMemeImage);
ivMemeImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
when I run the app and hit the add button image does not load in the image view.
and I have given both the read and write permission in the manifest.
You can display your image using your Uri. you only need to do is set your imageView.setImageUri(selectedImage)
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
your_imageView.setImageURI(selectedImage);
}
is this code you have done in android studio?
if(requestCode == RESULT_LOAD_IMAGE && requestCode == RESULT_OK && null != data)
it should be
if(requestCode == RESULT_LOAD_IMAGE && requestCode == RESULT_OK && data!=null)
Your code should give you compile time error
check out Picasso library .. http://square.github.io/picasso/
load image from a URI into imageview with one line of code:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

App crashing when trying to fetch image from gallery. Please see details

I have set up code which allows me to fetch image from gallery and show it in an ImageView.
My code worked on Android version 5.0.2, but is crashing on android versions below that.
Here's the error I'm getting: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference at com.humanehelper.humanehelper.PostARequest.getResizedBitmap(PostARequest.java:353)
Here's PostARequest.java file's code:
public class PostARequest extends Fragment {
Bitmap bitmap;
ImageView hPic;
ProgressBar progressBar;
private OnFragmentInteractionListener mListener;
public PostARequest() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_post_a_request, container, false);
progressBar = (ProgressBar) rootView.findViewById(R.id.pbHeaderProgress);
hPic = (ImageView) rootView.findViewById(R.id.h_pic);
hPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getContext());
builder.setItems(R.array.choose_profile_pic_choices, mDialogListener);
android.app.AlertDialog dialog = builder.create();
dialog.show();
}
});
return rootView;
}
protected DialogInterface.OnClickListener mDialogListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int position) {
switch (position) {
case 0: // Take picture
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
break;
case 1: // Choose picture
Intent choosePhotoIntent = new Intent(Intent.ACTION_GET_CONTENT);
choosePhotoIntent.setType("image/*");
startActivityForResult(choosePhotoIntent, PICK_PHOTO_REQUEST);
break;
}
}
};
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_PHOTO_REQUEST || requestCode == TAKE_PHOTO_REQUEST) {
if (data == null) {
// display an error
return;
}
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
bitmap = BitmapFactory.decodeFile(picturePath);
Bitmap convertedImage = getResizedBitmap(bitmap, 200);
hPic.setImageBitmap(convertedImage);
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(getContext(), "Something went wrong!", Toast.LENGTH_LONG).show();
}
}
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float)width / (float) height;
if (bitmapRatio > 0) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
I don't know what is wrong here.
Please let me know.
Please cooperate on bad format of the question, I'm still in learning phase.
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
So here is the trick ..
Remove this line from your onactivity result code And run it .
super.onActivityResult(requestCode, resultCode, data);
This above line.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_PHOTO_REQUEST || requestCode == TAKE_PHOTO_REQUEST) {
if (data == null) {
// display an error
return;
}
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
bitmap = BitmapFactory.decodeFile(picturePath);
Bitmap convertedImage = getResizedBitmap(bitmap, 200);
h.setImageBitmap(convertedImage);
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(getContext(), "Something went wrong!", Toast.LENGTH_LONG).show();
}
}

ImageView not showing image selected from gallery

So I have a button that loads the gallery, and selects an image using this code...
public void getGalleryImage(View v){
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivityForResult(intent, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
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();
galleryImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
But when it goes back to the original activity, the ImageView still doesn't show anything. It doesn't give me any errors, or anything like that. Here the XML for the ImageView...
<ImageView
android:id="#+id/galleryImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
How can I get it to show?
I ended up figuring something out. I just did...
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
galleryImage.setImageURI(selectedImage);
}
This worked for what I was trying to accomplish.
Try this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
galleryImage.setImageBitmap(MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri));
}
}
public class MainActivity extends AppCompatActivity{
ImageView image;
Button pick;
int TAG_IMAGE = 100;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.imageView);
pick = (Button) findViewById(R.id.button);
pick.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent,"Select Image "),TAG_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == TAG_IMAGE && resultCode == RESULT_OK )
{
Uri selectedImage = data.getData();
try
{
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,filePath,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
String images = cursor.getString(columnIndex);
image.setImageURI(selectedImage);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}

How to capture image and how to get image from gallery in android

I am integrating a code for how to capture image and how to get image from gallery.Here is my source code. its working fine for individual but it didn't show the imageview when upload image from gallery. please help me
private static int RESULT_LOAD_IMAGE = 1;
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView,imageView1;
private static final int SELECT_PICTURE = 1;
String selectedPath;
private String selectedImagePath;
Uri selectedImageUri;
//ADDED
private String filemanagerstring;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
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);
}
});
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
//Log.d(TAG, "onShutter'd");
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
protected void onActivityResult1(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
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();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
Declare Global Variables just after your class declaration at the top:
private static int RESULT_LOAD_IMAGE = 1;
private static final int PICK_FROM_GALLERY = 2;
Bitmap thumbnail = null;
Call the intent like this: (Yourfunction)
public void YourFunction(){
Intent in = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(in, RESULT_LOAD_IMAGE);
}
Handle the result like this: Declare this outside of your onCreate anywhere in the class.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
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();
thumbnail = (BitmapFactory.decodeFile(picturePath));
Thumbnail is your image, go play with it!

Categories

Resources