0

im trying to save a remote web file (.html) inside my sdcard, so i can read it later or manipulate it, but the application crash in the start

public class MainActivity extends ActionBarActivity {

    private WebView mWebView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        WebView webview = new WebView(this);
        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        setContentView(webview);
        webview.setWebViewClient(new WebViewClient());
        webview.loadUrl("file:///android_asset/paginas/index.html");
        //This LoadURL it load properly if i comment the img.DownloadFromURL, something is wrong there =/, if downloadfromurl is not commented, it crash!
        String url = "http://empregocerto.uol.com.br/info/vagas_por_area.html";

        ImageManager img = new ImageManager();
        img.DownloadFromUrl(url, "index.txt");

        //its ImageManager coz in the example the guy was downloading image, but i want all the html code in a file at my cellphone

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    public class ImageManager {

        private final String PATH = "/data/data/com.helloandroid.downloader/";  //put the downloaded file here


        public void DownloadFromUrl(String imageURL, String fileName) {  //this is the downloader method
                try {
                        URL url = new URL(imageURL); //you can write here any link
                        File file = new File(fileName);

                        long startTime = System.currentTimeMillis();
                        Log.d("ImageManager", "download begining");
                        Log.d("ImageManager", "download url:" + url);
                        Log.d("ImageManager", "downloaded file name:" + fileName);
                        /* Open a connection to that URL. */
                        URLConnection ucon = url.openConnection();

                        /*
                         * Define InputStreams to read from the URLConnection.
                         */
                        InputStream is = ucon.getInputStream();
                        BufferedInputStream bis = new BufferedInputStream(is);

                        /*
                         * Read bytes to the Buffer until there is nothing more to read(-1).
                         */
                        ByteArrayBuffer baf = new ByteArrayBuffer(50);
                        int current = 0;
                        while ((current = bis.read()) != -1) {
                                baf.append((byte) current);
                        }

                        /* Convert the Bytes read to a String. */
                        FileOutputStream fos = new FileOutputStream(file);
                        fos.write(baf.toByteArray());
                        fos.close();
                        Log.d("ImageManager", "download ready in"
                                        + ((System.currentTimeMillis() - startTime) / 1000)
                                        + " sec");

                } catch (IOException e) {
                        Log.d("ImageManager", "Error: " + e);
                }

        }
}
    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);
    }


    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            return rootView;
        }
    }

}

LOG CAT ERROR:

04-02 14:33:24.660: V/WebViewChromium(1370): Binding Chromium to the main looper Looper (main, tid 1) {b3d8e1c8} 04-02 14:33:24.680: I/chromium(1370): [INFO:library_loader_hooks.cc(112)] Chromium logging enabled: level = 0, default verbosity = 0 04-02 14:33:24.700: I/BrowserProcessMain(1370): Initializing chromium process, renderers=0 04-02 14:33:24.790: D/(1370): HostConnection::get() New Host Connection established 0xb7df38f8, tid 1370 04-02 14:33:24.800: W/chromium(1370): [WARNING:proxy_service.cc(888)] PAC support disabled because there is no system implementation 04-02 14:33:24.980: D/dalvikvm(1370): GC_FOR_ALLOC freed 86K, 6% free 2889K/3060K, paused 42ms, total 43ms 04-02 14:33:24.980: I/dalvikvm-heap(1370): Grow heap (frag case) to 3.508MB for 635812-byte allocation 04-02 14:33:25.040: D/dalvikvm(1370): GC_FOR_ALLOC freed <1K, 5% free 3510K/3684K, paused 50ms, total 50ms 04-02 14:33:25.350: D/dalvikvm(1370): GC_FOR_ALLOC freed 13K, 3% free 3953K/4060K, paused 21ms, total 22ms 04-02 14:33:25.560: D/ImageManager(1370): download begining 04-02 14:33:25.560: D/ImageManager(1370): download url:http://empregocerto.uol.com.br/info/vagas_por_area.html 04-02 14:33:25.560: D/ImageManager(1370): downloaded file name:index.txt

//there is no file index.txt saved

