2016-04-30 3 views
0

У меня есть таблица Sqlite, в которой хранятся 3 файла, и когда я хочу их читать из таблицы, он отлично работает, но когда я хочу загрузить на сервер, он просто загружает последнюю 3 раза. Я не знаю, что не так с моим кодом, пожалуйста, дайте мне решение этой проблемы. оценить благодаряЗагрузка файла на сервер в Android - загрузка последнего

Это как я называю из Активность:

List<MediaFiles> mediaFiles = mfh.getAllFiles(); 
     for (MediaFiles mf : mediaFiles) { 
      filePath = mf.getFile(); 
      lat = Double.parseDouble(mf.getGeolat()); 
      longi = Double.parseDouble(mf.getGeolng()); 
      String log = "Id: " + mf.getId() + " ,File: " + mf.getFile() + " ,latitued: " + mf.getGeolat() + " ,longitued: " + mf.getGeolng(); 
      Log.d("File Table Row: ", log); 
      new UploadFileToServerMain().execute(); 
     } 

И это класс Uploader:

private class UploadFileToServerMain extends AsyncTask<Void, Integer, String> { 
    @Override 
    protected void onPreExecute() { 
     // setting progress bar to zero 
     //progressBar.setProgress(0); 
     super.onPreExecute(); 
    } 

    @Override 
    protected void onProgressUpdate(Integer... progress) { 

    } 

    @Override 
    protected String doInBackground(Void... params) { 
     return uploadFile(); 
    } 

    @SuppressWarnings("deprecation") 
    private String uploadFile() { 

     String responseString = null; 

     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(global.getURL()+"fileUpload.php"); 

     try { 
      AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
        new AndroidMultiPartEntity.ProgressListener() { 

         @Override 
         public void transferred(long num) { 
          publishProgress((int) ((num/(float) totalSize) * 100)); 
         } 
        }); 

      File sourceFile = new File(filePath); 

      // Adding file data to http body 
      entity.addPart("latitued", new StringBody(lat+"")); 
      entity.addPart("longitued", new StringBody(longi+"")); 
      entity.addPart("image", new FileBody(sourceFile)); 
      entity.addPart("token",new StringBody(global.getMyToken())); 

      totalSize = entity.getContentLength(); 
      httppost.setEntity(entity); 

      // Making server call 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity r_entity = response.getEntity(); 

      int statusCode = response.getStatusLine().getStatusCode(); 
      if (statusCode == 200) { 
       // Server response 
       responseString = EntityUtils.toString(r_entity); 
      } else { 
       responseString = "Error occurred! Http Status Code: " 
         + statusCode; 
      } 

     } catch (ClientProtocolException e) { 
      responseString = e.toString(); 
     } catch (IOException e) { 
      responseString = e.toString(); 
     } 

     return responseString; 

    } 

    @Override 
    protected void onPostExecute(String result) { 
     Log.e(TAG, "Response from server: " + result); 
     // showing the server response in an alert dialog 
     //showAlert(result); 
     super.onPostExecute(result); 
    } 

} 

Logcat: enter image description here

+0

Где делает AsyncTask получить переменную Filepath из? Прямо сейчас вы просматриваете все три файла, но сохраняете только последний путь к файлу в переменной filePath. Поэтому, когда вы запускаете AsyncTasks, они будут использовать только тот же файл. Попробуйте отладить там или зайти, чтобы узнать, правда ли это. Редактировать: Если это файл, это то же самое, вы должны отправить в FilePath в AsyncTask в качестве параметра и использовать его там. –

+0

FilePath определен в верхней части моей активности –

+0

Как передать filePath как параметр в UploadFileToServerMain? –

ответ

0

Наконец я получил решение (Передача параметра в класс AsyncTask.)

List<MediaFiles> mediaFiles = mfh.getAllFiles(); 
    for (MediaFiles mf : mediaFiles) { 
     lat = Double.parseDouble(mf.getGeolat()); 
     longi = Double.parseDouble(mf.getGeolng()); 
     String log = "Id: " + mf.getId() + " ,File: " + mf.getFile() + " ,latitued: " + mf.getGeolat() + " ,longitued: " + mf.getGeolng(); 
     Log.d("File Table Row: ", log); 
     new UploadFileToServerMain(mf.getFile()).execute(); 
    } 

Создание конструктора загрузчиком класса

private class UploadFileToServerMain extends AsyncTask<Void, Integer, String> { 

private String path = null; 
public UploadFileToServerMain(String path){ 
     this.path = path; 
} 

@SuppressWarnings("deprecation") 
private String uploadFile() { 

    String responseString = null; 

    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost(global.getURL()+"fileUpload.php"); 

    try { 
     AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
       new AndroidMultiPartEntity.ProgressListener() { 

        @Override 
        public void transferred(long num) { 
         publishProgress((int) ((num/(float) totalSize) * 100)); 
        } 
       }); 

     File sourceFile = new File(path); 

     // Adding file data to http body 
     entity.addPart("latitued", new StringBody(lat+"")); 
     entity.addPart("longitued", new StringBody(longi+"")); 
     entity.addPart("image", new FileBody(sourceFile)); 
     entity.addPart("token",new StringBody(global.getMyToken())); 

     totalSize = entity.getContentLength(); 
     httppost.setEntity(entity); 

     // Making server call 
     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity r_entity = response.getEntity(); 

     int statusCode = response.getStatusLine().getStatusCode(); 
     if (statusCode == 200) { 
      // Server response 
      responseString = EntityUtils.toString(r_entity); 
     } else { 
      responseString = "Error occurred! Http Status Code: " 
        + statusCode; 
     } 

    } catch (ClientProtocolException e) { 
     responseString = e.toString(); 
    } catch (IOException e) { 
     responseString = e.toString(); 
    } 

    return responseString; 

} 

} 
Смежные вопросы