在尝试使用httpclient和打印整数时出现不幸的错误

时间:2013-10-19 21:18:57

标签: android

我无法理解logcat所说的内容,因为我对于android开发并不是很老。 这是logcat。代码在下面..

public class Json extends Activity {

    HttpClient client;
    TextView tvStatus;

    final static String url = "http://localhost/index.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.json);

        tvStatus = (TextView) findViewById(R.id.tvStatus);
        client = new DefaultHttpClient();

        try {
            int data = this.users();
            String Data = String.valueOf(data);
            tvStatus.setText(Data);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public int users() throws ClientProtocolException, IOException
    {
        StringBuilder URL = new StringBuilder(url);
        HttpGet get = new HttpGet(URL.toString());
        HttpResponse r = client.execute(get);

        int status = r.getStatusLine().getStatusCode();
        return status;  
    }
}

试图获取状态并附加到tvStatus。问题和解决方案可能是什么?

1 个答案:

答案 0 :(得分:1)

您收到错误android.os.NetworkOnMainThreadException,这意味着您正尝试在UI线程中执行网络操作,这是不允许的。您必须在单独的线程中执行代码。使用AsyncTask或创建new Thread()并从那里拨打电话。