我知道你不能在主线程中进行网络操作,因为 Android 3.0。所以,我在一个新的内部打了电话Thread
:
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
user=login.getText().toString();
password=pass.getText().toString();
params.add(new BasicNameValuePair("user", user));
params.add(new BasicNameValuePair("pass", password));
Thread thread=new Thread(){
public void run(){
try {
// Throws exception here
response=CustomHttpClient.executeHttpPost(urlogin, params);
response=response.replaceAll("\\s+","");
} catch (Exception e) {
e.printStackTrace();
}
if(response.equals("ok")){
Intent home=new Intent(c, HomeActivity.class);
home.putExtra("username", user);
startActivity(home);
Toast toast=Toast.makeText(
c, getString(R.string.welcome), Toast.LENGTH_LONG);
toast.show();
}else{
if(response.equals("fallo")){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast toast=Toast.makeText(
c, R.string.nologin, Toast.LENGTH_LONG);
toast.show();
login.setText("");
pass.setText("");
}
});
}else if(response.equals("nologin")){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast toast=Toast.makeText(
c, R.string.nouser, Toast.LENGTH_LONG);
toast.show();
login.setText("");
pass.setText("");
}
});
}
}
}
};
thread.run();
}
});
但是,尽管我不在主线程上,但我还是收到了这个异常(或者至少我认为......)