当数据准备就绪时,从改造的警报Mainthread

我有一个改造请求,当我在onResponse中获取数据时, 我在上面的代码中称为繁重工作的文本视图中插入了倍数,我从OnReponse得到结果,否则我会从数据库中得到结果,所以问题是我在OnResponse和OnFailure中有相同的代码,所以有任何方法可以将我繁重的工作放在改进之外,并等待响应只从OnResponse或OnFailure获得一个结果?当数据准备就绪时,从改造的警报Mainthread

call.enqueue(new Callback<Dashboard>() { 

@Override

public void onResponse(Call<Dashboard> call, Response<Dashboard> response) {

realm.beginTransaction();

dashboard = realm.copyToRealmOrUpdate(response.body());

realm.commitTransaction();

// heavy work : insert in data in multiple text views

}

@Override

public void onFailure(Call<Dashboard> call, Throwable t) {

Log.e("error ", "" + t.getMessage());

dashboard = realm.where(Dashboard.class).findFirst();

// heavy work : insert in data in multiple text views

}

}

回答:

试试这个.. 首先创建一个接口..Let称之为OKCallback。

public interface OKCallback { 

void onSuccess(String result);

void onFailure(String result);

}在方法启动改造要求

然后,通过最终OKCallback okCallback这样的..

public void NetworkCall(final OKCallback okCallback){ 

...........

call.enqueue(new Callback<Dashboard>() {

@Override

public void onResponse(Call<Dashboard> call, Response<Dashboard> response) {

realm.beginTransaction();

dashboard = realm.copyToRealmOrUpdate(response.body());

realm.commitTransaction();

// heavy work : insert in data in multiple text views

okCallback.onSuccess(parcel);

}

最后只需在任何类或活动(ActivityX实现OKCallback)和您应该可以在那里完成繁重的工作。您还可以使用Handler将数据包装在onSuccess方法中,如图所示。

@Override 

public void onSuccess(String result) {

Handler handler = new Handler(ActivityX.this.getMainLooper());

//process result and

handler.post(new Runnable() {

@Override

public void run() {

//heavy work done here will run on UI thread

}

});

}

回答:

你可以改变它这样

//create a interface 

public interface ConfirmationCallback {

void onSuccess(YourResponseClass value);

void onError();

}

//call this method from your class

yourApiCall(new ConfirmationCallback() {

@Override

public void onSuccess(YourResponseClass value) {

realm.beginTransaction();

dashboard = realm.copyToRealmOrUpdate(value);

realm.commitTransaction();

// heavy work : insert in data in multiple text views

}

@Override

public void onError() {

dashboard = realm.where(Dashboard.class).findFirst();

// heavy work : insert in data in multiple text views

}

});

public void yourApiCall(final ConfirmationCallback confirmationCallback){

call.enqueue(new Callback<Dashboard>() {

@Override

public void onResponse(Call<Dashboard> call, Response<Dashboard> response) {

confirmationCallback.onSuccess(response.body());

}

@Override

public void onFailure(Call<Dashboard> call, Throwable t) {

Log.e("error ", "" + t.getMessage());

confirmationCallback.onError();

}

}

}

回答:

你可以让一个接口,让回拨主线程或得到在的onSuccess API调用的响应后()或者onFailure处()开始新的AsynTask和处理在后台请求。

以上是 当数据准备就绪时,从改造的警报Mainthread 的全部内容, 来源链接: utcz.com/qa/262156.html

回到顶部