简体   繁体   中英

How to get image from gallery and set in ImageView (extends Fragment)?

I tried to get image from gallery and show that image in ImageView but getting this error :

    E/ActivityManager: Sending non-protected broadcast com.motorola.motocare.INTENT_TRIGGER from system 4425:com.motorola.process.system/1000 pkg com.motorola.motgeofencesvc
                                                  java.lang.Throwable
                                                      at com.android.server.am.ActivityManagerService.broadcastIntentLocked(ActivityManagerService.java:18179)
                                                      at com.android.server.am.ActivityManagerService.broadcastIntent(ActivityManagerService.java:18779)
                                                      at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:512)
                                                      at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2905)
                                                      at android.os.Binder.execTransact(Binder.java:565)
04-27 17:21:28.696 559-559/? W/SurfaceFlinger: couldn't log to binary event log: overflow.

Here the complete code is as follow:

main.java

    package omcommunication.image;

public class AddWOD extends Fragment implements View.OnClickListener {
Activity activity;

public AddWOD() {
}

; private static int IMG_RESULT = 1;
String ImageDecode;
ImageView imageViewLoad;
Button LoadImage;
Intent intent;
String[] FILE;
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.activity_add_wod, container, false);
     img=(ImageView) view.findViewById(R.id.imgview);
    buy_image1 = (ImageView) view.findViewById(R.id.rent_iv_addpro_image1);
    buy_image1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            intent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(intent, IMG_RESULT);



        }
    });
     return view;
}

   @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {

        if (requestCode == IMG_RESULT && resultCode == RESULT_OK
                && null != data) {


            Uri URI = data.getData();
            String[] FILE = { MediaStore.Images.Media.DATA };


            Cursor cursor = getActivity().getContentResolver().query(URI,
                    FILE, null, null, null);

            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(FILE[0]);
            ImageDecode = cursor.getString(columnIndex);
            cursor.close();

            img.setImageBitmap(BitmapFactory
                    .decodeFile(ImageDecode));

        }
    } catch (Exception e) {
        Toast.makeText(getActivity(), "Please try again", Toast.LENGTH_LONG)
                .show();
    }

}

I refer many questions but no getting the required things and yes i gave the external storage permission in manifest.

If you are running device greater than Lollipop , then you must be missing Android Runtime Permissions .

You can refer here for answer.

Preferably, you hand the Uri over to an image-loading library , such as Picasso, which can not only handle all of the image-loading for you, but can do so on a background thread.

If you insist upon doing this stuff yourself, start with:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {

        if (requestCode == IMG_RESULT && resultCode == RESULT_OK
                && null != data) {
            imageViewLoad.setImageBitmap(BitmapFactory
                    .decodeStream(getContentResolver().openInputStream(data.getData()));

        }
    } catch (Exception e) {
        Toast.makeText(this, "Please try again", Toast.LENGTH_LONG)
                .show();
    }

}

Then, after you get that working, switch to using an AsyncTask or something to do the decodeStream() part on a background thread and do the setImageBitmap() part on the main application thread.

In particular, this should not require you to mess with runtime permissions. Using the Uri properly takes advantage of the temporary permission grant that you are given as a result of the user choosing the picture.

Code for allowing the runtime permissions

if (Build.VERSION.SDK_INT >= 23)

{ checkMultiplePermissions();

} private void checkMultiplePermissions() {

    if (Build.VERSION.SDK_INT >= 23) {
        List<String> permissionsNeeded = new ArrayList<String>();
        List<String> permissionsList = new ArrayList<String>();

        if (!addPermission(permissionsList, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            permissionsNeeded.add("Access Location");
        }

        if (permissionsList.size() > 0) {
            requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                    REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
            return;
        }
    }
}

private boolean addPermission(List<String> permissionsList, String permission) {
    if (Build.VERSION.SDK_INT >= 23)

        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);

            // Check for Rationale Option
            if (!shouldShowRequestPermissionRationale(permission))
                return false;
        }
    return true;
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {

            Map<String, Integer> perms = new HashMap<String, Integer>();
            perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);


            for (int i = 0; i < permissions.length; i++)
                perms.put(permissions[i], grantResults[i]);
            if (perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                // All Permissions Granted
                return;
            } else {
                // Permission Denied
                if (Build.VERSION.SDK_INT >= 23) {


                }
            }
        }
        break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

its work for me:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)
        {
            Uri selectedImg = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getActivity().getContentResolver().query(selectedImg,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            buy_image1 .setImageBitmap(BitmapFactory.decodeFile(picturePath));
            cursor.close();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM