Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to download file in android?

I'm trying to download a file from a URL. I have the following code.

package com.example.downloadfile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

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

public class DownloadFile extends Activity {

     private static String fileName = "al.jpg";

     @Override
     public void onCreate(Bundle savedInstanceState) 
     {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = new TextView(this);
        tv.setText("This is download file program... ");

        try {
            //this is the file you want to download from the remote server
            String path ="http://www.fullissue.com/wp-content/uploads/2010/12/Adam-Lambert.jpg";
            //this is the name of the local file you will create

            String targetFileName = "al.jpg";

            boolean eof = false;

            URL u = new URL(path);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            String PATH_op = Environment.getExternalStorageDirectory() + "/download/" + targetFileName;

            tv.append("\nPath > " + PATH_op);

            FileOutputStream f = new FileOutputStream(new File(PATH_op));

            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 (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (ProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }

        tv.append("\nAnother append!");
        this.setContentView(tv);
    }

}

Can someone tell me what's wrong with this code. I'm not able to see the file I'm supposed to download. I'm new to java and android dev, many thanks for any help. :)

like image 326
Kris Avatar asked May 04 '11 10:05

Kris


People also ask

Where is my download file in Android?

You can find downloads on Android in My Files or File Manager. You can find these apps in the app drawer of your Android device. Within My Files or File Manager, navigate to the Downloads folder to find everything you downloaded.

Why can't I download files on my Android phone?

Go to Settings > Storage and check the Android's total and available storage space. If you are running low, try uninstalling any apps, videos, pictures, or other media. This is definitely a possibility you are unable to download any attachments, apps, and picks, and why the usual tricks aren't working.


2 Answers

  1. You are doing network I/O on the main application thread. At best, this will freeze your UI while the download is going on. At worst, you activity will crash with an "Application Not Responding" (ANR) dialog.

  2. You are trying to write to a directory (download/) on external storage that might not exist. Please create the directory first.

  3. Please consider switching to using Log.e() for your error logging, as I do not know if printStackTrace() works on Android.

Also, make sure that you have the WRITE_EXTERNAL_STORAGE permission and that you are using adb logcat, DDMS, or the DDMS perspective in Eclipse to examine LogCat and look for the error messages you are trying to log.

like image 200
CommonsWare Avatar answered Sep 19 '22 10:09

CommonsWare


firstly, you should add permissions to AndroidManifest.xml:

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

Secondly, add this code, so that if the folder doesn't exist, it checks and creates the folder:

File root = android.os.Environment.getExternalStorageDirectory();               

           File dir = new File (root.getAbsolutePath() + "/download");
           if(!dir.exists()) {
                dir.mkdirs();
           }

Thirdly, as Commons Ware said, downloading on the main thread is not a good practice; you should implement it on a new thread; because while downloading, the main thread is busy for downloading the file. If the waiting time be more than expected the system will generate "Not responding" error.

In order to do that you can use "TaskAsync" or "IntentService" or even making a new thread.

As you said you are new to java, I suggest using "TaskAsync", as it is very straightforward and easy.

like image 27
Saman Abdolmohammadpour Avatar answered Sep 18 '22 10:09

Saman Abdolmohammadpour