当我尝试通过改造2上传图像时,我的cursor.getString()返回null

时间:2018-12-05 10:32:34

标签: java android retrofit

我正在尝试从计算机,Android仿真器或手机上上传经过改造的图像,但是这三种方式均无法正常工作。 我从计算机的文件中获取了FileNotFoundException,并在手机或Android仿真器上获得了无效的路径。

我遵循了本教程:https://github.com/hidrodixtion/Example-Retrofit-Image-Upload/blob/master/app/src/main/java/com/projectbox/uploadfile/MainActivity.java#L11

并尝试解决有关此主题FileNotFoundException while uploading image using Retrofit

的问题

但是它现在仍然不起作用。

这是我的电话:

    @Multipart
@POST("http://192.168.1.102:8181/test_postimage.php")
Call<ResponseBody> postImage(@Part MultipartBody.Part image);

还有我的活动:

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prestations);

        Button btn =findViewById(R.id.btn5);

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        // Change base URL to your upload server URL.
        service = new Retrofit.Builder().baseUrl("http://192.168.0.234:3000").client(client).build().create(UserAccountServices.class);


            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE);
                }
            });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {

            Uri selectedImage = data.getData();
            String[] filePath = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePath,null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePath[0]);
            String FilePathStr = c.getString(columnIndex);
            c.close();

            //MultipartBody.Part body = null;

            File file = new File(FilePathStr);
            RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
            MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), reqFile);

            retrofit2.Call<okhttp3.ResponseBody> req = service.postImage(body);
            req.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    Log.i("response image OK",response.body().toString());
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    t.printStackTrace();
                }
            });
        }
    }

如果有帮助,我还会添加一个调试屏幕:enter image description here

感谢您的帮助。enter image description here

编辑:我尝试使用您的链接,并且在下面获得此代码:

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {

        Uri selectedImage = data.getData();

        File file = new File(selectedImage.getPath());
        RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), reqFile);

        retrofit2.Call<okhttp3.ResponseBody> req = service.postImage(body);
        req.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.i("response image OK",response.body().toString());
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }
}

}

但是我仍然收到FileNotFoundException错误:

enter image description here

enter image description here

最后,当我在手机中选择图像时出现错误:

enter image description here

编辑2:我仍在寻找解决方案,当我选择图像时,那些奇怪的路径可能来自这里,但我不知道是什么。

            Uri selectedImage = data.getData();

        File file = new File("/document/image/stars.jpg");
        Log.i("image path ==> ",selectedImage.getPath());
        Log.i("image encoded path ==> ",selectedImage.getEncodedPath());
        RequestBody reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), reqFile);

这些路径:

enter image description here

编辑3:

现在我的权限被拒绝了:

enter image description here

2 个答案:

答案 0 :(得分:0)

在学习教程时,您可以在此处访问Future Studio的改造教程:https://futurestud.io/tutorials/retrofit-getting-started-and-android-client,这是学习改造的最佳场所,有关具体案例,请访问this视频

答案 1 :(得分:0)

经过一些调查,我找到了解决问题的方法,并将其发布在这里供新手进行改造,因为在互联网上我对所见所闻存在很多误解。

首先,我如下更改了监听器:

          btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, PICK_IMAGE);
            }
        });

我们需要保留光标(与vivek mishra相反),并且必须添加用户请求确认。 我把我所有的代码放在下面,它在android 8.0上真的很好用。

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

    if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null && data.getData() !=null) {

        if (ContextCompat.checkSelfPermission(this.getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission is not granted

            ActivityCompat.requestPermissions(PrestationsActivity.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_EXTERNAL_STORAGE);
        }

        Uri selectedImage = data.getData();
        String[] filePath = {MediaStore.Images.Media.DATA};
        Cursor c = getContentResolver().query(selectedImage, filePath,null, null, null);
        c.moveToFirst();
        int columnIndex = c.getColumnIndex(filePath[0]);
        String FilePathStr = c.getString(columnIndex);
        c.close();


        File file = new File(FilePathStr);
        RequestBody reqFile = RequestBody.create(MediaType.parse(getContentResolver().getType(selectedImage)), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), reqFile);

        retrofit2.Call<okhttp3.ResponseBody> req = service.postImage(body);
        //Call<ResponseBody> req = service.postImage(body);
        req.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.i("response image OK",response.body().toString());
                Log.i("response image Type",response.body().contentType().toString());
                Log.i("response image Message",response.message());
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
            }
        });

        }
}

希望对某些开发人员有所帮助。