2015-12-23 2 views
0

В моем приложении для Android у меня есть кнопка, которая загружает файл с сервера. Я попытался удалить файл с сервера, но когда я нажимаю кнопку, приложение загружает файл. Это код:Android не загружает правильный файл

private class DownloadTask extends AsyncTask<String, Integer, String> 
{ 

    private Context context; 
    private PowerManager.WakeLock mWakeLock; 

    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/LabTracKin/analisi"); 

      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; 
       // publishing the progress.... 
       if (fileLength > 0) // only if total length is known 
        publishProgress((int) (total * 100/fileLength)); 
       output.write(data, 0, 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 onPreExecute() { 
     super.onPreExecute(); 
     // take CPU lock to prevent CPU from going off if the user 
     // presses the power button during download 
     PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); 
     mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 
       getClass().getName()); 
     mWakeLock.acquire(); 
     mProgressDialog.show(); 
    } 

    @Override 
    protected void onProgressUpdate(Integer... progress) { 
     super.onProgressUpdate(progress); 
     // if we get here, length is known, now set indeterminate to false 
     mProgressDialog.setIndeterminate(false); 
     mProgressDialog.setMax(100); 
     mProgressDialog.setProgress(progress[0]); 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     mWakeLock.release(); 
     mProgressDialog.dismiss(); 
     if (result != null) 
      Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show(); 
     else 
      Toast.makeText(context,"File Scaricato", Toast.LENGTH_SHORT).show(); 
    } 
} 

Я думал, что это может быть проблема с кэшированием, то я добавил этот код, чтобы очистить кэш

Clear Application cache on exit in android

Но проблема остается.

+0

проверки длины содержимого (что вы в конечном итоге запись в файл) в обоих случаях. вероятно, что-то еще записывается в файл, когда он его не находит. также проверьте размер файла в каждом случае. они точно соответствуют? – AndroidMechanic

+0

Размер файла изменяется, теперь я удаляю файл на сервере, но могу загрузить старый файл. Я не знаю, почему он не отображает сообщение об ошибке – chianta

+0

, тогда вы не будете правильно проверять, доступен ли файл на сервере или нет, и записывать что-то еще в файл, когда он недоступен. Проверьте содержимое в обоих случаях и включите их в свой вопрос, если это возможно. – AndroidMechanic

ответ

0

Я нашел проблему! Проблема заключалась в выполнении задачи, она создала много потоков.

Я изменил

downloadTask.execute(params) 

в

downloadTask.executeOnExecutor(Executors.newSingleThreadExecutor(), params) 
Смежные вопросы