Android-访问Http客户端时出现Android.os.NetworkOnMainThreadException

Android-访问Http客户端时出现Android.os.NetworkOnMainThreadException,android,web-services,http,thread-exceptions,Android,Web Services,Http,Thread Exceptions,可能重复: 当我运行我的android应用程序时,我得到了android.os.NetworkOnMainThreadException,原因是什么。我如何修复它。这是我的代码 public class Login extends Activity { private Button btnLogin; private EditText txtusername; private EditText txtPassword; public String username; public Strin

可能重复:

当我运行我的android应用程序时,我得到了android.os.NetworkOnMainThreadException,原因是什么。我如何修复它。这是我的代码

public class Login extends Activity {

private Button btnLogin;
private EditText txtusername;
private EditText txtPassword;
public String username;
public String password;
public boolean doLogin = false;
Intent intent;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.login);


    btnLogin = (Button) findViewById(R.id.btnLogin);
    txtusername = (EditText) findViewById(R.id.txtuserName);
    txtPassword = (EditText) findViewById(R.id.txtPassword);
    btnLogin.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {

            username = txtusername.getText().toString();
            password = txtPassword.getText().toString();

            if (username.equals("") || password.equals("")) {

                AlertDialog alert = new AlertDialog.Builder(Login.this)
                        .create();
                alert.setMessage("Username or Password can not be Empty");
                alert.setButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                            }
                        });

                alert.setIcon(R.drawable.loginlogo);
                alert.show();

            }

            else {

                HttpAsync httpasync = new HttpAsync();

                httpasync.execute(new String[] { "http://www.diskonbanget.com/bni/login/login.php" });

            }

        }

    });

}

private class HttpAsync extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String str = null;
        try {

            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://www.diskonbanget.com/bni/login/login.php");
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                    2);
            nameValuePairs
                    .add(new BasicNameValuePair("username", username));
            nameValuePairs
                    .add(new BasicNameValuePair("password", password));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request

            HttpResponse response = httpclient.execute(httppost);

            str = inputStreamToString(response.getEntity().getContent())
                    .toString();

        } catch (Exception e) {
            return str;
        }
        return str;
    }

    @Override
    protected void onPostExecute(String result) {
        String str = result;

        if (str.toString().equalsIgnoreCase("false")) {

            AlertDialog alert = new AlertDialog.Builder(Login.this)
                    .create();
            alert.setMessage("Please enter valid username & Password");
            alert.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            });

            alert.setIcon(R.drawable.loginlogo);
            alert.show();

        }

        else if (str.toString().equalsIgnoreCase("null")) {
            AlertDialog alert = new AlertDialog.Builder(Login.this)
                    .create();
            alert.setMessage("Can not Connect to the server.please make sure your internet is Switch on  ");
            alert.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            alert.setIcon(R.drawable.loginlogo);
            alert.show();
        }

        else {

            intent = new Intent(Login.this, MainMenu.class);
            intent.putExtra("photo", str);
            intent.putExtra("username", str);   
            getApplicationContext().startActivity(intent);

        }

    }

}

