ImageView not showing image selected from gallery - java

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

Related

Android 10, select a photo from the gallery

people. I'm trying to get a photo from the Android 10 gallery. But, it tells me that bitmap = null, code below, what's wrong?
public void createIntent() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
uri = data.getData();
if(Build.VERSION.SDK_INT < 29 ) {
this.bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
} else {
this.bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(this.getContentResolver(), uri));
}
This is working on Android 10 also for me.
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String imagePath = getPath(data.getData());
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(new FileInputStream(imagePath),
null, options);
} catch (FileNotFoundException e) {
logger.log(Level.SEVERE, "Error loading the bitmap from the path: "
+ imagePath, e);
}
}
private String getPath(Uri uri) {
String path = "";
Cursor cursor = null;
try {
String[] projection = { MediaColumns.DATA };
cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor == null || !cursor.moveToFirst()) {
path = "";
} else {
int columnIndex = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
path = cursor.getString(columnIndex);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return path;
}
I have created the solution.
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uri = data.getData();
InputStream stream = this.getContentResolver().openInputStream(uri);
bitmap = BitmapFactory.decodeStream(stream);
}
This code works for Build.VERSION.SDK_INT < 29 and for Build.VERSION.SDK_INT >= 29

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

How to use onAcitivtyResult into some fragments int Android

In my application i have one activity (MainActivity) and some fragments (ServicesFragment , NewAddressFragment).
ServicesFragment used in viewPager and NewAddressFragment used getFragmentManager().replace ... for show this fragments!
in this fragments i used onActivityResult, but get conflict in one of fragments not call codes of onActivityResult codes in one of fragments.
I write below codes, please see this.
MainActivity :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment servicesFrag = bottomNavAdapter.getItem(mainViewPager.getCurrentItem());
if (servicesFrag instanceof ServicesFragment) {
((ServicesFragment) servicesFrag).onActivityResult(requestCode, resultCode, data);
}
}
ServiceFragment :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("BazaarPaymentLog", "Result");
Log.e("BazaarPaymentLog", "bazaarRequestCode : " + bazaarRequestCode);
if (iabHelper == null) return;
if (requestCode == bazaarRequestCode) {
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
if (resultCode == RESULT_OK) {
try {
JSONObject jo = new JSONObject(purchaseData);
purchaseToken = jo.getString("purchaseToken");
productId = jo.getString("productId");
packageName = jo.getString("packageName");
Log.e("BazaarPaymentLog", "purchaseToken : " + purchaseToken);
if (iabHelper != null) {
iabHelper.handleActivityResult(requestCode, resultCode, data);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
NewAddressFragment :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_PHOTO || requestCode == REQUEST_PICK_PHOTO) {
if (data != null) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath = cursor.getString(columnIndex);
cursor.close();
postPath = mediaPath;
uploadImageToServer(postPath);
}
} else if (requestCode == CAMERA_PIC_REQUEST) {
if (Build.VERSION.SDK_INT > 21) {
postPath = mImageFileLocation;
} else {
postPath = fileUri.getPath();
}
uploadImageToServer(postPath);
}
} else if (resultCode != RESULT_CANCELED) {
Toast.makeText(getActivity(), "Failed", Toast.LENGTH_LONG).show();
}
}
When write onActivityResult code in MainActivity, in ServicesFragment call onActivityResult codes and in NewAddressFragment not call onActivityResult codes.
But When remove onActivityResult code in MainActivity, in ServicesFragment not call onActivityResult codes and in NewAddressFragment call onActivityResult codes.
How can i fix it?
Inside onActivityResult of MainActivity use this :
Instead of this :-
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment servicesFrag = bottomNavAdapter.getItem(mainViewPager.getCurrentItem());
if (servicesFrag instanceof ServicesFragment) {
((ServicesFragment) servicesFrag).onActivityResult(requestCode, resultCode, data);
}
}
Use this :-
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
for(Fragment fragment : getSupportFragmentManager().getFragments()){
fragment.onActivityResult(requestCode,resultCode,data);
}
}
let me know if it is working or not
please add this line to onActivityResult in activity
Fragment servicesFrag = bottomNavAdapter.getItem(mainViewPager.getCurrentItem());
Fragment addressFrag = findFragmentByTag("NewAddressFragmentTag");
if (servicesFrag instanceof ServicesFragment) {
((ServicesFragment) servicesFrag).onActivityResult(requestCode, resultCode, data);
}
if (addressFrag instanceof NewAddressFragment) {
((NewAddressFragment) addressFrag).onActivityResult(requestCode, resultCode, data);
}
}
I can resolved my problem!
Change MainActivity codes with below codes :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment servicesFrag = bottomNavAdapter.getItem(mainViewPager.getCurrentItem());
Fragment addressFrag = getSupportFragmentManager().findFragmentByTag("NewAddressFragmentTag");
if (servicesFrag instanceof ServicesFragment) {
((ServicesFragment) servicesFrag).onActivityResult(requestCode, resultCode, data);
}
if (addressFrag instanceof NewAddressFragment) {
super.onActivityResult(requestCode, resultCode, data);
}
}
I hope help this for another dear developers

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

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