使用 AsyncHttpClient loopj 返回值



我目前正在使用 loopj Android Asynchronous loopj 从 JSON 读取数据。这是我的代码:

public class HorariosActivity extends AppCompatActivity {
String hora_inicio;
String hora_fin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_horarios);
obtDatosBD();
}

private void obtDatosBD(){    
final AsyncHttpClient client = new AsyncHttpClient();
client.get("http://192.168.0.26/WS_policlinica/horas.php", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if(statusCode==200){
try {
JSONArray jsonArray = new JSONArray(new String(responseBody));
for (int i=0; i<jsonArray.length(); i++){
hora_inicio = jsonArray.getJSONObject(i).getString("FISIO_HORA_INICIO");
hora_fin = jsonArray.getJSONObject(i).getString("FISIO_HORA_FIN");
}
}catch (Exception e){
e.printStackTrace();
}
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
}}}

使用此代码,我可以像hora_inicio和hora_fin一样在onSuccess中接收和存储数据。但是,如何在函数之外使用这些值呢?

具体来说,我想在我的onCreate中使用这些变量,但我无法让它工作。

例如创建一个interface

public interface CallbackInterface {
void onDownloadSuccess(JSONArray jsonArray);
void onDownloadFailed(@NonNull Throwable t);
}

然后在下载数据的Activity中实现此接口implements CallbackInterface之后,您将需要override方法onDownloadSuccessonDownloadFailed。例如,在obtDatosBD()pas 作为参数CallbackInterfaceobtDatosBD(CallbackInterface callbackInterface)当您在onCreate中调用obtDatosBD方法时,您需要提供this作为参数。

在方法onSuccess可以将值传递给接口方法:

if(callbackInterface != null)
callbackInterface.onDownloadSuccess(jsonArray);

onFailure方法中遵循相同的内容onDownloadFailed.然后,在您之前override的方法中,您将能够在这种情况下JSONArray获取值,并对它们执行任何需要的操作。我希望这会有所帮助,并希望这是您所需要的。

最新更新