que 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.onNe twork(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.DefaultClientConnectionO perator.openConnection(DefaultClientConnectionOper ator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(A bstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapte r.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector .execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.exe cute(AbstractHttpClient.java:670)
at org.apache.http.impl.client.AbstractHttpClient.exe cute(AbstractHttpClient.java:769)
at org.apache.http.impl.client.AbstractHttpClient.exe cute(AbstractHttpClient.java:743)
at org.apache.http.impl.client.AbstractHttpClient.exe cute(AbstractHttpClient.java:732)
at moodle.android.APLICACIONMOVILDECAMPUSVIRTUAL.Gene ral.TokenHttpRequest.doHTTPRequest(TokenHttpReques t.java:29)
at moodle.android.APLICACIONMOVILDECAMPUSVIRTUAL.Gene ral.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.jav a:4918)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCa ller.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).getConnectionTyp e(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;
}
}