You cannot use DownloadManager to download directly to your app's portion of internal storage. You will need to use OkHttp or some other in-process HTTP client API.

Answer from CommonsWare on Stack Overflow
🌐
The Code City
thecodecity.com › home › android › download pdf from any url in android studio – solution
Download PDF From Any URL in Android Studio – Solution
May 13, 2023 - You can use this function on the download button’s onclick and the pdf file will be downloaded and saved to internal storage.
🌐
Talkerscode
talkerscode.com › howto › android-download-file-from-url-and-save-to-internal-storage.php
Android Download File From URL And Save To Internal Storage
Name your new project InternalStorageDemo when you create it. To add the following code, open res -> layout -> activity main.xml (or) main.xml. In this step, we enter MainActivity and add the save and next functions that were defined over the button onclick. The save function takes the information from edittext and stores it within a file in byte format.
🌐
Stack Overflow
stackoverflow.com › questions › 10378895 › download-doc-pdf-from-the-internet-and-save-to-internal-memory
android - Download Doc/PDF from the internet and save to internal memory - Stack Overflow
And why do you insist on internal memory? Why can't you save those files to the external storage and use them from there? If you still want to use internal storage follow the guidelines here: developer.android.com/guide/topics/data/…
🌐
Stack Overflow
stackoverflow.com › questions › 58864154 › how-do-i-copy-a-pdf-into-my-internal-storage-android-studio
How do I copy a PDF into my internal storage? -Android studio - Stack Overflow
I would like to copy the pdf from the download folder into my app (internal storage). Problem is that the method throws a NullPointerExeption. File source = new File("/storage/emulated/0/Download/test1.pdf"); File dest = new File("/data/user/0/com.example.meinuniverwalter/files/Gson"); try{ copyFileUsingStream(source,dest); }catch(IOException e){ e.printStackTrace(); } private static void copyFileUsingStream(File source, File dest) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(source); os = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } finally { is.close(); os.close(); } }
🌐
GitHub
github.com › ajithvgiri › PDF-Downloader
GitHub - ajithvgiri/PDF-Downloader: Example app to download pdf from url and saved into your internal storage
Example app to download pdf from url and saved into your internal storage - ajithvgiri/PDF-Downloader
Starred by 30 users
Forked by 12 users
Languages   Java 100.0% | Java 100.0%
Top answer
1 of 2
1

For download you have to use async task.

like in this example I am downloading mutliple file it can be PDF, Image etc

class DownloadFileAsync(paths: Array<String?>, listener: AsyncResponse?, size: Int) : AsyncTask<String, String, Array<String?>>() {
    private val listener: AsyncResponse? = listener
    var current = 0
    var paths: Array<String?>
    val downPaths = arrayOfNulls<String>(size)

    lateinit var fpath: String
    var show = false


    init {
        this.paths = paths
    }


    protected override fun onPreExecute() {
        super.onPreExecute()
    }

    protected override fun doInBackground(vararg aurl: String): Array<String?> {
        val rows = aurl.size
        while (current < rows) {
            var count: Int
            try {
                println("Current: " + current + "\t\tRows: " + rows)
                fpath = getFileName(this.paths[current]!!)
                val url = URL(this.paths[current])
                val conexion = url.openConnection()
                conexion.connect()
                val lenghtOfFile = conexion.getContentLength()
                val input = BufferedInputStream(url.openStream(), 512)
                val file = File(Environment.getExternalStorageDirectory().path.plus(File.separator).plus(fpath))
                downPaths.set(current, file.absolutePath)
                if (!file.exists()) file.createNewFile()
                val output = FileOutputStream(file)
                val data = ByteArray(512)
                var total: Long = 0
                while (true) {
                    count = input.read(data)
                    if (count == -1) break
                    total += count
                    output.write(data, 0, count)
                }


                show = true
                output.flush()
                output.close()
                input.close()
                current++
            } catch (e: Exception) {
                Log.d("Exception", "" + e)
            }
        } // while end
        onPostExecute(downPaths)
        return downPaths
    }

    override fun onProgressUpdate(progress: Array<String?>) {

    }

    override fun onPostExecute(result: Array<String?>) {
        listener?.processFinish(result)
    }

    private fun getFileName(wholePath: String): String {
        var name: String? = null
        val start: Int
        val end: Int
        start = wholePath.lastIndexOf('/')
        end = wholePath.length //lastIndexOf('.');
        name = wholePath.substring((start + 1), end)
        return name
    }
}

After that I am geting the call back of file path via interface listener?.processFinish(result)

2 of 2
-1

Note: Maybe I should use comment section for this, but my reputation is still low so...

I try running your code, the only thing missing is on the download function. It should be:

 val destinationInExternalPublicDir = request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, nameOfFile)
🌐
Stack Overflow
stackoverflow.com › questions › 47998478 › saving-a-pdf-to-internal-storage
android - Saving a Pdf to internal storage - Stack Overflow
December 28, 2017 - StorageRef.child(adapterView.getItemAtPosition(i)+".pdf"); try { getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE); progressBar.setVisibility(View.VISIBLE); final File localFile = File.createTempFile("filename","pdf"); StorageRef.getFile(localFile).addOnCompleteListener(new OnCompleteListener<FileDownloadTask.TaskSnapshot>() { @Override public void onComplete(@NonNull Task<FileDownloadTask.TaskSnapshot> task) { Toast.makeText(ShowActivity.this, "Download Successful", Toast.LENGTH_SHORT).show(); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE); progressBar.setVisibility(View.GONE); } }); }catch (Exception e){ System.out.println(e); }
🌐
Kodemetrics
kodemetrics.com › home › android download file from url and save
android download file from url and save - Kodemetrics
March 18, 2021 - In this tutorial we will learn how to download a pdf file from a url and save to local storage and also as read the pdf with the default android reader.
Find elsewhere
🌐
YouTube
youtube.com › watch
How to Download Pdf and save into Downloads folder and ...
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
Codeplayon
codeplayon.com › home › android tutorial › how to download pdf from url in android code example
How to Download PDF from URL in Android Code Example – Codeplayon
January 17, 2020 - <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.codeplayon.pdf.download.example"> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.READ_PHONE_STATE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Top answer
1 of 4
2

