Android:尝试在空对象引用上调用虚拟方法“”

Android : Attempt to invoke virtual method '' on a null object reference

提问人:LAZREQ 提问时间:7/30/2022 最后编辑:LAZREQ 更新时间:7/30/2022 访问量:1856

问:

嘿,怎么了,伙计们,我需要你们的帮助!

上下文:我正在开发一个应用程序,用于扫描产品的条形码并检索信息。我正在使用 Retrofit 与 API 进行通信。

我有这个:

E/an.fifthscanne: [qarth_debug:] get PatchStore::createDisableExceptionQarthFile method fail. E/AndroidRuntime: FATAL EXCEPTION: main Process: com.givaudan.fifthscanner, PID: 9635 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.givaudan.fifthscanner.http.Product.getBrand()' on a null object reference at com.givaudan.fifthscanner.form$2.onResponse(form.java:121)

问题来自这一行:

brand = data.getProductField().getBrand() + "\n";

当我扫描数据库中不存在的产品时,会发生这种情况。这是它崩溃的地方,我似乎无法进行错误处理。(如果它为 null...)。

(我看到要回答这个问题,人们说要初始化我的对象,但我以他们以外的其他方式使用它,我无法实现它)

法典:

公共类表单扩展 AppCompatActivity {

private TextView textViewResult;
private TextView success;

ProgressDialog progressDialog;
Button btnInsert;
String brand;
String barcode;
String line;
String packaging;
String countries;

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

    textViewResult = findViewById(R.id.text_view_result);

    btnInsert = findViewById(R.id.bt_send_excel);

    //Set the "Loading PopUp"
    progressDialog = new ProgressDialog(form.this);
    progressDialog.setMessage("Loading ...");

    btnInsert.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            addProductData(brand, barcode, line, packaging, countries);
            progressDialog.show();
        }
    });

    //retrieve value CODE_BARRE from MainActivity
    String productCode = getIntent().getStringExtra("productId");

    //=========================
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://world.openfoodfacts.org/api/v0/produit/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestPlaceHolder requestPlaceHolder = retrofit.create(RequestPlaceHolder.class);

    String url = "https://world.openfoodfacts.org/api/v0/produit/" +  productCode + ".json";

    Call<Data> call = requestPlaceHolder.getData(url);

    call.enqueue(new Callback<Data>() {
        @Override
        public void onResponse(Call<Data> call, Response<Data> response) {

            /*if (response.body() != null) {
                //textViewResult.setText("Code" + response.code());
                textViewResult.setText("The product does not exist with this barcode,\n" +
                        "look for the barcode of the product on: \n\n" +
                        "https://fr.openbeautyfacts.org/");
                return;
            }*/

            if (response.isSuccessful()) {
                //Retrieve data and display it

                Data data = response.body();

                barcode = productCode + "\n";
                brand = data.getProductField().getBrand() + "\n";
                line = data.getProductField().getLine() + "\n";
                packaging = data.getProductField().getPackaging() + "\n";
                countries = data.getProductField().getCountries() + "\n";
                String content = brand + "\n" + barcode + "\n" + line +
                        "\n" + packaging + "\n" + countries;
                textViewResult.append(content);
            }

        }

        @Override
        public void onFailure(Call<Data> call, Throwable t) {
            textViewResult.setText(t.getMessage());
        }
    });

}


//Add data to excel
public void addProductData(String brand, String barcode, String line, String packaging, String countries) {

    StringRequest stringRequest = new StringRequest(Request.Method.POST, "https://script.google.com/macros/s/AKfycbwyXLOJEa_Bvgb4Ae-qqX5zWQO0E_MJcUPy7nJBft9MTq3BvCd6gcwy0_2MhGUDFZNo8w/exec", new com.android.volley.Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Intent intent = new Intent(form.this, SuccessActivity.class);
            startActivity(intent);
            progressDialog.hide();

        }
    }, error -> {

    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("sbrand", brand);
            params.put("sbarcode", barcode);
            params.put("sline", line);
            params.put("spackaging", packaging);
            params.put("scountries", countries);

            return params;
        }
    };

    int socketTimeOut = 50000;
    RetryPolicy retryPolicy = new DefaultRetryPolicy(socketTimeOut, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    stringRequest.setRetryPolicy(retryPolicy);

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

}

谢谢你们抽出时间:)

亚尼斯

Java Android 对象 改造

评论

0赞 user2340612 7/30/2022
这回答了你的问题吗?什么是 NullPointerException,如何修复它?
0赞 LAZREQ 7/30/2022
这几乎是我在研究中理解的,它证实了我的想法,谢谢!但是我不知道检查该值是否为 null,因为它在我输入“if”之前崩溃了
0赞 Jake Henry 7/30/2022
if(data != null && data.getProductField != null) { //构建内容并更新文本视图 } else { textViewResult.append(“未找到产品”);
0赞 user2340612 7/30/2022
根据错误消息,代码在调用时崩溃,这意味着返回 null。有多种方法可以处理这个问题(例如,守卫子句),但例如,您可以尝试使用getBrand()data.getProductField()if (data.getProductField() != null) { ... }
0赞 LAZREQ 7/30/2022
它有效,你是颠簸!就是这样 Jacques Henri && user2340612 非常感谢 !

答: 暂无答案