I want to get an image from gallery and set it on an ImageView in fragments. I also want to upload the image to my API backend as a file in fragments, so it needs to be in a format that allows me to upload the file. This is how it looks like in Postman. enter image description here
The addCover_btn allows me to open the gallery and select an image, but it crashes as soon as I select the image.
FragmentWriting.java
public class FragmentWriting extends Fragment implements Serializable, AdapterView.OnItemSelectedListener {
ImageView imageView;
Uri imageUri;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_writing, container, false);
addCover_btn = rootView.findViewById(R.id.addCoverButton);
// imageView = rootView.findViewById(R.id.short_image).setOnClickListener();
addCover_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
openGallery();
}
});
return rootView;
}
// Getting image from gallery try 2.0
private void openGallery() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(photoPickerIntent, 100);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == 100){
imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}