在项目中添加此界面....
public interface RetrofitCallback {
<T> void getSuccessCallBack(Response<T> response, int position);
void getErrorCallBack(String message, int position);
}
在Utility或RetrofitUtility中添加这些方法。
public static <T> void callRetrofit(final Context context, final Fragment fragment, Call<T> call, final int position, final RetrofitCallback callback) {
final ProgressDialog pDialog = CommonMethod.showProgressDialog(context, context.getResources().getString(R.string.loading));// progress for whole application
call.enqueue(new Callback<T>() {
@Override
public void onResponse(Call<T> call, Response<T> response) {
pDialog.dismiss();
if (response.isSuccessful()) {
ResultBody result = (ResultBody) response.body();
if (result.isSuccess())
callback.getSuccessCallBack(response, position);
else
callback.getErrorCallBack(result.getMessage(), position);
} else
Toast.makeText(context, response.message(), Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<T> call, Throwable t) {
pDialog.dismiss();
if (CommonMethod.checkconnection(context)) { // checking internet connection
Toast.makeText(context, "Server_error", Toast.LENGTH_SHORT).show();
} else {
CommonMethod.showconnectiondialog(context, fragment);
}
}
});
}
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl("XXXXXXXXXXXXX")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
所有Retrofit API
public interface RetrofitApi {
@POST("allData")
Call<UserData> getAllData();
}
在Activity和Fragment中实现RetrofitCallback
像这样打电话给Api
Call<UserData> call = ApiClient.getClient().create(RetrofitApi.class).getAllData();
ApiClient.callRetrofit(context, this, call, 0, this);
您将从下面的RetrofitCallback覆盖方法中获取数据
@Override
public <T> void getSuccessCallBack(Response<T> response, int position) {
UserData userData = ((UserData) response.body());
// do your operation over here
}
@Override
public void getErrorCallBack(String message, int position) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
这是所有型号文件....
ResultBody.class
public class ResultBody {
private String message;
private boolean success;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
}
UserData.class
public class UserData extends ResultBody {
private User userData;
public User getUserData() {
return userData;
}
public void setUserData(User user) {
this.userData = user;
}
}
如果你卡在任何地方,让我知道.....
相关帖子或问题