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

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

Related

Capturing the Image from camera intent image is rotating in some devices Android

I was trying to upload a profile of the user. In the app, users can choose from a gallery or camera.
While I was capturing the image from the camera, the image is rotating. I tried with exifinterface but the orientation getting as 0, and it works fine on some devices. How to solve this issue can anyone help me out?
xml
<com.facebook.drawee.view.SimpleDraweeView
android:id="#+id/profile_image"
app:placeholderImage="#drawable/defaultprofile1"
app:placeholderImageScaleType="fitCenter"
app:roundingBorderColor="#color/browser_actions_bg_grey"
fresco:roundAsCircle="true"
android:layout_width="110dp"
android:layout_height="110dp"
android:scaleType="fitCenter" />
Code
draweeView3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View view){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
ActivityCompat.requestPermissions(Objects.requireNonNull(getActivity()), new
String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
selectImage();
}
}
});
private void selectImage() {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Upload Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
}
}
});
builder.show();
}
#SuppressLint("LongLogTag")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 0) {
if (data != null) {
Bitmap selectedImage = (Bitmap) data.getExtras().get("data");
System.out.println("imagebitmap" + selectedImage);
Uri tempUri = getImageUri(Objects.requireNonNull(getContext()), selectedImage);
System.out.println("tempUri" + tempUri);
String picturePath = getRealPathFromURI(tempUri);
System.out.println("paaaaaaaa" + picturePath);
File f = new File(picturePath);
String imageName = f.getName();
System.out.println("file f" + f);
Uri imageUri = Uri.fromFile(new File(picturePath));// For files on device
draweeView3.setImageURI(imageUri);
}
}
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
Bitmap OutImage = Bitmap.createScaledBitmap(inImage, 1000, 1000, true);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), OutImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
String path = "";
if (getActivity().getContentResolver() != null) {
Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cursor.getString(idx);
System.out.println("final path" + path);
cursor.close();
}
}
return path;
}

imageView not display an image from external storage

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

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

Replace the original image on a new image in android application

In this MainActivity java class on Android Application Project I can't replace the original image given by the system with the one different selected from the photo gallery of smartphone.
When I select the one different photo I have always the original image.
public class MainActivity extends Activity implements OnClickListener {
Button uploadButton, btnselectpic;
ImageView imageview;
private ProgressDialog dialog = null;
private String imagepath = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadButton = (Button) findViewById(R.id.uploadButton);
btnselectpic = (Button) findViewById(R.id.btnselectpic);
imageview = (ImageView) findViewById(R.id.imageview);
btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
#Override
public void onClick(View arg0) {
if (arg0 == btnselectpic) {
selectImage();
} else if (arg0 == uploadButton) {
dialog = ProgressDialog.show(MainActivity.this, "",
"Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
}
}).start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && requestCode == 2 && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" + imagepath);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
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(), "temp.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();
}
The problem is that your onActivityResult() will never do anything.
You start this method off with:
if (requestCode == 1 && requestCode == 2 && resultCode == RESULT_OK) {
// ...
}
requestCode cannot be both 1 and 2, so this conditional will always be false.
You are likely looking for something more like this:
if ((requestCode == 1 && resultCode == RESULT_OK) ||
(requestCode == 2 && resultCode == RESULT_OK)) {
// ...
}

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