Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronous ResponseHandler used in AsyncHttpClient Error

last day i was trying fix an error with my asynchttpclient, but the help that i founded didnt fix the problem. Hope somebody can help me with it. The error is when i start the service, i want that task is allways doing a sql query with php and it receive params that i will use later.

Error is:01-30 00:20:25.319 4167-4671/proyecto.android W/AsyncHttpRH: Current thread has not called Looper.prepare(). Forcing synchronous mode.
01-30 00:20:25.320 4167-4671/proyecto.android W/System.err: java.lang.IllegalArgumentException: Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead.
01-30 00:20:25.320 4167-4671/proyecto.android W/System.err:     at com.loopj.android.http.AsyncHttpClient.sendRequest(AsyncHttpClient.java:1493)
01-30 00:20:25.320 4167-4671/proyecto.android W/System.err:     at com.loopj.android.http.AsyncHttpClient.post(AsyncHttpClient.java:1169)
01-30 00:20:25.320 4167-4671/proyecto.android W/System.err:     at com.loopj.android.http.AsyncHttpClient.post(AsyncHttpClient.java:1152)
01-30 00:20:25.320 4167-4671/proyecto.android W/System.err:     at com.loopj.android.http.AsyncHttpClient.post(AsyncHttpClient.java:1139)
01-30 00:20:25.320 4167-4671/proyecto.android W/System.err:     at proyecto.android.MyService.ConsultaCaract(MyService.java:128)
01-30 00:20:25.320 4167-4671/proyecto.android W/System.err:     at proyecto.android.MyService$MyTask.doInBackground(MyService.java:72)
01-30 00:20:25.320 4167-4671/proyecto.android W/System.err:     at proyecto.android.MyService$MyTask.doInBackground(MyService.java:61)
01-30 00:20:25.320 4167-4671/proyecto.android W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
01-30 00:20:25.320 4167-4671/proyecto.android W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-30 00:20:25.320 4167-4671/proyecto.android W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-30 00:20:25.321 4167-4671/proyecto.android W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-30 00:20:25.321 4167-4671/proyecto.android W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-30 00:20:25.321 4167-4671/proyecto.android W/System.err:     at java.lang.Thread.run(Thread.java:818)

And my code is this:

package proyecto.android;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;

import java.util.ArrayList;

public class MyService extends Service {
    MediaPlayer  mp;
    String email="[email protected]";
    MyTask task= new MyTask();
  //  Bundle miBundle= getIntent().getExtras();
  // Bundle datosext = getIntent().getExtras();



   // String email=datosext.getString("email");
    @Override
    public void onCreate() {
        super.onCreate();
    }

    //Al pulsar el boton de iniciar servicio se ejecutara onStartCommand
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Toast.makeText(this, "Servicio Iniciado", Toast.LENGTH_SHORT).show();
        try {
            task.execute();
        }catch (Exception e){
            e.printStackTrace();
        }
        return START_STICKY;
    }

    //Al pulsar el boton de destruir servicio se ejecutara ondestroy
    @Override
    public void onDestroy(){
        Toast.makeText(this, "Servicio Detenido", Toast.LENGTH_SHORT).show();
        task.onCancelled();
    }



    private class MyTask extends AsyncTask<String, String, String>{
        boolean time=true;

        int contador=0;
        @Override
        protected String doInBackground(String... params) {
        while(time) {
            try {
                Log.e("Entro", "En log dentro de while: " + email + " " + (++contador));
                Thread.sleep(2000);
                //ConsultaCaract(email);
                ConsultaCaract(email);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
            return null;
        }




        @Override
        protected void onPostExecute(String s) {
           super.onPostExecute(s);
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    ConsultaCaract(email);
                }
            }, 10000);

        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            time=false;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
            //inicio();
        }


    }
    public void inicio(){
        ConsultaCaract(email);
    }



    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }



    public void ConsultaCaract(String email) {
        String url="http://localhost/scripts/Envio_Datos/android_functions.php";
        RequestParams params = new RequestParams();
        params.put("email", email);

        AsyncHttpClient cliente = new AsyncHttpClient();

        cliente.post(url, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes) {
                getDataJson(new String(bytes));
            }

            @Override
            public void onFailure(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes, Throwable throwable) {
                conection_error();
            }

        });

    }
    //Toast indicando error para la conexión ocn la BD
    public void conection_error(){
        Vibrator vibrator =(Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(200);
        Toast errtoast = Toast.makeText(getApplicationContext(),"Servidor: Hay un problema con el servidor, intentelo mas tarde.", Toast.LENGTH_SHORT);
        errtoast.show();
    }
    //Se crea un Array en JSON por el cual obtenemos los valores logstatus(0 o 1 segun si existe o no) y el campo Nombre de la consulta SQL
    public ArrayList<String > getDataJson(String response){
        ArrayList<String> listado=new ArrayList<String>();
        try{
            JSONArray jsonArray= new JSONArray(response);
            String Wifi,Bluetooth, email,Camera, GPS, Vibracion, Alarma;

            for(int i =0; i<jsonArray.length();i++){
                Wifi=jsonArray.getJSONObject(i).getString("Wifi");
                Bluetooth=jsonArray.getJSONObject(i).getString("Bluetooth");
                Camera=jsonArray.getJSONObject(i).getString("Camera");
                GPS=jsonArray.getJSONObject(i).getString("GPS");
                Vibracion=jsonArray.getJSONObject(i).getString("Vibracion");
                Alarma=jsonArray.getJSONObject(i).getString("Alarma");
                ComprFunc(Wifi, Bluetooth, Camera, GPS, Vibracion, Alarma);
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return listado;
    }

    //Funcion para iniciar aplicaciones de movil.
    public void ComprFunc(String Wifi, String Bluetooth, String Camera, String GPS, String Vibracion, String Alarma){
        WifiManager admin_wifi=(WifiManager)this.getSystemService(Context.WIFI_SERVICE);
        mp = MediaPlayer.create(this, R.raw.sirena);
        BluetoothAdapter adapter_bluetooth=BluetoothAdapter.getDefaultAdapter();

        if(Wifi.equals("1")){
            admin_wifi.setWifiEnabled(admin_wifi.isWifiEnabled());
            Wifi="0";
        }
        else{
            admin_wifi.setWifiEnabled(!admin_wifi.isWifiEnabled());
        }
        if (Alarma.equals("1")) {
            mp.start();
        } else{
            mp.stop();
        }
        if(Vibracion.equals("1")){
            Vibrator vibrator =(Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            vibrator.vibrate(3500);
        }
        if(Bluetooth.equals("1")){
            adapter_bluetooth.enable();
        }
        else{
            adapter_bluetooth.disable();
        }

    }

}

Thx for the future help!!

like image 636
Toote Avatar asked Jan 29 '16 23:01

Toote


1 Answers

The error "Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead." hints on what is the problem.

Since in this case you wanna use AsyncHttpClient and not the SyncHttpClient you will need to use the looper thread.

Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = new Runnable() {
           @Override
            public void run() {
                //Code that uses AsyncHttpClient in your case ConsultaCaract()
            }
        };
mainHandler.post(myRunnable);
like image 121
little Avatar answered Sep 23 '22 17:09

little