我目前正在创建一个带有API调用的实时货币转换器应用程序,但是每当我单击Button来转换货币时,我的应用程序就会崩溃,我得到了这一行:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.gson.JsonObject com.google.gson.JsonObject.getAsJsonObject(java.lang.String)' on a null object reference
at com.example.converterproject.MoneyActivity$1$1.onResponse(MoneyActivity.java:70)下面是我编写的一些代码:
MoneyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RetrofitInterface retrofitInterface = RetrofitBuilder.getRetrofitInstance().create(RetrofitInterface.class);
Call<JsonObject> call = retrofitInterface.getExchangeCurrency(MoneyTo.getSelectedItem().toString());
call.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
JsonObject res = response.body();
JsonObject rates = res.getAsJsonObject("rates");
double currency = Double.valueOf(MoneyEd.getText().toString());
double multiplier = Double.valueOf(rates.get(MoneyFrom.getSelectedItem().toString()).toString());
double result = currency * multiplier;
MoneyTextView.setText(String.valueOf(result));
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
}
});
}
});因此,很明显,JsonObject rates = res.getAsJsonObject("rates");是导致问题的原因。我真的不知道怎么解决这个问题,所以我非常感谢你的帮助
发布于 2022-09-16 13:56:32
您的响应似乎是JsonObject,您不需要获取res,即JsonObject => JsonObject res = response.body(); as JsonObject。
所以如果你删除这一行
JsonObject rates = res.getAsJsonObject("rates");取而代之的是使用res。我想这会管用的。
https://stackoverflow.com/questions/73737352
复制相似问题