1

In my application i'm trying to download PDF file from server and storing it in SD card, but when i try to download, the download always failed and the logcat says no handler found. i need help to solve this problem, please help me. thank you

downloadText.java

package mobile.download;

import java.io.*;
import java.net.*;
import java.util.regex.Pattern;

import mobile.config.Kondownload;

import com.karismaelearning.R;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.text.util.Linkify;
import android.util.Log;
import android.widget.TextView;

public class DownloadText extends Activity{
    public Kondownload linkurl;
    String url;
    String SERVER_URL;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
setContentView(R.layout.linkdownload);

        TextView mTextLink = (TextView) findViewById(R.id.LinkDownload);
        Bundle bundle = this.getIntent().getExtras();

        String param1 = bundle.getString("keyIdc");
        String param2 = bundle.getString("keyReference");
        linkurl = new Kondownload(this);
        SERVER_URL = linkurl.getUrl();
        SERVER_URL += "/moodledata/"+param1+"/"+param2;

        URLConnection urlConnection = null;

        try{

            URL url = new URL(SERVER_URL);

            //Opening connection of currrent url

            urlConnection = url.openConnection();
            urlConnection.connect();

            //int lenghtOfFile = urlConnection.getContentLength();


        String PATH = Environment.getExternalStorageDirectory() + "/pdf/";

        File file = new File(PATH);
        file.mkdirs();
        File outputFile = new File(file, param2);
        FileOutputStream fos = new FileOutputStream(outputFile);

        InputStream is = url.openStream();


        byte[] buffer = new byte[1024];

        int len1 = 0;

        while ((len1 = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len1);
        }

        fos.close();
        is.close();

         System.out.println("--pdf downloaded--ok--"+SERVER_URL);

        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();

        }

        mTextLink.setText(SERVER_URL);
        Pattern pattern = Pattern.compile(SERVER_URL);

       Linkify.addLinks(mTextLink, pattern, "");

    }
}

logcat

