Yusuf Ali
Yusuf Ali

Reputation: 173

getting unfortunately error when trying to use httpclient and printing integer

I can not understand what logcat say, because I'm not really old for android development. Here is the logcat. Codes are below..

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;  
    }
}

Just trying to get status and appending into tvStatus. What may the problem and solution be?

Upvotes: 0

Views: 25

Answers (1)

Carnal
Carnal

Reputation: 22064

You are getting the error android.os.NetworkOnMainThreadException which means you are trying to execute a network operation in UI Thread, which is not allowed. You will have to execute your code in a separate thread. Either use AsyncTask or create a new Thread() and make the call from there.

Upvotes: 1

Related Questions