【问题标题】:how to send file to server with retrofit2 and alertDialog [duplicate]如何使用retrofit2和alertDialog将文件发送到服务器[重复]
【发布时间】:2019-05-29 07:13:58
【问题描述】:

您好,我想使用 retrofit2 和 alertDialog 将文件发送到服务器,但我遇到了一些错误。

我的改造请求

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

我为添加项目创建了一个浮动操作按钮

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

当我选择通过更改按钮名称来通知我时,我会为我创建 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();

    }

我为选择图像创建选择图像以在我的画廊中读取图像。

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)

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

【问题讨论】:

  • 你能显示你的错误日志吗?
  • @MiteshMachhoya 对不起。我编辑文件并写入错误
  • 清楚地检查你的xml页面
  • 你的声明ID检查主类
  • @sureshmadaparthi 在修复edittext之后更改了我的错误

标签: java android nullpointerexception retrofit2


【解决方案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:尝试调用虚拟方法 'android.text.Editable android.widget.EditText.getText()' 为空 对象引用

NullPointerException 告诉您您正在访问的 EditText 对象为空。因为您没有为 EditText 对象提供任何内存。表示您在没有绑定的情况下访问它。

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

【讨论】:

  • 在修复edittext之后更改我的错误
  • 检查答案并了解每个异常错误。从长远来看,它将对您有所帮助。
猜你喜欢
  • 2016-12-28
  • 1970-01-01
  • 2011-09-02
  • 2014-02-15
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 2023-03-03
相关资源
最近更新 更多