【问题标题】:Retrofit Call GSON Return null Object改造调用 GSON 返回空对象
【发布时间】:2018-12-05 05:47:43
【问题描述】:

我向 NearByApi 创建了一个请求,该请求 Get Nearby place 和 location place ,但我从 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 中。我将地名和位置从谷歌地图发送到方法调用,当用户单击按钮时,地名将发送到 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 中的这一行是 return null

呼叫呼叫 = MyApplication.getApp().getApiService().getNearbyPlaces(placeType, location.getLatitude() + "," + location.getLongitude(), PROXIMITY_RADIUS);

【问题讨论】:

    标签: android


    【解决方案1】:
    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());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 2018-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多