无法使用Retrofit从Google地图获取经度和纬度

时间:2018-01-26 06:47:42

标签: android google-maps google-maps-api-3 retrofit jsonschema2pojo

我已经定义了一个Model类及其中的接口。代码如下:

public class MapModel {
    MapContract.Presenter mPresenter;
    private Location mResLocation;
    private static final String TAG = MapModel.class.getSimpleName();

    public MapModel(MapContract.Presenter presenter) {
        mPresenter = presenter;
    }
    public static WebServiceInterface WebServiceInterface = RetrofitServiceGenerator.create(WebServiceInterface.class);


    public void queryAddress(String address) throws IOException {

        WebServiceInterface .lookupAddress(Constants.GOOGLE_API_KEY, address).enqueue(
                new Callback<Result>() {
                    @Override
                    public void onResponse(Call<Result> call, Response<Result> response) {


                        mResLocation = response.body().getGeometry().getLocation();


 Log.i(TAG, "onResponse: " + response.toString());
                            Log.i(TAG, "Location : " + mResLocation.getLat() + " : " + mResLocation.getLat());
                            mPresenter.onSearchSuccess(mResLocation);
                        }



                  @Override
                    public void onFailure(Call<Result> call, Throwable t) {mPresenter.onSearchFailed("Search failed");
                    }
                }
        );
    }
    public interface WebServiceInterface {

        @GET("json")
        Call<Result> lookupAddress(@Query("key") String apiKey, @Query("address") String searchTerm);
    }

}

我的改装发电机如下:

public class RetrofitServiceGenerator {
    public static <S> S create(Class<S> serviceClass) {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor)
                .readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(30, TimeUnit.SECONDS).build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://maps.googleapis.com/maps/api/geocode/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        return retrofit.create(serviceClass);
    }
}

我遇到的问题是,当我调用方法queryAddress时,它似乎返回null。我已经使用http://www.jsonschema2pojo.org/为json结果创建了POJO对象。您可以看到完整的代码以及POJO类class here。我得到的错误如下:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Double sematec.mehdi.mymap.webmodels.Location.getLat()' on a null object reference 我认为我的请求是正确的,因为okhttp日志显示正确的json响应。所以罪魁祸首就在别的地方。有谁知道我哪里错了?

2 个答案:

答案 0 :(得分:1)

问题是您在从响应中设置对象之前记录了lat / long。这一行

Log.i(TAG, "Location : " + mResLocation.getLat() + " : " + mResLocation.getLat());

应该在您从响应中设置对象之后继续。

所以它应该是:

mResLocation = response.body().getGeometry().getLocation();
Log.i(TAG, "Location : " + mResLocation.getLat() + " : " + mResLocation.getLat());

答案 1 :(得分:1)

我终于找到了问题的根源。如果你看一下网络模型,还有一个GoogleMapModel类。调用方法必须返回该类型。接下来,我们将从中提取位置信息。所以,代码变成了:

static final String STATE_USER = "user";
private String mUser;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
    // Restore value of members from saved state
    mUser = savedInstanceState.getString(STATE_USER);
} else {
    // Probably initialize members with default values for a new instance
    mUser = "NewUser";
}
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(STATE_USER, mUser);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}