private StringBuilder inputStreamToString(InputStream is) {
    String line = "";
    StringBuilder total = new StringBuilder();
    // Wrap a BufferedReader around the InputStream
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    // Read response until the end
    try {
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
        return total;

    } catch (Exception e) {

        return null;
    }

}
公共类登录扩展活动{
私人按钮;
私有编辑文本txtusername;
私有编辑文本txtPassword;
公共字符串用户名;
公共字符串密码;
公共布尔值doLogin=false;
意图;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(窗口。功能\u无\u标题);
setContentView(R.layout.login);
btnLogin=(按钮)findViewById(R.id.btnLogin);
txtusername=(EditText)findViewById(R.id.txtusername);
txtPassword=(EditText)findViewById(R.id.txtPassword);
setOnClickListener(新的OnClickListener(){
公共void onClick(视图arg0){
username=txtusername.getText().toString();
password=txtPassword.getText().toString();
if(username.equals(“”)| | password.equals(“”){
AlertDialog alert=新建AlertDialog.Builder(Login.this)
.create();
alert.setMessage(“用户名或密码不能为空”);
alert.setButton(“确定”,
新建DialogInterface.OnClickListener(){
公共void onClick(对话框接口对话框,
int(其中){
}
});
alert.setIcon(R.drawable.loginlogo);
alert.show();
}
否则{
HttpAsync HttpAsync=新的HttpAsync();
httpasync.execute(新字符串[]{”http://www.diskonbanget.com/bni/login/login.php" });
}
}
});
}
私有类HttpAsync扩展异步任务{
@凌驾
受保护的字符串doInBackground(字符串…参数){
字符串str=null;
试一试{
//创建一个新的HttpClient和Post头
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(
"http://www.diskonbanget.com/bni/login/login.php");
List name valuepairs=new ArrayList(
2);
nameValuePairs
.添加(新的BasicNameValuePair(“用户名”,用户名));
nameValuePairs
.add(新的BasicNameValuePair(“密码”,password));
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
//执行HTTP Post请求
HttpResponse response=httpclient.execute(httppost);
str=inputStreamToString(response.getEntity().getContent())
.toString();
}捕获(例外e){
返回str;
}
返回str;
}
@凌驾
受保护的void onPostExecute(字符串结果){
字符串str=结果;
if(str.toString().equalsIgnoreCase(“false”)){
AlertDialog alert=新建AlertDialog.Builder(Login.this)
.create();
alert.setMessage(“请输入有效的用户名和密码”);
alert.setButton(“确定”,新建DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
}
});
alert.setIcon(R.drawable.loginlogo);
alert.show();
}
else if(str.toString().equalsIgnoreCase(“null”)){
AlertDialog alert=新建AlertDialog.Builder(Login.this)
.create();
alert.setMessage(“无法连接到服务器。请确保您的internet已打开”);
alert.setButton(“确定”,新建DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
}
});
alert.setIcon(R.drawable.loginlogo);
alert.show();
}
否则{
intent=新的intent(Login.this,main menu.class);
意图。额外(“照片”,str);
intent.putExtra(“用户名”,str);
getApplicationContext().startActivity(intent);
}
}
}
私有StringBuilder inputStreamToString(InputStream为){
字符串行=”;
StringBuilder总计=新StringBuilder();
//在InputStream周围包装一个BufferedReader
BufferedReader rd=新的BufferedReader(新的InputStreamReader(is));
//读取响应直到结束
试一试{
而((line=rd.readLine())!=null){
合计.追加(行);
}
返回总数;
}捕获(例外e){
返回null;
}
}

请有人帮帮我。android版本3.2,尝试使用XOOM2 emulator运行

原因是您的登录方法在ui线程中建立了http连接,您应该在单独的线程中或使用

您可以将上下文传递给任务,然后:

protected void onPostExecute(Void result) {
   Intent showContent = new Intent(context, yourActivity.class);
   context.startActivity(showContent);
}

原因是您的登录方法在ui线程中建立http连接,您应该在单独的线程中或使用

您可以将上下文传递给任务,然后:

protected void onPostExecute(Void result) {
   Intent showContent = new Intent(context, yourActivity.class);
   context.startActivity(showContent);
}

虽然我不建议您这样做,但您可以将其用于测试。有关良好实践,请参阅@imran khan。
将其添加到onCreate()方法中以绕过检查

if( Build.VERSION.SDK_INT >= 9){
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

    StrictMode.setThreadPolicy(policy); 
}

虽然我不建议您这样做,但您可以将其用于测试。有关良好实践,请参阅@imran khan。
将其添加到onCreate()方法中以绕过检查

if( Build.VERSION.SDK_INT >= 9){
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

    StrictMode.setThreadPolicy(policy); 
}

我用过这个。它很好用。如果我用这个方法有什么问题吗?我已经在市场上的应用程序上用过了。这个方法没有问题,只是不喜欢使用主线程从互联网加载数据,谷歌不久前添加了StrictMode。从网络获取数据的一个好方法是使用异步Task或服务,因此您不必担心