06-06 13:18:13.371: W/System.err(1056): java.io.FileNotFoundException: /mnt/sdcard/pdf/Dokumen/Dogmatika_1.pdf (No such file or directory)
06-06 13:18:13.371: W/System.err(1056):     at org.apache.harmony.luni.platform.OSFileSystem.open(Native Method)
06-06 13:18:13.391: W/System.err(1056):     at dalvik.system.BlockGuard$WrappedFileSystem.open(BlockGuard.java:232)
06-06 13:18:13.391: W/System.err(1056):     at java.io.FileOutputStream.<init>(FileOutputStream.java:94)
06-06 13:18:13.402: W/System.err(1056):     at java.io.FileOutputStream.<init>(FileOutputStream.java:66)
06-06 13:18:13.402: W/System.err(1056):     at mobile.download.DownloadText.onCreate(DownloadText.java:85)
06-06 13:18:13.402: W/System.err(1056):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-06 13:18:13.402: W/System.err(1056):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
06-06 13:18:13.402: W/System.err(1056):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
06-06 13:18:13.402: W/System.err(1056):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-06 13:18:13.402: W/System.err(1056):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
06-06 13:18:13.402: W/System.err(1056):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-06 13:18:13.402: W/System.err(1056):     at android.os.Looper.loop(Looper.java:123)
06-06 13:18:13.402: W/System.err(1056):     at android.app.ActivityThread.main(ActivityThread.java:3683)
06-06 13:18:13.402: W/System.err(1056):     at java.lang.reflect.Method.invokeNative(Native Method)
06-06 13:18:13.411: W/System.err(1056):     at java.lang.reflect.Method.invoke(Method.java:507)
06-06 13:18:13.411: W/System.err(1056):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-06 13:18:13.411: W/System.err(1056):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-06 13:18:13.411: W/System.err(1056):     at dalvik.system.NativeStart.main(Native Method)
06-06 13:18:13.861: I/ActivityManager(61): Displayed com.karismaelearning/mobile.download.DownloadText: +649ms
06-06 13:18:15.101: I/ActivityManager(61): Starting: Intent { act=android.intent.action.VIEW dat=http://10.0.2.2/moodledata/2/Dokumen/Dogmatika_1.pdf cmp=com.android.browser/.BrowserActivity (has extras) } from pid 1056
06-06 13:18:15.831: I/ActivityManager(61): Displayed com.android.browser/.BrowserActivity: +675ms
06-06 13:18:17.271: W/InputManagerService(61): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy@40554818 (uid=10020 pid=378)
06-06 13:18:17.781: D/webviewglue(378): nativeDestroy view: 0x3e4820
06-06 13:18:18.541: I/DownloadManager(218): Initiating request for download 22
06-06 13:18:19.281: W/DownloadManager(218): Aborting request for download 22: no handler found for this download type
blackneko
  • 91
  • 1
  • 12
  • That looks like the wrong portion of the `LogCat`, or the wrong portion of code. Furthermore, you are using a network connection in the UI thread, which will give you an error (by default) on Android 4.0+. Finally, this question [discusses a number of ways of launching a PDF that might relate to your problem](http://stackoverflow.com/q/5113435/1270789). – Ken Y-N Jun 06 '13 at 03:56
  • @KenY-N, i want to download the pdf file, but always failed and the logcat say no handler. i think my codes have some mistakes, can you help me to solve this problem? thank you – blackneko Jun 06 '13 at 04:06
  • @blackneko: i ll saggest you to use this way: http://stackoverflow.com/a/16294388/1168654 – Dhaval Parmar Jun 06 '13 at 05:10
  • @DhawalSodha, thank you Dhawal for looked and answer my question. i want to ask for this part, `.setDestinationInExternalPublicDir("/dhaval_files", "test.jpg");`, what the test.jpg is for? – blackneko Jun 06 '13 at 05:22
  • you have to add your url & image name. like http://xbmc.org/wp-content/uploads/2012/12/zappy_android.jpg here zappy_android.jpg is my image name – Dhaval Parmar Jun 06 '13 at 05:46
  • @DhawalSodha, so in my case I type like this ? `.setDestinationInExternalPublicDir("/PDF", param2);` – blackneko Jun 06 '13 at 05:52
  • @DhawalSodha, I got confused with the codes, because i use linkify in my code `mTextLink.setText(SERVER_URL); Pattern pattern = Pattern.compile(SERVER_URL); Linkify.addLinks(mTextLink, pattern, "");` where i must put this code if i use download manager @_@ – blackneko Jun 06 '13 at 05:58
  • i have add code below read Properly and use one of them. http://stackoverflow.com/a/16955090/1168654 – Dhaval Parmar Jun 06 '13 at 06:27

2 Answers2

1

check below code: its work in >= 9 Android API.

public void file_download(String uRl) {

        //uRl = ;
        File direct = new File(Environment.getExternalStorageDirectory()
                + "/dhaval_files");

        if (!direct.exists()) {
            direct.mkdirs();
        }

        DownloadManager mgr = (DownloadManager) this
                .getSystemService(Context.DOWNLOAD_SERVICE);

        Uri downloadUri = Uri.parse(uRl);
        DownloadManager.Request request = new DownloadManager.Request(
                downloadUri);

        request.setAllowedNetworkTypes(
                DownloadManager.Request.NETWORK_WIFI
                        | DownloadManager.Request.NETWORK_MOBILE)
                .setAllowedOverRoaming(false).setTitle("Demo")
                .setDescription("Something useful. No, really.")
                .setDestinationInExternalPublicDir("/dhaval_files", "lecture3.pdf");

        mgr.enqueue(request);

    }

call above method using: file_download("http://moss.csc.ncsu.edu/~mueller/g1/lecture3.pdf");


For < 9 Android API use this way:

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockActivity;

public class MainActivity extends Activity {

    ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setTheme(R.style.Theme_Sherlock_Light);
        setContentView(R.layout.activity_main);

        mProgressDialog = new ProgressDialog(MainActivity.this);
        mProgressDialog.setMessage("A message");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        // execute this when the downloader must be fired
        DownloadFile downloadFile = new DownloadFile();
        downloadFile
                .execute("http://moss.csc.ncsu.edu/~mueller/g1/lecture3.pdf");
    }

    private class DownloadFile extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... sUrl) {
            try {
                URL url = new URL(sUrl[0]);
                URLConnection connection = url.openConnection();
                connection.connect();
                // this will be useful so that you can show a typical 0-100%
                // progress bar
                int fileLength = connection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream("/sdcard/lecture3.pdf");

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            mProgressDialog.setProgress(progress[0]);
        }

    }
}

both code is working it download PDF file.

Here is Best Answer

Community
  • 1
  • 1
