使用改装从调用 google 位置 api 中获取 response.body null

Getting response.body null from calling google places api using retrofit

在此之前,我曾尝试在没有图书馆的情况下这样做,但效果很好。 但是使用改造库我得到它返回这个日志:

FATAL EXCEPTION: main Process: com.example.lenovo.retrof, PID: 21218 java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.lenovo.retrof.POJO.MainResponse.getResults()' on a null object reference at com.example.lenovo.retrof.MainActivity.onResponse(MainActivity.java:53) at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.run(ExecutorCallAdapterFactory.java:68) at android.os.Handler.handleCallback(Handler.java:815) at android.os.Handler.dispatchMessage(Handler.java:104) at android.os.Looper.loop(Looper.java:207) at android.app.ActivityThread.main(ActivityThread.java:5728) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

这是我在崩溃时的代码:

gitrep.enqueue(new Callback<MainResponse>() {
        @Override
        public void onResponse(Call<MainResponse> call, Response<MainResponse> response) {
            if(response == null){
                Log.d("place","place id null");
            }
            else {
                for (int i =0; i < response.body().getResults().size(); i++){
                    String place_id = response.body().getResults().get(i).getPlaceId();
                    Log.d("place",place_id);

                }

            }
        }

这也是我的 MainResponse pojo class

public class MainResponse {
    @SerializedName("html_attributions")
    @Expose
    private List<Object> html_attributions = new ArrayList<Object>();

@SerializedName("next_page_token")
@Expose
private String next_page_token;

@SerializedName("results")
@Expose
private List<Result> results = new ArrayList<Result>();

@SerializedName("status")
@Expose
private String status;

public List<Object> getHtml_attributions() {
    return html_attributions;
}

public void setHtml_attributions(List<Object> html_attributions) {
    this.html_attributions = html_attributions;
}

public String getNext_page_token() {
    return next_page_token;
}

public void setNext_page_token(String next_page_token) {
    this.next_page_token = next_page_token;
}

public List<Result> getResults() {
    return results;
}

public void setResults(List<Result> results) {
    this.results = results;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

}

我找到了解决问题的方法。 顺便学了一些retrofit的tricky

我将其声明为基础 URL:

https://maps.googleapis.com/maps/api/place/

而不是这个:

https://maps.googleapis.com/

Retrofit 会自动删除 /maps/place/ 并给我留下不完整的请求。 我通过记录我得到的响应发现了字符串。 然后我得到了错误的 URL 作为响应,我进行了更改并且现在工作正常。

所以要改造,BASE URL 是 BASE URL...仅此而已