2015-03-02 9 views
-1
protected void doDownload(final String urlLink, final String fileName) { 
     Thread dx = new Thread() { 

       public void run() { 

       File root = android.os.Environment.getExternalStorageDirectory();    
       File dir = new File (root.getAbsolutePath() + "/Content2/"); 
       if(dir.exists()==false) { 

         dir.mkdirs(); 
        } 
       //Save the path as a string value 

       try 
       { 
         URL url = new URL(urlLink); 
         Log.i("FILE_NAME", "File name is "+imageFile); 
         Log.i("FILE_URLLINK", "File URL is "+url); 
         URLConnection connection = url.openConnection(); 
         connection.connect(); 
         // this will be useful so that you can show a typical 0-100% progress bar 
         int fileLength = connection.getContentLength(); 

         // download the file 
         InputStream input = new BufferedInputStream(url.openStream()); 
         OutputStream output = new FileOutputStream(dir+"/"+imageFile); 

         byte data[] = new byte[1024]; 
         long total = 0; 
         int count; 
         while ((count = input.read(data)) != -1) { 
          total += count; 

          output.write(data, 0, count); 
         } 

         output.flush(); 
         output.close(); 
         input.close(); 
        } 
       catch (Exception e) 
       { 
        e.printStackTrace(); 
        Log.i("ERROR ON DOWNLOADING FILES", "ERROR IS" +e); 
        } 
      } 
     }; 

     dx.start();  
    } 

через это, я не могу загрузить файл с сервера.Как загрузить файл базы данных sqlite с сервера в Android?

Как решить эту проблему?

+0

это даст вам ошибку? напишите подробнее о своей проблеме ... –

+0

Добавили ли вы запись внешнего хранилища и разрешение на доступ в интернет к файлу манифеста? – IshRoid

+0

См. Эту ссылку: http://stackoverflow.com/questions/9499849/synchronise-update-sqlite-databases –

ответ

0

Прежде всего, вы должны использовать Async-Task.

Вот как вы можете это сделать

final DownloadTask downloadTask = new DownloadTask(YourActivity.this); 
downloadTask.execute("the url to the file you want to download"); 

// usually, subclasses of AsyncTask are declared inside the activity class. 
// that way, you can easily modify the UI thread from here 
private class DownloadTask extends AsyncTask<String, Integer, String> { 

    private Context context; 

    public DownloadTask(Context context) { 
     this.context = context; 
    } 

    @Override 
    protected String doInBackground(String... sUrl) { 
     InputStream input = null; 
     OutputStream output = null; 
     HttpURLConnection connection = null; 
     try { 
      URL url = new URL(sUrl[0]); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.connect(); 

      // expect HTTP 200 OK, so we don't mistakenly save error report 
      // instead of the file 
      if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { 
       return "Server returned HTTP " + connection.getResponseCode() 
         + " " + connection.getResponseMessage(); 
      } 

      // this will be useful to display download percentage 
      // might be -1: server did not report the length 
      int fileLength = connection.getContentLength(); 

      // download the file 
      input = connection.getInputStream(); 
      output = new FileOutputStream("/sdcard/file_name.extension"); 

      byte data[] = new byte[4096]; 
      long total = 0; 
      int count; 
      while ((count = input.read(data)) != -1) { 
       // allow canceling with back button 
       if (isCancelled()) { 
        input.close(); 
        return null; 
       } 
       total += count; 
      } 
     } catch (Exception e) { 
      return e.toString(); 
     } finally { 
      try { 
       if (output != null) 
        output.close(); 
       if (input != null) 
        input.close(); 
      } catch (IOException ignored) { 
      } 

      if (connection != null) 
       connection.disconnect(); 
     } 
     return null; 
    } 

@Override 
    protected void onPostExecute(String result) { 
     if (result != null) 
      Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show(); 
     else 
      Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show(); 
    } 
Смежные вопросы