java.lang.NullPointerException on converter app

Viewed 41

I'm currently creating a live currency converter app with API calls, but whenever I click the Button to convert the currency, my app crashes and I get this line:

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)

Here's some of the code I wrote:

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) {

                }
            });
        }
    });

So apparently JsonObject rates = res.getAsJsonObject("rates"); is the line that's causing the problem. I really don't know how to fix this so I would be very grateful for some help

1 Answers

it's appear your response is JsonObject and you don't need to get res which is JsonObject => JsonObject res = response.body(); as JsonObject.

so if you remove this line

 JsonObject rates = res.getAsJsonObject("rates");

and use res instead. I think this will work.

Related