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.
Create an
interfacefor example:Then inside your
Activitywhere you download data implement this interfaceimplements CallbackInterfaceafter that you will need yooverridemethodsonDownloadSuccessandonDownloadFailed. In yourobtDatosBD()pas as parameterCallbackInterfacefor example:obtDatosBD(CallbackInterface callbackInterface)when you callobtDatosBDmethod inonCreateyou will need to providethisas parameter.Inside
onSuccessmethod you can pass the values to interface method:Following same thing inside
onFailuremethod withonDownloadFailed. Then in methods which you previouslyoverrideyou will be able to get values in this caseJSONArrayand do whatever you need with them. I hope this will help and hope this is what you need.