Skip to content Skip to sidebar Skip to footer

Android: Is It Possible To Dowload File To Disk Given An Xml (from A Url)?

I have a URL, for example http://somedomain.com/sync_login/go123/go and it gives an XML, if you're gonna view it in web browser (i use firefox), the output is something like this:

Solution 1:

private Uri downloadFileFromURL(URL url, Context context, String fileName) {
    try {
      URLConnectionconn= url.openConnection();
      HttpURLConnectionhttpConnection= conn instanceof HttpURLConnection ? (HttpURLConnection ) conn  : null;
      if(httpConnection != null) {
        intcontentLength= httpConnection.getContentLength();
        int len, length = 0;
        byte[] buf = newbyte[8192];
        InputStreamis= httpConnection.getInputStream();
        Filefile=newFile(context.getExternalFilesDir(null), fileName);
        OutputStreamos=newFileOutputStream(file);
        try {
          while((len = is.read(buf, 0, buf.length)) > 0) {
            os.write(buf, 0, len);
            length += len;
            publishProgress((int) (PROGRESS_MAX * (float) length / contentLength));
          }
          os.flush();
        }
        finally {
          is.close();
          os.close();
        }
        return Uri.fromFile(file);
      }
    }
    catch(IOException e)
    {
       //Exception handling goes here
    }
    returnnull;
  }

I wrote this method in my AsyncTask class, so I use publishProgress to update progress, you can remove that line. But I suggest you wrote your AsyncTask as well.

Hope it helps :)

And dont forget to add android.permission.INTERNET permission in your android-manifest.xml. I made this stupid mistake serval times :)

Post a Comment for "Android: Is It Possible To Dowload File To Disk Given An Xml (from A Url)?"