Error- android.os.NetworkOnMainThreadException

时间:2013-10-09 19:21:02

标签: android

当我尝试连接到php文件以访问数据库时,应用程序崩溃并且try和catch打印此错误NetworkOnMainThreadException但此方法运行良好。

        boolean login(String username, String password){

    String servicePath = "http://localhost/student.php";

    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(servicePath);
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("username",username));
        nameValuePairs.add(new BasicNameValuePair("password",password));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = httpclient.execute(httpPost,responseHandler);
        if(response.equalsIgnoreCase("found")) return true;
        }
    catch(Exception ex)
    {
        ex.printStackTrace();
        Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();
    }
    return false;
}

2 个答案:

答案 0 :(得分:0)

Exception一样,您正在尝试在主Thread上进行网络通话。尝试使用AsyncTask或开始新的Thread

答案 1 :(得分:0)

刚刚使用线程执行任何网络操作..