Skip to content Skip to sidebar Skip to footer

Got Error When Try To Download Pdf File

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

Solution 1:

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

publicvoidfile_download(String uRl) {

        //uRl = ;Filedirect=newFile(Environment.getExternalStorageDirectory()
                + "/dhaval_files");

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

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

        UridownloadUri= Uri.parse(uRl);
        DownloadManager.Requestrequest=newDownloadManager.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;

publicclassMainActivityextendsActivity {

    ProgressDialog mProgressDialog;

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

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

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

    privateclassDownloadFileextendsAsyncTask<String, Integer, String> {
        @Overrideprotected String doInBackground(String... sUrl) {
            try {
                URLurl=newURL(sUrl[0]);
                URLConnectionconnection= url.openConnection();
                connection.connect();
                // this will be useful so that you can show a typical 0-100%// progress barintfileLength= connection.getContentLength();

                // download the fileInputStreaminput=newBufferedInputStream(url.openStream());
                OutputStreamoutput=newFileOutputStream("/sdcard/lecture3.pdf");

                byte data[] = newbyte[1024];
                longtotal=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) {
            }
            returnnull;
        }

        @OverrideprotectedvoidonPreExecute() {
            super.onPreExecute();
            mProgressDialog.show();
        }

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

    }
}

both code is working it download PDF file.

Here is Best Answer

Solution 2:

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

publicvoiddownloadPdfContent(String urlToDownload){

URLConnectionurlConnection=null;

try{

    URLurl=newURL(urlToDownload);

    //Opening connection of currrent url

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

    //int lenghtOfFile = urlConnection.getContentLength();StringPATH= Environment.getExternalStorageDirectory() + "/1/";

Filefile=newFile(PATH);
file.mkdirs();
FileoutputFile=newFile(file, "test.pdf");
FileOutputStreamfos=newFileOutputStream(outputFile);

InputStreamis= url.openStream();


byte[] buffer = newbyte[1024];

intlen1=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();

}

}

Post a Comment for "Got Error When Try To Download Pdf File"