سؤال

    public String urltobody(String createdurl){ 
            URL url = new URL (createdurl); 
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            int responseCode = connection.getResponseCode();//fails here
            if (responseCode == HttpURLConnection.HTTP_OK) { 
                InputStream is = connection.getInputStream();
                String content = convertInputStream(is, "UTF-8"); 
                is.close();
                return content;
            }
    }

The above function works if I call it inside of doInBackground but does not workin onPostExecute. I really need to call this function independent to pre, background, post prdocedure.

This is my class definition private class FetchTask extends AsyncTask < Void, Void, String>

Please let me know if you can help me with one of the below questions.

Do you know how I can call my function outside of doInbackground?

Do you know what happens when I call new FetchTask().execute()?

Any other solution?

Thank you in advance

هل كانت مفيدة؟

المحلول

The reason is that doInBackground is run in a background thread while onPreExectute onPostExecute are run in the UI-thread.

==> Url Connections should not be done from UI thread, (because it may freeze the UI while it is loading) that is why Android throws an NetworkOnMainThreadException whenever you try to do that.

==> This is the reason why you should establish network connections only asynchronously from the background thread not UI thread. That is why it only works in doInBackground.

نصائح أخرى

You can try this code

private class FetchTask extends AsyncTask<Void, Void, Boolean>

instead of

private class FetchTask extenends AsyncTask < Void, Void, String>

May be solve your problem.

also for example for your understanding

private class ResponseLocDepts extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected Boolean doInBackground(Void... params) {
                URL url = new URL (createdurl); 
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        int responseCode = connection.getResponseCode();//fails here
        if (responseCode == HttpURLConnection.HTTP_OK) { 
            InputStream is = connection.getInputStream();
            String content = convertInputStream(is, "UTF-8"); 
            is.close();
            return true;
        }
       else
        {
         return false;
         }

        }

        @Override
        protected void onPostExecute(final Boolean success) {
                // somethings

        }

    }

String content should be globally diclare. Please try it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top