改造电话GSON返回空对象

时间:2018-12-05 05:47:44

标签: android

我创建了一个对NearByApi的请求,该请求获取“附近”和“位置”,但是我从MyApplication类中获取了Null对象

public class MyApplication extends Application {
    NearByApi nearByApi = null;
    static MyApplication app;

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
    }


    public NearByApi getApiService() {
        if (nearByApi == null) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient.Builder().retryOnConnectionFailure(true).readTimeout(80, TimeUnit.SECONDS).connectTimeout(80, TimeUnit.SECONDS).addInterceptor(interceptor).build();

            Retrofit retrofit = new Retrofit.Builder().baseUrl(Constant.PLACE_API_BASE_URL).addConverterFactory(getApiConvertorFactory()).client(client).build();

            nearByApi = retrofit.create(NearByApi.class);
            return nearByApi;
        } else {
            return nearByApi;
        }
    }

    private static GsonConverterFactory getApiConvertorFactory() {
        return GsonConverterFactory.create();
    }


    public static MyApplication getApp() {
        return app;
    }

}

在MainActicity中。我将地点和位置的名称从Google地图发送到方法调用,当用户单击按钮时,会将地点名称发送到FindPlace方法

 public void onHospitalsFindClick(View view){

        Log.e("Lonnng", location.getLatitude() + " !!!" + location.getLongitude());

         findPlaces("hospital");

        Intent intent = new Intent(SearchNearByPlaces.this, DetailActivity.class);
        startActivity(intent);
    }

    public void findPlaces(String placeType){

      Log.e("fad", String.valueOf(MyApplication.getApp().getApiService()));
        Log.e("fad", "fadend");

            Call<NearByApiResponse> call = MyApplication.getApp().getApiService().getNearbyPlaces(placeType, location.getLatitude() + "," + location.getLongitude(), PROXIMITY_RADIUS);

        call.enqueue(new Callback<NearByApiResponse>() {
            @Override
            public void onResponse(Call<NearByApiResponse> call, Response<NearByApiResponse> response) {
                try {
                    googleMap.clear();
                    // This loop will go through all the results and add marker on each location.
                    for (int i = 0; i < 5; i++) {
                        Double lat = response.body().getResults().get(i).getGeometry().getLocation().getLat();
                        Double lng = response.body().getResults().get(i).getGeometry().getLocation().getLng();
                        String placeName = response.body().getResults().get(i).getName();
                        String vicinity = response.body().getResults().get(i).getVicinity();
                        ArrayList<String> strings= new ArrayList<>();
                        strings.add(placeName);
                        strings.add(vicinity);
                        Log.e("TAGTT",strings.toString());
                        MarkerOptions markerOptions = new MarkerOptions();
                        LatLng latLng = new LatLng(lat, lng);
                        // Location of Marker on Map
                        markerOptions.position(latLng);
                        // Title for Marker
                        markerOptions.title(placeName + " : " + vicinity);
                        titlelist.add(placeName);

                        // Color or drawable for marker
                        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
                        // add marker

                        Marker m = googleMap.addMarker(markerOptions);
                        // move map camera
                        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                        googleMap.animateCamera(CameraUpdateFactory.zoomTo(13));
                    }

                } catch (Exception e) {
                    Log.d("onResponse", "There is an error");
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<NearByApiResponse> call, Throwable t) {
                Log.d("onFailure", t.toString());
                t.printStackTrace();
                PROXIMITY_RADIUS += 10000;
            }
        });
    }

我不知道为什么mainActivity中的这一行返回null

  

通话=   MyApplication.getApp()。getApiService()。getNearbyPlaces(placeType,   location.getLatitude()+“,” + location.getLongitude(),   PROXIMITY_RADIUS);

1 个答案:

答案 0 :(得分:0)

Try this code... 

public static Retrofit getRetrofit() {
    if (retrofit == null) retrofit = new Retrofit.Builder()
            .baseUrl(BuildConfigure.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(getClient())
            .build();
    return retrofit;
}

private static OkHttpClient getClient() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder()
            .addNetworkInterceptor(interceptor)
            .addNetworkInterceptor(new AddHeaderInterceptor())
            .connectTimeout(10, TimeUnit.MINUTES)
            .readTimeout(10, TimeUnit.MINUTES)
            .retryOnConnectionFailure(true)
            .build();
    client.connectionPool().evictAll();
    return client;
}

public static class AddHeaderInterceptor implements Interceptor {
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        builder.addHeader("X-Requested-With", "XMLHttpRequest");
        builder.addHeader("Authorization", "" + GlobalData.accessToken);
        return chain.proceed(builder.build());
    }
}