我创建了一个将对象发送到服务器的方法。 如果发送失败并进入onFailure方法,我想将对象插入数据库以尝试在连接时发送它。
当我一次调用该方法时,它可以正常工作,但是当我连续进行多次调用时,onFailure始终包含我作为参数传递它的最后一个对象,其余的都丢失了。
public void sendPerson(final Context ctx, final Person person, final boolean requiresInsert){
WebService.getInstance()
.createService(WebServiceAPI.class)
.sendPersonAPI(person)
.enqueue(new Callback<Person>() {
@Override
public void onResponse(Call<Person> call, Response<Person> response) {
Log.d(TAG, "Post successful - " + response.toString());
if (response.code() != 201 && requiresInsert){
String textForMd5 = new Gson().toJson(person);
handlerDB = new HandlerDB();
handlerDB.insertDB(ctx, person, HashMD5.md5(textForMd5));
}
}
@Override
public void onFailure(Call<Person> call, Throwable t) {
Log.d(TAG, "Post failure - " + Objects.requireNonNull(t.getMessage()));
if (requiresInsert){
String textForMd5 = new Gson().toJson(person);
handlerDB = new HandlerDB();
handlerDB.insertDB(ctx, person, HashMD5.md5(textForMd5));
}
}
});
}
这是界面
public interface WebServiceAPI {
@POST("/person")
Call<Person> sendPersonAPI(@Body Person Person);
}
这是我的WebService类
public class WebService {
//private static final String BASE_URL = "http://2905.multimedia-advisor.info:18001";
private static WebService instance;
private Retrofit retrofit;
private HttpLoggingInterceptor httpLoggingInterceptor;
private OkHttpClient.Builder httpClientBuilder;
//Constructor
private WebService(){
//Show the request and response information
httpLoggingInterceptor = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);
httpClientBuilder = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor);
retrofit = new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.client(httpClientBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
//La etiqueta syncronized se asegura que solo haya una instancia.
public static synchronized WebService getInstance(){
if (instance == null){
instance = new WebService();
}
return instance;
}
public <S> S createService(Class<S> serviceClass){
return retrofit.create(serviceClass);
}
}