如何使用Retrofit2和alertDialog将文件发送到服务器

时间:2019-05-29 07:13:58

标签: java android nullpointerexception retrofit2

嗨,我想使用Retrofit2和alertDialog将文件发送到服务器,但出现了一些错误。

我的retrofit2请求

@Multipart
    @POST("ads")
    Call<ResponseBody> getUpload(@Header("Authorization") String token
            , @Part("title") RequestBody title
            , @Part("description") RequestBody description
            , @Part("price") RequestBody price
            , @Part("tell") RequestBody tell
            , @Part("address") RequestBody address
            , @Part("category") RequestBody category
            , @Part MultipartBody.Part image);

我为添加项目创建了一个floatAction按钮

FloatingActionButton floatingActionButton = findViewById(R.id.fab);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showList();
            }
        });

当我选择通过更改Button的名称通知我时,我为我创建了onActivityResult

 @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_FROM_GALLERY_REQUEST && resultCode == RESULT_OK
                && data != null && data.getData() != null) {
            saveUri = data.getData();
            btn_select.setText("Image Selected !");
        }
    }

我创建了用于显示布局的显示列表,添加了新帖子,并使用alertDialog填充了信息

 private void showList() {
        Log.d(TAG, "showList: started");
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(Home.this);
        alertDialog.setTitle("Add new post");
        alertDialog.setMessage("please fill all information");

        LayoutInflater layoutInflater = this.getLayoutInflater();
        View view = layoutInflater.inflate(R.layout.add_new_post, null);

        tv_title = view.findViewById(R.id.tv_title);
        tv_category = view.findViewById(R.id.tv_category);
        tv_tell = view.findViewById(R.id.tv_tell);
        tv_price = view.findViewById(R.id.tv_price);
        tv_description = view.findViewById(R.id.tv_description);
        tv_address = view.findViewById(R.id.tv_address);

        btn_select = view.findViewById(R.id.btn_select);
        btn_upload = view.findViewById(R.id.btn_upload);

        btn_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseImage();
            }
        });

        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadImage(saveUri);
            }
        });


        alertDialog.setView(view);

        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        alertDialog.show();

    }

我创建chooseImage来选择要在我的画廊中读取的图像。

private void chooseImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_FROM_GALLERY_REQUEST);
    }

最后,我创建了uploadImage以便将文件发送到服务器

private void uploadImage(Uri uri) {
        Log.d(TAG, "uploadImage: started");

        tv_title = findViewById(R.id.tv_title);
        tv_address = findViewById(R.id.tv_address);
        tv_description = findViewById(R.id.tv_description);
        tv_price = findViewById(R.id.tv_price);
        tv_tell = findViewById(R.id.tv_tell);
        tv_category = findViewById(R.id.tv_category);

        File originalFile = new File(uri.toString());

        RequestBody titlePart = RequestBody.create(MultipartBody.FORM, tv_title.getText().toString());
        RequestBody addressPart = RequestBody.create(MultipartBody.FORM, tv_address.getText().toString());
        RequestBody descriptionPart = RequestBody.create(MultipartBody.FORM, tv_description.getText().toString());
        RequestBody pricePart = RequestBody.create(MultipartBody.FORM, tv_price.getText().toString());
        RequestBody tellPart = RequestBody.create(MultipartBody.FORM, tv_tell.getText().toString());
        RequestBody categoryPart = RequestBody.create(MultipartBody.FORM, tv_category.getText().toString());

        RequestBody imagePart  = RequestBody.create(MediaType.parse(getContentResolver().getType(uri)),
                FileUtils.getFile(originalFile));

        MultipartBody.Part file = MultipartBody.Part.createFormData("image", originalFile.getName(), imagePart);

        SharedPreferences preferences = getSharedPreferences("Get_Token", MODE_PRIVATE);
        final String token = preferences.getString("Token", null);

        Call<ResponseBody> call = RetrofitClient.getmInstance().getApi().getUpload(token, titlePart, descriptionPart, pricePart, tellPart, addressPart, categoryPart, file);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

            }

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

            }
        });
    }

告诉我这个错误

2019-05-29 12:12:46.647 19215-19215/com.example.book E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.book, PID: 19215
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
        at com.example.book.Activities.Home.uploadImage(Home.java:160)
        at com.example.book.Activities.Home.access$200(Home.java:53)
        at com.example.book.Activities.Home$3.onClick(Home.java:123)
        at android.view.View.performClick(View.java:6261)
        at android.widget.TextView.performClick(TextView.java:11163)
        at android.view.View$PerformClick.run(View.java:23748)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6776)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)

现在告诉我我哪里弄错了。谢谢

1 个答案:

答案 0 :(得分:1)

  

抛出该错误以表明代码已尝试将对象强制转换为   不是实例的子类。例如,以下   代码生成ClassCastException:

错误:-

  

java.lang.ClassCastException:   android.support.v7.widget.AppCompatTextView无法转换为   android.widget.EditText

此错误告诉您您正在尝试将AppCompatTextView转换为EditText。

浏览XML并检查您要强制转换的XML。

解决方案:-更改XML(将TextView转换为EditaText)或活动(将EditText转换为TextView)。

错误:-

  

java.lang.NullPointerException:尝试调用虚拟方法   'null上的'android.text.Editable android.widget.EditText.getText()'   对象引用

NullPointerException告诉您正在访问的EditText对象为null。因为您没有提供EditText对象任何内存。意味着您正在访问它而没有绑定。

解决方案:-使用findViewById将您的EditText对象绑定到您在XML中提到的ID。