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?