androidloopj

Return value with AsyncHttpClient loopj


I currently using loopj Android Asynchronous loopj to read data from a JSON. This is my code:

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) {

            }
        });
    }}}

With this code, i can receive and storage data in onSuccess like hora_inicio and hora_fin. But how is it possible to use those values outside function onSuccess?

Specifically, I want to use those variables in my onCreate, but I cannot get it to work.


Solution

  • Create an interface for example:

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

    Then inside your Activity where you download data implement this interface implements CallbackInterface after that you will need yo override methods onDownloadSuccess and onDownloadFailed. In your obtDatosBD() pas as parameter CallbackInterface for example: obtDatosBD(CallbackInterface callbackInterface) when you call obtDatosBD method in onCreate you will need to provide this as parameter.

    Inside onSuccess method you can pass the values to interface method:

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

    Following same thing inside onFailure method with onDownloadFailed. Then in methods which you previously override you will be able to get values in this case JSONArray and do whatever you need with them. I hope this will help and hope this is what you need.