consume Json in android studio FATAL EXCEPTION: Thread-13149

1

I have the following code to consume data from a webservice:

public String enviardatosGet(String user, String pass){

    URL url = null;
    String linea = "";
    int respuesta = 0;
    StringBuilder resul = null;
    try {
        url = new URL("http://www.nestel.cl/Login.php?user="+user+"&pass="+pass);
        HttpURLConnection conexion= (HttpsURLConnection)url.openConnection();
        respuesta=conexion.getResponseCode();

        resul=new StringBuilder();

        if (respuesta==HttpURLConnection.HTTP_OK )
        {
            InputStream in=new BufferedInputStream(conexion.getInputStream());
            BufferedReader reader=new BufferedReader(new InputStreamReader(in));

            while((linea=reader.readLine())!=null)
            {
                resul.append(linea);
            }
        }

        }
    catch (Exception e){
        Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
    }

    return resul.toString();
}


public int obtenerdatosJSON(String response){

    int respuesta = 0;
    try {
        JSONArray json = new JSONArray(response);
        if(json.length()>0)
        {
            respuesta = 1;
        }
    }catch (Exception e){}
    return  respuesta;
}


public void onClick(View v) {

    Thread tr = new Thread(){
        @Override
        public void run() {
            final String resultado = enviardatosGet(mirut.getText().toString(), mipass.getText().toString());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    int r=obtenerdatosJSON(resultado);
                    if(r>0){
                        Intent i = new Intent(getApplicationContext(),menu.class);

                        startActivity(i);
                    }else{
                        Toast.makeText(getApplicationContext(), "usuario o pass incorrecto", Toast.LENGTH_LONG).show();
                    }
                }
            });
        }
    };
    tr.start();
}

I get the following error:

FATAL EXCEPTION: Thread-13149

              Process: com.example.luisalarcon.alumnos, PID: 24002

              java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
                  at android.os.Handler.<init>(Handler.java:200)
                  at android.os.Handler.<init>(Handler.java:114)
                  at android.widget.Toast$TN.<init>(Toast.java:627)
                  at android.widget.Toast.<init>(Toast.java:131)
                  at android.widget.Toast.makeText(Toast.java:431)
                  at com.example.luisalarcon.alumnos.MainActivity.enviardatosGet(MainActivity.java:67)
                  at com.example.luisalarcon.alumnos.MainActivity$1.run(MainActivity.java:93)

Any solution?

    
asked by luis alarcon 24.11.2016 в 22:32
source

2 answers

2

By clicking on your button, you do not need to create a Thread , since you're using runOnUiThread () , I suggest you add your enviardatosGet() request as well so that you should be able to run this operation without problems inside the main Thread:

public void onClick(View v) {

 //   Thread tr = new Thread(){
 //        @Override
 //       public void run() {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                     String resultado = enviardatosGet(mirut.getText().toString(), mipass.getText().toString());
                    int r=obtenerdatosJSON(resultado);
                    if(r>0){
                        Intent i = new Intent(getApplicationContext(),menu.class);

                        startActivity(i);
                    }else{
                        Toast.makeText(getApplicationContext(), "usuario o pass incorrecto", Toast.LENGTH_LONG).show();
                    }
                }
            });
  //      }
  // };
  //  tr.start();
}
    
answered by 24.11.2016 в 23:35
0

Good, the use of Threads in android has the inconvenience that you can not change anything from the UI from there, you can use AsyncTask here I leave you an example of how you could mount it:

private class JsonTask extends AsyncTask<String, Integer, String> {
 @Override
 protected String doInBackground(String... urls) {
     String resultado = enviardatosGet(mirut.getText().toString(), mipass.getText().toString());
     return resultado;
 }

 @Override
 protected void onPostExecute(String result) {
     int r=obtenerdatosJSON(result);
     if(r>0){
        Intent i = new Intent(getApplicationContext(),menu.class);

        startActivity(i);
     }else{
        Toast.makeText(getApplicationContext(), "usuario o pass incorrecto", Toast.LENGTH_LONG).show();
     }
 }
}

new JsonTask().execute("");

I have not been able to try it because I do not have the Android Studio in front of me, try and tell me how it has gone.

Greetings!

    
answered by 25.11.2016 в 11:39