Android url.openStream() not working

后端 未结 1 1918
陌清茗
陌清茗 2021-01-16 23:03

I am trying to retrieve data from a website and my app keeps crashing. I have located the issue down to the openStream() command. The class I am using is defined below. I am

相关标签:
1条回答
  • 2021-01-16 23:50

    NetworkOnMainThreadException

    You created your own doInBackground methods, but Internet connection must be only in background, put your code to overrided methods doInbackground! See example below:

    In background implement getting data, in method opPostExecute - settings data to views.

    private class MyAsyncTask extends AsyncTask<Void, Void, Void>{
    
        @Override
        protected Void doInBackground(Void... arg0) {
           URL url = null;
           try {
               url = new URL("URL is in here");
    
               BufferedInputStream bis = new BufferedInputStream(url.openStream());
               byte[] buffer = new byte[1024];
               StringBuilder sb = new StringBuilder();
               int bytesRead = 0;
               while((bytesRead = bis.read(buffer)) > 0) {
                   String text = new String(buffer, 0, bytesRead);
                   sb.append(text);
               }
               bis.close();
    
           } catch (MalformedURLException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
    
           return yourResult;
        }
    }
    

    or

    private class MyAsyncTask extends AsyncTask<Void, Void, Void>{
    
        @Override
        protected Void doInBackground(Void... arg0) {
            doInBackground();   //your methods
            return null;
        }
    
        protected void doInBackground() {
            URL url = null;
            try {
                url = new URL("URL is in here");
    
                BufferedInputStream bis = new BufferedInputStream(url.openStream());
                byte[] buffer = new byte[1024];
                StringBuilder sb = new StringBuilder();
                int bytesRead = 0;
                while((bytesRead = bis.read(buffer)) > 0) {
                   String text = new String(buffer, 0, bytesRead);
                   sb.append(text);
                }
               bis.close();
    
    
           } catch (MalformedURLException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
    
       }
    

    }

    hope, I help you.

    0 讨论(0)
提交回复
热议问题