Search code examples
androidnetworkonmainthread

Why there is NetworkOnMainThreadException on my activity?


I have an activity which downloads a file and I'm getting an NetworkOnMainThreadException on onPostExecute() after a while I execute the activity. Also the file is not completely downloaded. I can't find where I'm wrong. Here is my code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_activity1);

    RetrieveFeedTask download = new RetrieveFeedTask();
    download.execute();
}

class RetrieveFeedTask extends AsyncTask<String, Void, InputStream> {

    private Exception exception;

    protected InputStream doInBackground(String... urls) {
        try {
             OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                  .url(URL)
                  .build();

              Response response = client.newCall(request).execute();
              InputStream asd = response.body().byteStream();
              System.out.println(asd + " vaslisiss");
                          return asd;
        } catch (Exception e) {
            System.out.println("helloooo");
            this.exception = e;;
            return null;
        }
    }

    protected void onPostExecute(InputStream feed) {
        Log.e("mactibiti", "exception", exception); 
        // TODO: do something with the feed
        if(exception == null)
            System.out.println("asdasdasdasdasdasdads");
        try{
        File file = new File(Environment.getExternalStorageDirectory() + "/downloaded_file.xml");
        FileOutputStream fileOutput = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ( (bufferLength = feed.read(buffer)) > 0 ) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        //close the output stream when complete //
        fileOutput.close();
        feed.close();
        }
        catch(Exception e){
            Log.e("filex", "ioexc", e);
        }

    }
}}

Solution

  • protected void onPostExecute(InputStream feed) {
    

    feed is the InputStream you are reading from the Http call