0

我无法理解 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。问题和解决方案可能是什么?

4

1 回答 1

1

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

于 2013-10-19T21:32:14.553 回答