-1

I'm making a simply android app. Now I've made a activity where it loads information from the web and use the information to set a listview. If run the app it works fine, but if I open the activity (which I described above) he gives the error: android.os.NetworkOnMainThreadException

activity file:

package com.a3gaatleren;

import android.support.v7.app.ActionBarActivity;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.a3gaatleren.ReadFile;

public class Agenda extends ActionBarActivity {


        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_agenda);

                doInBackground();

        }



        protected void doInBackground(){
                try {
                        ListView mainListView ;  
                        // Find the ListView resource.     
                        mainListView = (ListView) findViewById( R.id.listView2);
                        String file_name =  "http://3gaatleren.16mb.com/appagenda/agenda.html";

                        // Create and populate a List of planet names.
                        ReadFile file = new ReadFile(file_name);

                        String[] huiswerk = file.OpenFile();
                        ArrayList<String> huiswerklist = new ArrayList<String>();  
                        huiswerklist.addAll( Arrays.asList(huiswerk) );  

                        // Create ArrayAdapter using the planet list. 
                        ArrayAdapter<String> listAdapter;
                        listAdapter = new ArrayAdapter<String>(Agenda.this, R.layout.simplerow, huiswerklist);  

                        // Set the ArrayAdapter as the ListView's adapter.  
                mainListView.setAdapter( listAdapter ); 

                        }catch(MalformedURLException e){
                                System.out.println(e);

                        }catch(IOException f){
                                System.out.println(f);
                        }

        }





        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.agenda, menu);
                return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
                // Handle action bar item clicks here. The action bar will
                // automatically handle clicks on the Home/Up button, so long
                // as you specify a parent activity in AndroidManifest.xml.
                int id = item.getItemId();
                if (id == R.id.action_settings) {
                        return true;
                }
                return super.onOptionsItemSelected(item);
        }

}

java file where I define the readfile function:

package com.a3gaatleren;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Scanner;

import org.jsoup.Jsoup;

import java.io.FileReader;
import java.io.BufferedReader;

public class ReadFile {

        private String path;

        public ReadFile (String file_path){
                path= file_path;
        }


        public String[] OpenFile() throws IOException{

                URL url = new URL(path);
                BufferedReader textReader = new BufferedReader(new InputStreamReader(url.openStream()));
                int numberOfLines=readLines();
                String[] textData = new String[numberOfLines];

                int i;

                for (i=0; i< numberOfLines; i++){
                        String html = textReader.readLine();
                        org.jsoup.nodes.Document doc;
                        doc = Jsoup.parse(html, "utf-8");
                        String text = doc.body().text();

                        textData[i] =text;
                }

                textReader.close();
                return textData;

        }

        int readLines() throws IOException{
                URL file_to_read = new URL(path);
                BufferedReader bf = new BufferedReader(new InputStreamReader(file_to_read.openStream()));

                int numberOfLines = 0;

                String str;

                while ((str = bf.readLine()) != null){
                        numberOfLines++;

                }
                bf.close();

                return numberOfLines;


        }

}

Can someone tell me what's the problem?

PS: English is not my first language, I don't know if it's correct English

Luuk Verhagen
  • 350
  • 1
  • 5
  • 13
  • You're reading a file from the network. You are not allowed to do this on the main thread (it will block the UI). See the 1000+ other questions on this site about `NetworkOnMainThreadException` for a method to solve it. – Glorfindel Aug 16 '15 at 16:57
  • I think you will need to use AsyncTask with a new thread to fix your problem. As Glorfindel has suggested, search on stackoverflow about it... – Hussein El Feky Aug 16 '15 at 17:04

1 Answers1

0

Basically the UI thread is the part of you app that processes what's shown on screen and let's the user use it. If things don't respond when the user tries something then at best the user thinks the app is slow and at worst the user thinks the app has crashed and Android is bad, which we don't want.

To get around that we can do anything that takes a long time or a lot of processing power on another thread. The easiest way to do that is with an AsyncTask.

new AsyncTask<Void, Void, Void>() {

    public void doInBackground(Void... params,) {
        //do your loading here
        return null;
    }

    public void onPostExecute(Void result) {
        //update your ui here when loading finishes
    }

}.execute();

The above is absolute bare bones but should help you solve your problem

Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124