The possible reason is the folder in which you want to does not exist. First check if it exist. Create it if not. Then create fileoutputstream and write to it.

2 of 4
1

I suggest you use the DownloadManager. There are too many problems that can arise during download to handle all of them yourself. Just think of temporary loss of connectivity in the middle of download... Below is some code I pulled out of my app and slightly modified to get rid of parts you don't need.

public void downloadAndOpenPdf(String url,final File file) {
    if(!file.isFile()) {
        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request req = new DownloadManager.Request(Uri.parse(url));
        req.setDestinationUri(Uri.fromFile(file));
        req.setTitle("Some title");

        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                unregisterReceiver(this);
                if (file.exists()) {
                    openPdfDocument(file);
                }
            }
        };
        registerReceiver(receiver, new IntentFilter(
                DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        dm.enqueue(req);
        Toast.makeText(this, "Download started", Toast.LENGTH_SHORT).show();
    }
    else {
        openPdfDocument(file);
    }
}

public boolean openPdfDocument(File file) {
    Intent target = new Intent(Intent.ACTION_VIEW);
    target.setDataAndType(Uri.fromFile(file), "application/pdf");
    target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    try {
        startActivity(target);
        return true;
    } catch (ActivityNotFoundException e) {
        Toast.makeText(this,"No PDF reader found",Toast.LENGTH_LONG).show();
        return false;
    }

}
🌐
DocHub
dochub.com › en › functionalities › download-pdf-from-link-in-android
Download PDF from link in Android easily | DocHub
When prompted, choose where you want to save the file. How to download PDFs from links using the Web to PDF tool Go to the HTML to PDF tool. Paste the URL you want to download as a PDF. Adjust the tool settings to your requirements. Click Convert to PDF.
Top answer
1 of 1
17

Please take a look at this link.

It Contains an example of your requirement. Below there is a summary of the information in the link.

First step declaring persmissions in AndroidManifest.xml

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

Create a downloader class

public class Downloader {

    public static void DownloadFile(String fileURL, File directory) {
        try {

            FileOutputStream f = new FileOutputStream(directory);
            URL u = new URL(fileURL);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            InputStream in = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = in.read(buffer)) > 0) {
                f.write(buffer, 0, len1);
            }
            f.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Finally creating an activity which downloads the PDF file from internet,

public class PDFFromServerActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String extStorageDirectory = Environment.getExternalStorageDirectory()
        .toString();
        File folder = new File(extStorageDirectory, "pdf");
        folder.mkdir();
        File file = new File(folder, "Read.pdf");
        try {
            file.createNewFile();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Downloader.DownloadFile("http://www.nmu.ac.in/ejournals/aspx/courselist.pdf", file);

        showPdf();
    }
    public void showPdf()
        {
            File file = new File(Environment.getExternalStorageDirectory()+"/pdf/Read.pdf");
            PackageManager packageManager = getPackageManager();
            Intent testIntent = new Intent(Intent.ACTION_VIEW);
            testIntent.setType("application/pdf");
            List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/pdf");
            startActivity(intent);
        }
}
🌐
Oodlestechnologies
oodlestechnologies.com › blogs › Downloading-and-Retrieving-Files-on-SD-card-in-Android-using-Android-SDK-in-Eclipse
Downloading and Retrieving Files on SD card in Android using Android SDK in Eclipse
February 14, 2020 - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "sample.pdf"); It's a public directory. 6. Now, Lastly, define the below two permissions in your AndroidManifest.xml file: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"> <uses-permission android:name="android.permission.INTERNET"> 7. Now, Either create Emulator with SD card or test it on device. After giving proper download URL and Clicking on "Download File" button, downloading will start and you can see the progress in Notification bar like screenshot below.
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 1483471 › how-to-download-pdf-in-app-internal-storage-by-usi
How to download pdf in app/internal storage by using url and then show it in webview in .net maui - Microsoft Q&A
January 8, 2024 - <WebView x:Name="web_view" WidthRequest="300" HeightRequest="500" Source="https://learn.microsoft.com/dotnet/maui" /> <Button Text="download pdf" Clicked="Button_Clicked"/> private async void Button_Clicked(object sender, EventArgs e) { string path; using (var http = new HttpClient()) { var stream = await http.GetStreamAsync("https://www.africau.edu/images/default/sample.pdf"); path = Path.Combine(FileSystem.AppDataDirectory, "sample.pdf"); using Stream streamToWriteTo = File.Open(path, FileMode.Create); await stream.CopyToAsync(streamToWriteTo); } if (File.Exists(path)) { #if ANDROID Android.Net.Uri uri = Android.Net.Uri.FromFile(new Java.IO.File(path)); string pdfFilePath = string.Format("file:///android_asset/web/viewer.html?file={0}", uri); web_view.Source = new UrlWebViewSource { Url = pdfFilePath }; #endif } }
🌐
Stack Overflow
stackoverflow.com › questions › 50502717 › how-to-save-and-share-pdf-file-that-was-downloaded-using-url-and-save-to-cache › 50578986
android - How to save and share pdf file, that was downloaded using url and save to cache folder of app - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Using the below set of code, I am trying to get the pdf file using the URL and then I need to share the file via mail or save it to the device storage.