java.lang.NullPointerException:尝试从空对象引用中的字段FCMResponce.success中读取

时间:2019-03-18 13:21:36

标签: android nullpointerexception retrofit

如何解决此错误

java.lang.NullPointerException: Attempt to read from field 'int com.ddu.d_ride_customer.Model.FCMResponce.success' on a null object reference

FCMClient类

public class FCMClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseURL)
{
    if(retrofit == null)
    {
        retrofit = new Retrofit.Builder()
                .baseUrl(baseURL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
  }
}

产生错误的示例代码

   mService.sendMessage(content)
                                .enqueue(new Callback<FCMResponce>() {
                                    @Override
                                    public void onResponse(Call<FCMResponce> call, Response<FCMResponce> response) {
                                        if(response.isSuccessful() && response.body()!=null) {
                                            Toast.makeText(Home.this, "Request sent!", Toast.LENGTH_SHORT).show();
                                        }
                                        else
                                            Toast.makeText(Home.this, "Failed", Toast.LENGTH_SHORT).show();
                                    }

1 个答案:

答案 0 :(得分:0)

您在.addConverterFactory(GsonConverterFactory.create())中使用Gson 因此,在返回改造之前,您还需要改造接口。您应该具有解析响应的接口。 因此,例如可以使用响应https://square.github.io/retrofit/的gsonInterface(随机名称)(来自GitHub改造示例:公共接口

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

) 然后在返回改造之前 gsonInterface = retrofit.create(gsonInterafce.class); 或注释掉.addConverterFactory(GsonConverterFactory.create())行 也使用相同版本的库: retrofit convertor factory can not access GsonConverterFactory