04-02 14:33:25.750: D/dalvikvm(1370): GC_FOR_ALLOC freed 81K, 4% free 4382K/4548K, paused 23ms, total 24ms 04-02 14:33:25.810: D/AndroidRuntime(1370): Shutting down VM 04-02 14:33:25.810: W/dalvikvm(1370): threadid=1: thread exiting with uncaught exception (group=0xb3accba8) 04-02 14:33:25.830: E/AndroidRuntime(1370): FATAL EXCEPTION: main 04-02 14:33:25.830: E/AndroidRuntime(1370): Process: com.example.helloworld, PID: 1370 04-02 14:33:25.830: E/AndroidRuntime(1370): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helloworld/com.example.helloworld.MainActivity}: android.os.NetworkOnMainThreadException 04-02 14:33:25.830: E/AndroidRuntime(1370): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 04-02 14:33:25.830: E/AndroidRuntime(1370): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 04-02 14:33:25.830: E/AndroidRuntime(1370): at android.app.ActivityThread.access$800(ActivityThread.java:135) 04-02 14:33:25.830: E/AndroidRuntime(1370): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 04-02 14:33:25.830: E/AndroidRuntime(1370): at android.os.Handler.dispatchMessage(Handler.java:102) 04-02 14:33:25.830: E/AndroidRuntime(1370): at android.os.Looper.loop(Looper.java:136) 04-02 14:33:25.830: E/AndroidRuntime(1370): at android.app.ActivityThread.main(ActivityThread.java:5017) 04-02 14:33:25.830: E/AndroidRuntime(1370): at java.lang.reflect.Method.invokeNative(Native Method) 04-02 14:33:25.830: E/AndroidRuntime(1370): at java.lang.reflect.Method.invoke(Method.java:515) 04-02 14:33:25.830: E/AndroidRuntime(1370): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 04-02 14:33:25.830: E/AndroidRuntime(1370): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 04-02 14:33:25.830: E/AndroidRuntime(1370): at dalvik.system.NativeStart.main(Native Method) 04-02 14:33:25.830: E/AndroidRuntime(1370): Caused by: android.os.NetworkOnMainThreadException 04-02 14:33:25.830: E/AndroidRuntime(1370): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145) 04-02 14:33:25.830: E/AndroidRuntime(1370): at java.net.InetAddress.lookupHostByName(InetAddress.java:385) 04-02 14:33:25.830: E/AndroidRuntime(1370): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 04-02 14:33:25.830: E/AndroidRuntime(1370): at java.net.InetAddress.getAllByName(InetAddress.java:214) 04-02 14:33:25.830: E/AndroidRuntime(1370): at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28) 04-02 14:33:25.830: E/AndroidRuntime(1370): at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216) 04-02 14:33:25.830: E/AndroidRuntime(1370): at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122) 04-02 14:33:25.830: E/AndroidRuntime(1370): at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292) 04-02 14:33:25.830: E/AndroidRuntime(1370): at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255) 04-02 14:33:25.830: E/AndroidRuntime(1370): at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206) 04-02 14:33:25.830: E/AndroidRuntime(1370): at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345) 04-02 14:33:25.830: E/AndroidRuntime(1370): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296) 04-02 14:33:25.830: E/AndroidRuntime(1370): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179) 04-02 14:33:25.830: E/AndroidRuntime(1370): at com.example.helloworld.MainActivity$ImageManager.DownloadFromUrl(MainActivity.java:87) 04-02 14:33:25.830: E/AndroidRuntime(1370): at com.example.helloworld.MainActivity.onCreate(MainActivity.java:54) 04-02 14:33:25.830: E/AndroidRuntime(1370): at android.app.Activity.performCreate(Activity.java:5231) 04-02 14:33:25.830: E/AndroidRuntime(1370): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 04-02 14:33:25.830: E/AndroidRuntime(1370): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 04-02 14:33:25.830: E/AndroidRuntime(1370): ... 11 more 04-02 14:33:30.280: I/Process(1370): Sending signal. PID: 1370 SIG: 9

user3284660
  • 59
  • 1
  • 2
  • 11

1 Answers1

0

The error you are getting is android.os.NetworkOnMainThreadException. This means that you cannot run network type operations on the main UI thread. In your case, you are trying to retrieve web content over the network.

Therefore, img.DownloadFromUrl(url, "index.txt"); must either be called in an AsyncTask or run in a separate thread.

Please refer to this for a complete stackoverflow question and answers on this error.

Community
  • 1
  • 1
singularhum
  • 5,072
  • 2
  • 24
  • 32