0

I have created an android application and debug it on a simulator, But it gives me an exception android.os.NetworkOnMainThreadException.

Below is java code which accesses data remotely.

  String filepath = datapath + "/tessdata/eng.traineddata";
       // AssetManager assetManager = getAssets();
        URL url = new URL("http://192.168.2.52/tessdata/eng.traineddata");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("GET");
        connection.connect();
       // assetManager.open("tessdata/eng.traineddata");
        InputStream instream =  connection.getInputStream();
        OutputStream outstream = new FileOutputStream(filepath);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = instream.read(buffer)) != -1) {
            outstream.write(buffer, 0, read);
        }


        outstream.flush();
        outstream.close();
        instream.close();

        File file = new File(filepath);
        if (!file.exists()) {
            throw new FileNotFoundException();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

I added following permission in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
ND1010_
  • 3,743
  • 24
  • 41
dny
  • 67
  • 2
  • 11
  • 1
    This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in `AsyncTask` – Harshad Prajapati Dec 12 '17 at 07:11
  • you must use Async Task for network call :) that solve your problem :) – Subhash Prajapati Dec 12 '17 at 07:11
  • Just a suggestion before you post something in SO just check if the question is already asked. Just search for android.os.NetworkOnMainThreadException in google and you will get 100 s of same questions. – Sunil Sunny Dec 12 '17 at 07:26

0 Answers0