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

后端 未结 2 1158
野趣味
野趣味 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:27

    One problem you have is you are attempting to update the screen (message) from a background thread. Use AsyncTask.publishProgress(...) to let the main thread update the GUI in its onProgressUpdate() method.

    Also rather than updating the screen, consider writing log messages Log.d(TAG, "You Are Here.); and watching them in logcat.

    This doesn't address the HTTP issue, but clear this up first to be sure you are not causing a hang by changing the screen in a background thread.

    0 讨论(0)
  • 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<String, Void, String>{
    
        @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);
        }   
    }
    
    0 讨论(0)
提交回复
热议问题