Dhaval Parmar
  • 18,812
  • 8
  • 82
  • 177
  • i understand for this part `Uri downloadUri = Uri.parse(uRl);` i change it become my url like this `Uri downloadUri = Uri.parse(SERVER_URL);`, is it right? or not?. but i don't understand for this part `File direct = new File(Environment.getExternalStorageDirectory() + "/dhaval_files");` and this part `.setDestinationInExternalPublicDir("/dhaval_files", "lecture3.pdf");` . the `"/dhaval_files"` is it the destination folder for the downloaded file? – blackneko Jun 06 '13 at 06:40
  • it success :D! thank you, Dhawal! i want to ask again, so the user must create manually first? O.o when they don't have the folder, the file can't be downloaded? – blackneko Jun 06 '13 at 06:54
  • its depend on our need. Basically we can't ask user to where save file just tell him we have save file at "sdcard/yourappname/test.pdf" or whatever you want. so, if folder is not exist then we create folder programmatically. like: 'File direct = new File(Environment.getExternalStorageDirectory() + "/dhaval_files");' this line check folder is exist or not. if not then we create folder using 'direct.mkdirs();'. if you want to ask user where he want to store file then you have to take folder name from user and do same Process. – Dhaval Parmar Jun 06 '13 at 07:04
  • and yes if folder is not found(you have not create folder before download) then it give you error destination path not found. – Dhaval Parmar Jun 06 '13 at 07:06
  • Dhawal, may I ask again? in moodle e-learning I can share the video link, so the user can see the link like this `http://10.0.2.2/moodledata/2/http://youtu.be/W6RN...` but when i try to click this link through emulator it get forbidden 403, why is that? thank you – blackneko Jun 06 '13 at 10:32
  • [link]http://10.0.2.2/moodledata/2/http://youtu.be/W6RNJ6HDTpU . this is the link the client will see on the phone, and when they click it,i want it will open on youtube or browser but get access is forbidden and error 403 when i click it on the emulator. why this is happen? thank you – blackneko Jun 06 '13 at 11:06
  • its not working because you have two url: first: http://10.0.2.2/moodledata/2 and second: http://youtu.be/W6RNJ6HDTpU so, you have to redirect on http://youtu.be/W6RNJ6HDTpU URL insted of both. – Dhaval Parmar Jun 06 '13 at 11:48
  • owh so it is like that, thank you hehe.. oh i wanna ask too, i use linkify to show the link, but how to put the linkify on download manager? because the file can be downloaded when i click item on listview but when i click the linkify it is not working. thank you – blackneko Jun 06 '13 at 12:45
  • Dhawal, can you help me with my another question? [link]http://stackoverflow.com/questions/17015821/unable-connect-to-server-from-application-on-device . In this question i have problem i can't connect with server through my application, please help me. thank you very much – blackneko Jun 10 '13 at 01:32
0

Try this out

var win = Ti.UI.createWindow({
navBarHidden: true,
backgroundColor: 'blue'
});
win.open();

var button = Ti.UI.createButton({
title: 'Get PDF',
height: 50,
width: 200,
top: 20
});
win.add(button);
button.addEventListener('click', function(e) {
var xhr = Ti.Network.createHTTPClient();
xhr.onload = function() {
    var f =    Ti.Filesystem.getFile(Titanium.Filesystem.externalStorageDirectory,"test.pdf");
    f.write(this.responseData);
    var intent = Ti.Android.createIntent({
        action : Ti.Android.ACTION_VIEW,
        type : 'application/pdf',
        data : f.getNativePath()
    });
    Ti.Android.currentActivity.startActivity(intent);
};

xhr.open("GET", "http://www.appcelerator.com/assets/The_iPad_App_Wave.pdf");
xhr.send();
});

Or try this out

public void downloadPdfContent(String urlToDownload){

URLConnection urlConnection = null;

try{

    URL url = new URL(urlToDownload);

    //Opening connection of currrent url

    urlConnection = url.openConnection();
    urlConnection.connect();

    //int lenghtOfFile = urlConnection.getContentLength();


String PATH = Environment.getExternalStorageDirectory() + "/1/";

File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "test.pdf");
FileOutputStream fos = new FileOutputStream(outputFile);

InputStream is = url.openStream();


byte[] buffer = new byte[1024];

int len1 = 0;

while ((len1 = is.read(buffer)) != -1) {
    fos.write(buffer, 0, len1);
}

fos.close();
is.close();

 System.out.println("--pdf downloaded--ok--"+urlToDownload);

}catch (Exception e) {
    // TODO: handle exception
    e.printStackTrace();

}

}
Droid
  • 419
  • 4
  • 15
  • Chinmai, where i must put this code? if I use this code inside public void OnCreate it has red mark and say : void is an invalid type for the variable downloadPdfContent. sorry, I'm newbie in Android so please help me. thank you – blackneko Jun 06 '13 at 05:07
  • the second one downloadPdfContent is a different function. Then call this function as per your needs – Droid Jun 06 '13 at 05:20
  • I tried to use the second code and type it after `SERVER_URL += ...`, start from `URLConn` until `catch`, and after `catch` i don't erase `mTextLink.setText(SERVER_URL);` but why the error still the same? what is the mistake? – blackneko Jun 06 '13 at 05:44
  • chinmai, can you guide me what i must change from my code, please? i tried to change several codes but still the download unsuccessful. thank you – blackneko Jun 06 '13 at 06:06
  • I edited my new codes and logcat, so you can see what error that i have. i think the cause of error because i don't understand what i must change in several codes. thank you – blackneko Jun 06 '13 at 06:21