将文件从我的数据库下载到特定位置

时间:2018-06-18 10:51:20

标签: android download

我编写了一个android应用程序,它将数据从mysql数据库加载到应用程序中的listview,一切正常。

1。我想要的是什么:

来自我的服务器的元素是音频文件的网址,我希望用户通过单击相应列表视图的元素来下载这些文件。现在我不能这样做。

2.我尝试

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String[] url = GetJson.url;
            Uri uri = Uri.parse(url[i]);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    });

当我点击列表视图中的某个项目时,我得到了这个:

image

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:0)

首先你应该下载mp3文件,然后需要在SD卡上创建文件夹,然后将文件存储在那里。

请看一下这段代码:

步骤1)创建下载方法。

public String Download(String Url)
 {
  String filepath=null;
  try {
   //set the download URL, a url that points to a file on the internet
   //this is the file to be downloaded
   URL url = new URL(Url);
   //create the new connection
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

   //set up some things on the connection
   urlConnection.setRequestMethod("GET");
   urlConnection.setDoOutput(true); 
    //and connect!
   urlConnection.connect();
   //set the path where we want to save the file
   //in this case, going to save it on the root directory of the
   //sd card.
   File SDCardRoot = Environment.getExternalStorageDirectory();
   //create a new file, specifying the path, and the filename
   //which we want to save the file as.

   String filename= "downloadedFile.png";   // you can download to any type of file ex:.jpeg (image) ,.txt(text file),.mp3 (audio file)
   Log.i("Local filename:",""+filename);
   file = new File(SDCardRoot,filename);
   if(file.createNewFile())
   {
    file.createNewFile();
   }

   //this will be used to write the downloaded data into the file we created
   FileOutputStream fileOutput = new FileOutputStream(file);

   //this will be used in reading the data from the internet
   InputStream inputStream = urlConnection.getInputStream();

   //this is the total size of the file
   int totalSize = urlConnection.getContentLength();
   //variable to store total downloaded bytes
   int downloadedSize = 0;

   //create a buffer...
   byte[] buffer = new byte[1024];
   int bufferLength = 0; //used to store a temporary size of the buffer

   //now, read through the input buffer and write the contents to the file
   while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
    //add the data in the buffer to the file in the file output stream (the file on the sd card
    fileOutput.write(buffer, 0, bufferLength);
    //add up the size so we know how much is downloaded
    downloadedSize += bufferLength;
    //this is where you would do something to report the prgress, like this maybe
    Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;

   }
   //close the output stream when done
   fileOutput.close();
   if(downloadedSize==totalSize)   filepath=file.getPath();

  //catch some possible errors...
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   filepath=null;
   e.printStackTrace();
  }
  Log.i("filepath:"," "+filepath) ;

  return filepath;

 }

REF - http://androidsnips.blogspot.com/2010/08/download-from-internet-and-save-to-sd.html

请使用Asynctask进行baground操作。

答案 1 :(得分:0)

String url=GetJson.url[i];//your audiofile url came from server
    int fsize;
    /*create a directory to store your files. declare it globally so that it will be accessible from any class in app*/
    File directory = new File((getExternalFilesDir(null)!=null?getExternalFilesDir(null):getFilesDir().getPath()) +"/"+ getPackageName()+"/dirName/");
    if (!directory.exists()) {
        directory.mkdirs();
    }
    File file = new File(directory, "fileName");
    if(file.exists() && file.length()==0){
        file.delete();
    }
    if(!file.exists()){
        try
        {
            URL ur=new URL(url);
            fsize=ur.openConnection().getContentLength();
            DataInputStream dis = new DataInputStream(ur.openStream());

            byte[] buffer = new byte[2048];//as par requirement
            int length;

            DataOutputStream fos = new DataOutputStream(new FileOutputStream(file));
            while ((length = dis.read(buffer))>0) {
                fos.write(buffer, 0, length);
            }

            fos.flush();
            dis.close();
            fos.close();
            if(file.length()<fsize){
                if(file.exists())
                    file.delete();
            }
        }
        catch (Exception e){}
    }
相关问题