Android code after httpclient.execute(httpget) doesn't get run in try (using AsyncTask)

后端 未结 2 1159
野趣味
野趣味 2021-01-21 03:16

I\'m trying to get data from a website and parse it into my android application. Unfortunately I don\'t even get to the part of parsing the data. The code doesn\'t run after the

2条回答
  •  [愿得一人]
    2021-01-21 03:30

    Alike Dale Wilson said, you can't update UI in doInBackground method. Prefer onPreExecute and onPostExecute methods.

    You can also update your message TextView with the result of your doInBackground like that :

    private class getinternetData extends AsyncTask{
    
        @Override
        protected String doInBackground(String... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet("http://www.google.com");
            try{
                //message.setText("333");
                HttpResponse response = httpclient.execute(httpget);
                //message.setText("444");
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                if(statusCode == 200){
                    return "Could connect";
                }else
                    return "Couldn't connect";
            }catch(Exception e){
                return e.toString();
            }
    
            return null;
        }
    
        @Override
        protected void onPostExecute(String result) {
            if (result != null)
                message.setText(result);
        }   
    }
    

提交回复
热议问题