ama989
ama989

Reputation: 463

How to download a file on a click

how are you doing ? I am making a application, in the application I want to click a listView and my application starts to download a link. I already have the link. I used the following code but, my application crashes:

Here is the listener to handle my clicks:

mListViewMagazine.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            DownloadFromUrl(mMagazine_title[position]);


        }
    });

The DownloadFromUrl function is as the following:

public void DownloadFromUrl( String fileName) {  //this is the downloader method
    try {
        URL url = new URL("http://themwl.org/web/sites/default/files/584_0.pdf");
                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);
    }

}

The Error message:

 06-19 22:32:01.585  12336-12336/alahdal.amjad.mwlapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: alahdal.amjad.mwlapplication, PID: 12336
android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
        at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
        at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
        at java.net.InetAddress.getAllByName(InetAddress.java:215)
        at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
        at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
        at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
        at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
        at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
        at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
        at alahdal.amjad.mwlapplication.PublicationsFragment.DownloadFromUrl(PublicationsFragment.java:98)
        at alahdal.amjad.mwlapplication.PublicationsFragment$1.onItemClick(PublicationsFragment.java:75)
        at android.widget.AdapterView.performItemClick(AdapterView.java:300)
        at android.widget.AbsListView.performItemClick(AbsListView.java:1143)
        at android.widget.AbsListView$PerformClick.run(AbsListView.java:3044)
        at android.widget.AbsListView$3.run(AbsListView.java:3833)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Upvotes: 1

Views: 123

Answers (2)

Bennik2000
Bennik2000

Reputation: 1162

Because you did not provide an error message I think that you forgot to add

<uses-permission android:name="android.permission.INTERNET" />

to your AndroidManifest.xml
Please add an error message :)

------------- Update -------------

This happens when you access the internet (network) on the MainUIThread. Simply run your network things on a seperate thread

I would do it like this:

mListViewMagazine.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        AsyncTask thread = new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] params) {
                DownloadFromUrl(mMagazine_title[position]);
                return "Finish";
            }
        };
        thread.execute("");
    }
});

Upvotes: 1

ama989
ama989

Reputation: 463

This is the solution:

            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(files_url[position]));
            request.setTitle("File Downloading");
            request.setDescription("File is being Downloaded...");
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
            String File_name = URLUtil.guessFileName(files_url[position],null, MimeTypeMap.getFileExtensionFromUrl(files_url[position]));
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,File_name)  ;
            DownloadManager manager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
            manager.enqueue(request);
            Toast.makeText(getActivity(),"Downloading",Toast.LENGTH_LONG).show();

Upvotes: 1

Related Questions