java – Gallery photo not loading (FileNotFoundExeption)

Question:

I can't upload a photo from the gallery and send it in a post request. I am attaching the code:

public void onClickImageViewAvatar(View view) {
    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, RESULT_LOAD_IMAGE);
}

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

    if (resultCode == RESULT_OK) {
        try {
            final Uri imageUri = data.getData();
            final InputStream imageStream = getContentResolver().openInputStream(imageUri);
            final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
            File file = new File(imageUri.toString());

            String URL = "http://*****";
            RequestParams requestParams = new RequestParams();
            requestParams.put("photo", file);// ошибка здесь
            requestParams.put("token",user.getToken());
            requestParams.put("user_id", user.getUser_id());

            client.post(URL, requestParams, new JsonHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    Log.i("fg", "change avatar " + response.toString());
                    try {
                        String status = response.getString("status");
                        if (Objects.equals(status, STATUS_FAIL)) {


                        } else if (Objects.equals(status, STATUS_SUCCESS)) {
                            imageViewAvatar.setImageBitmap(selectedImage);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            });


        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(ProfileSettings.this, "Something went wrong", Toast.LENGTH_LONG).show();
        }

    } else {
        Toast.makeText(ProfileSettings.this, "You haven't picked Image", Toast.LENGTH_LONG).show();
    }
}

Conclusion:

java.io.FileNotFoundException
    at com.loopj.android.http.RequestParams.put(RequestParams.java:285)
    at com.loopj.android.http.RequestParams.put(RequestParams.java:247)
    at com.example.uncolor.aroundme.ProfileSettings.onActivityResult(ProfileSettings.java:302)
    at android.app.Activity.dispatchActivityResult(Activity.java:6295)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:3929)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3976)
    at android.app.ActivityThread.access$1300(ActivityThread.java:176)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1578)
    at android.os.Handler.dispatchMessage(Handler.java:111)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5747)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1104)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:870)

Thank you in advance for your help!

Answer:

The returned Uri is not always a File . You need to get the absolute path to the selected image using the ContentResolver :

 final Uri imageUri = data.getData();
 Cursor c = getContentResolver().query(imageUri,null,null,null,null);
 if (c.moveToNext()) {
    String path = c.getString(c.getColumnIndex(MediaStore.MediaColumns.DATA));
    File file = new File(path);
    RequestParams requestParams = new RequestParams();
    requestParams.put("photo", file);// ошибки уже нет
 }

 c.close(); // не забудьте курсор закрыть
Scroll to Top