在调用方法中改进null错误

时间:2018-08-13 13:58:15

标签: java android retrofit2

我想通过改造从MySQL数据库中获取最后一个ID,但是当运行项目的邮递员测试的调用方法值出错并获取值时

APIClient.java:

public class APIClient {
private static final String BASE_URL = "http://**********/Api/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
    if (retrofit == null) {
        retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}

}

APIIinterface.java:

public interface APIIinterface {

@POST("Agahi/getlastid.php")
Call<AgahiLastId> getAgahiLastId(); }

AgahiLastId.java:

public class AgahiLastId {

    @SerializedName("agahi_id")
    private int agahi_id;

    public int getAgahi_id() {
        return agahi_id;
    }

    public void setAgahi_id(int agahi_id) {
        this.agahi_id = agahi_id;
    }
}

MainActivity.java:

       public class MainActivity extends AppCompatActivity {


private APIIinterface apiIinterface;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

Call<AgahiLastId> agahiLastIdCall = apiIinterface.getAgahiLastId();

agahiLastIdCall.enqueue(new Callback<AgahiLastId>() {
    @Override
    public void onResponse(Call<AgahiLastId> call, Response<AgahiLastId> response) {
        if (response.isSuccessful()) {
            Log.d("lts","ok");
        }
    }

    @Override
    public void onFailure(Call<AgahiLastId> call, Throwable t) {

    }
});}

我在此行中遇到错误:

Call<AgahiLastId> agahiLastIdCall = apiIinterface.getAgahiLastId();

错误日志:

 Attempt to invoke the interface method 'retrofit2. Call app.zagroszoom.mseif.com.zagroszoom.webService.APIIinterface.getAgahiLastId()' on a null object reference

2 个答案:

答案 0 :(得分:0)

您需要在Mainactivity之前的onCreate内的Call<AgahiLastId> agahiLastIdCall = apiIinterface.getAgahiLastId();中添加以下内容

apiIinterface= APIClient.getClient().create(APIIinterface.class);

详细了解Retrofit here

答案 1 :(得分:0)

您错过了电话。      APIIinterface apiIinterface = ApiUtils.getAPIService();

After that  you can call the own method.

Call<AgahiLastId> agahiLastIdCall = apiIinterface.getAgahiLastId();

agahiLastIdCall.enqueue(new Callback<AgahiLastId>() {
    @Override
    public void onResponse(Call<AgahiLastId> call, Response<AgahiLastId> response) {
        if (response.isSuccessful()) {
            Log.d("lts","ok");
        }
    }

    @Override
    public void onFailure(Call<AgahiLastId> call, Throwable t) {

    }
});}