Return 值与 AsyncHttpClient loopj

Return value with AsyncHttpClient loopj

我目前正在使用 loopj Android 异步 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) {

            }
        });
    }}}

使用此代码,我可以在 onSuccess 中接收和存储数据,如 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() 中作为参数 CallbackInterface 例如: obtDatosBD(CallbackInterface callbackInterface) 当你在 onCreate 中调用 obtDatosBD 方法时,你需要提供 this 作为参数.

onSuccess 方法中,您可以将值传递给接口方法:

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

onFailure 方法中使用 onDownloadFailed 执行相同的操作。然后在您之前 override 的方法中,您将能够在这种情况下获得值 JSONArray 并使用它们做任何您需要的事情。我希望这会有所帮助,希望这就是您所需要的。