Foro sobre Android > E/AndroidRuntime﹕ FATAL EXCEPTION: main android.os.NetworkOnMainThreadException
Está intentando crear un conexión contra un web service en el hilo principal de la aplicación por lo visto a partir de la version 9 de la SDK no está permitido.
Te dejo un par de referencias:
http://stackoverflow.com/questions/13136539/caused-by-android-os-networkonmainthreadexception
http://stackoverflow.com/questions/25093546/android-os-networkonmainthreadexception-at-android-os-strictmodeandroidblockgua
Tienes que meter tu llamada en un Async Task
http://programmerguru.com/android-tutorial/android-asynctask-example/
a mi pasa lo mismo pero queriendo consumir un webservices con asp con el metodo Soap.. me podrian ayudar.. ya tengo mi codigo con la clase extendida... pero me truena...
package com.example.onc_lap.oncontrolmobile;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.net.URL;
import java.net.URLConnection;
public class Principal extends AppCompatActivity {
EditText txtusuario;
EditText txtpassword;
private Button btningresar;
private ProgressDialog pDialog;
public final int dialogo_alert = 0;
public String msje = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
txtusuario = (EditText) findViewById(R.id.txtusuario);
txtpassword = (EditText) findViewById(R.id.txtpassword);
btningresar = (Button) findViewById(R.id.btningresar);
btningresar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new webserv().execute();
} //fin del click view
});
}
class webserv extends AsyncTask<String, String, String> {
protected void onPreExecute() {
String usuario = txtusuario.getText().toString();
String password = txtpassword.getText().toString();
pDialog = new ProgressDialog(Principal.this);
pDialog.setMessage("Iniciando sesion ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
final String NAMESPACE = "http://ONControl_MobileWS/";
final String URL = "http://oncontrol.no-ip.net:9020/ONControl_MobileWS.asmx";
final String METHOD_NAME = "Login";
final String SOAP_ACTION = "http://ONControl_MobileWS/Login";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try {
transporte.call(SOAP_ACTION, envelope);
SoapPrimitive resultado_xml = (SoapPrimitive) envelope.getResponse();
String res = resultado_xml.toString();
msje = res;
if (res.equals("Gracias por Iniciar Sesion")) {
//envia al otro activity
Intent intent = new Intent("menu.class");
startActivity(intent);
finish();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
/* protected void onPostExecute(){
Intent intent = new Intent("menu.class");
startActivity(intent);
finish();
}*/
}
}
e tal amigos, tengo una aplicacion movil que debe conectar a moodle, sin embargo al tratar de realizar el login me aparece el siguiente error , soy nuevo en java, alguien puede ayudarme please
11-04 23:47:17.205 5524-5524/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:769)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:743)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
at moodle.android.APLICACIONMOVILDECAMPUSVIRTUAL.General.TokenHttpRequest.doHTTPRequest(TokenHttpRequest.java:29)
at moodle.android.APLICACIONMOVILDECAMPUSVIRTUAL.General.Login.onClick(Login.java:138)
at android.view.View.performClick(View.java:4198)
at android.view.View$PerformClick.run(View.java:17158)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4918)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
at dalvik.system.NativeStart.main(Native Method)
///////////////////////////////////////////////////////////////////////////////////////////////
aqui estan mis dos clases
public class Login extends Activity implements OnClickListener {
Button login;
EditText siteUrl, username, password;
User user;
SharedPreferences saved;
String loginDetails;
ProgressDialog dialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
try {
siteUrl = (EditText) findViewById(R.id.moodle_url);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login_button);
try {
//
siteUrl.setHint(R.string.login_url_hint);
username.setHint(R.string.login_username_hint);
password.setHint(R.string.login_password_hint);
siteUrl.setText("https://uacjmoodle.milaulas.com");
username.setText("juan_guardado");
password.setText("Prueba123#");
} catch (Exception e) {
Log.e("NoPreferences", e.toString());
}
login.setOnClickListener(this);
} catch (Exception e) {
Log.e("Error With Login", e.toString());
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_button:
dialog = ProgressDialog.show(this, "",
"Verificando Ususrio y Contraseña", true);
if (AppStatus.getInstance(Login.this).isOnline(Login.this)) {
String conType = AppStatus.getInstance(Login.this).getConnectionType(Login.this);
conType = conType == null ? "No hay cursos visibles" : conType;
Toast.makeText(getApplicationContext(), "Estas en linea (" + conType + ")!!!!", Toast.LENGTH_LONG).show();
} else {
messageHandler.sendEmptyMessage(0);
Toast.makeText(getApplicationContext(), "No tienes Internet!!!!", Toast.LENGTH_LONG).show();
}
String siteUrlVal = siteUrl.getText().toString();
String usr = username.getText().toString();
String pwd = password.getText().toString();
String usrUri = Uri.encode(usr);
String pwdUri = Uri.encode(pwd);
saved = getSharedPreferences(loginDetails, MODE_PRIVATE);
SharedPreferences.Editor e = saved.edit();
e.putString("siteUrlVal", siteUrlVal);
e.putString("usr", usr);
e.putString("pwd", pwd);
e.commit();
//moodle_mobile_app
String url = siteUrlVal + "/login/token.php?username=" + usrUri + "&password=" + pwdUri + "&rest";
//url = "https://uacjmoodle.milaulas.com/login/token.php?username=festrada&password=Profesor123!&service=&service=moodle_mobile_app";//&service=moodle_mobile_app
TokenHttpRequest tokenRequest = new TokenHttpRequest();
String token = tokenRequest.doHTTPRequest(url);
//se quito la llamada a tokenrequest y se le asigna el token manual
//se declara este tocken para acceder a la informacion del usuario festrada
//String token= "700c1d9f3af35836885b12a65a584e1e"; //acceder a la informacion del usuario festrada
if (token != null && token != "")
{
String serverurl = siteUrlVal + "/webservice/rest/server.php" + "?wstoken=" + token + "&wsfunction=";
user = new User();
user.setUsername(usr);
user.setPassword(pwd);
user.setToken(token);
user.setTokenCreateDate();
user.setUrl(url);
//AQUI SE MANDA LLAMAR A LA CLASE MOODLEWEBSERVICE
//PARA OBTENER LA INFORMACION DE LOS CURSOS EN LO QUE ESTA INSC
//Y LA INFORMACION DE LOS CURSOS
//crea objeto de tipo Moodlewebservice, para poder mandar llamar getSiteinfo
MoodleWebService webService = new MoodleWebService(Login.this);
//crea objeto siteInfo para envianrselo vacio como parametro a funcion getsiteinfo
SiteInfo siteInfo = new SiteInfo();
//IdUser idUser = new IdUser();
//LLAMADA A 1ER WEBSERVICE PARA OBTENER DATOS DE DOC XML NOMBRE COMPLETO DE USUARIO Y NOMBRE D SITIO)
webService.getSiteinfo(serverurl, siteInfo);//llamada a webservice 1
user.setSiteInfo(siteInfo);
ArrayList<Course> courses = new ArrayList<Course>();
if (courses.size() > 0) {
for (int i = 0; i < courses.size(); i++) {
Course c = courses.get(i);
ArrayList<CourseContent> coursecontents = new ArrayList<CourseContent>();
webService.getCourseContents(serverurl, c.getId(), coursecontents);
if (coursecontents.size() > 0) {
c.setCourseContent(coursecontents);
}
} //fin for
user.setCourses(courses);
Intent nextPage;
//
nextPage = new Intent(Login.this, CourseDetail.class);
nextPage.putExtra("userObject", user);
startActivity(nextPage);
} else {
messageHandler.sendEmptyMessage(0);
Log.e("Course Error", "Usuario no esta inscrito en un curso");
Toast.makeText(getApplicationContext(), "No tienes curso(s) asignados", Toast.LENGTH_LONG).show();
}
} else {
messageHandler.sendEmptyMessage(0);
Toast.makeText(getApplicationContext(), "El usuario o contraseña son incorrectos. Intenta de nuevo!", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Verifica si el sitio tiene habilitado el protocolo REST", Toast.LENGTH_LONG).show();
}
break;
default:
}
}
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
dialog.dismiss();
}
};
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class TokenHttpRequest {
public String doHTTPRequest(String url){
String responseBody = "";
String token = "";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
try {
ResponseHandler<String> responseHandler=new BasicResponseHandler();
responseBody = httpClient.execute(httpPost, responseHandler);
JSONObject jObject = new JSONObject(responseBody);
token = jObject.getString("token");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
return token;
}
}