2012-10-04 3 views
2

내 SD에서 dropboxfolder로 여러 파일을 업로드하고 싶습니다. 그러나 문제는 보관 용 계정 문제와 관련이 없습니다.android asynctask 보관함에 여러 파일 업로드

파일 배열이 있는데 파일 하나 하나를 모두 업로드하고 싶습니다. 동시에 모두를 업로드하려고합니다.

파일 배열을 통해 for 루프를 수행하므로 업로드가 정상적으로 작동하지만 동시에 수행됩니다.

나는 파일

어떤 제안의 전체 크기와 숫자에 대한해서 ProgressDialog 정보를주고 싶습니다?

덕분에, 내가 myClass가에서 통과

: "toBeUploaded는"파일 배열입니다

Log.i("toBeUploaded", 
           " " + Arrays.toString(toBeUploaded)); 

         for (int i = 0; i < toBeUploaded.length; i++) { 

          Upload upload = new Upload(CalcDBActivity.this, 
            mDBApi, getIntent().getExtras() 
              .getString("project") 
              + File.separatorChar, 
            toBeUploaded[i]); 
          upload.execute(); 

          if (upload.getStatus() == Upload.Status.PENDING) { 
           // My AsyncTask has not started yet 
           Log.i("Status pend", 
             " " + upload.getStatus()); 
          } 

          if (upload.getStatus() == Upload.Status.RUNNING) { 
           // My AsyncTask is currently doing work in 
           // doInBackground() 
           Log.i("Status run ", 
             " " + upload.getStatus()); 
          } 

          if (upload.getStatus() == Upload.Status.FINISHED) { 
           Log.i("Status Finished", 
             " " + upload.getStatus()); 
           // My AsyncTask is done and onPostExecute 
           // was called 
          } 

         } 

.

업로드 클래스 :

public class Upload extends AsyncTask<Void, Long, Boolean> { 

private DropboxAPI<?> mApi; 
private String mPath; 
private File mFile; 

private long mFileLen; 
private UploadRequest mRequest; 
private Context mContext; 
private final ProgressDialog mDialog; 

private String mErrorMsg; 


public Upload(Context context, DropboxAPI<?> api, String dropboxPath, 
     File file) { 
    // We set the context this way so we don't accidentally leak activities 
    mContext = context.getApplicationContext(); 

    mFileLen = file.length(); 
    mApi = api; 
    mPath = dropboxPath; 
    mFile = file; 

    mDialog = new ProgressDialog(context); 
    mDialog.setMax(100); 
    mDialog.setMessage("Uploading " + file.getName()); 
    mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
    mDialog.setProgress(0); 
    mDialog.setButton("Cancel", new OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
      // This will cancel the putFile operation 
      mRequest.abort(); 
     } 
    }); 
    mDialog.show(); 
} 

@Override 
protected Boolean doInBackground(Void... params) { 
    try { 
     // By creating a request, we get a handle to the putFile operation, 
     // so we can cancel it later if we want to 
     FileInputStream fis = new FileInputStream(mFile); 
     String path = mPath + mFile.getName(); 
     mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(), 
       new ProgressListener() { 
      @Override 
      public long progressInterval() { 
       // Update the progress bar every half-second or so 
       return 500; 
      } 

      @Override 
      public void onProgress(long bytes, long total) { 
       publishProgress(bytes); 
      } 
     }); 

     if (mRequest != null) { 
      mRequest.upload(); 
      return true; 
     } 

    } catch (DropboxUnlinkedException e) { 
     // This session wasn't authenticated properly or user unlinked 
     mErrorMsg = "This app wasn't authenticated properly."; 
    } catch (DropboxFileSizeException e) { 
     // File size too big to upload via the API 
     mErrorMsg = "This file is too big to upload"; 
    } catch (DropboxPartialFileException e) { 
     // We canceled the operation 
     mErrorMsg = "Upload canceled"; 
    } catch (DropboxServerException e) { 
     // Server-side exception. These are examples of what could happen, 
     // but we don't do anything special with them here. 
     if (e.error == DropboxServerException._401_UNAUTHORIZED) { 
      // Unauthorized, so we should unlink them. You may want to 
      // automatically log the user out in this case. 
     } else if (e.error == DropboxServerException._403_FORBIDDEN) { 
      // Not allowed to access this 
     } else if (e.error == DropboxServerException._404_NOT_FOUND) { 
      // path not found (or if it was the thumbnail, can't be 
      // thumbnailed) 
     } else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) { 
      // user is over quota 
     } else { 
      // Something else 
     } 
     // This gets the Dropbox error, translated into the user's language 
     mErrorMsg = e.body.userError; 
     if (mErrorMsg == null) { 
      mErrorMsg = e.body.error; 
     } 
    } catch (DropboxIOException e) { 
     // Happens all the time, probably want to retry automatically. 
     mErrorMsg = "Network error. Try again."; 
    } catch (DropboxParseException e) { 
     // Probably due to Dropbox server restarting, should retry 
     mErrorMsg = "Dropbox error. Try again."; 
    } catch (DropboxException e) { 
     // Unknown error 
     mErrorMsg = "Unknown error. Try again."; 
    } catch (FileNotFoundException e) { 
    } 
    return false; 
} 

@Override 
protected void onProgressUpdate(Long... progress) { 
    int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5); 
    mDialog.setProgress(percent); 
} 

@Override 
protected void onPostExecute(Boolean result) { 
    mDialog.dismiss(); 
    if (result) { 
     showToast("Image successfully uploaded"); 
    } else { 
     showToast(mErrorMsg); 
    } 
} 

private void showToast(String msg) { 
    Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG); 
    error.show(); 
} 

}

답변

4

이동합니다 메인 클래스의-for 루프

Log.i("toBeUploaded", " " + Arrays.toString(toBeUploaded)); 

Upload upload = new Upload(CalcDBActivity.this, 
    mDBApi, 
    getIntent().getExtras().getString("project") + File.separatorChar, 
    toBeUploaded); 
upload.execute(); 

업로드 클래스에 :

public class Upload extends AsyncTask<Void, Long, Boolean> { 

    private DropboxAPI<?> mApi; 
    private String mPath; 

    private UploadRequest mRequest; 
    private Context mContext; 
    private ProgressDialog mDialog; 

    private String mErrorMsg; 

    //new class variables: 
    private int mFilesUploaded; 
    private File[] mFilesToUpload; 
    private int mCurrentFileIndex; 

    public Upload(Context context, DropboxAPI<?> api, String dropboxPath, File[] filesToUpload) { 
     // We set the context this way so we don't accidentally leak activities 
     mContext = context.getApplicationContext(); 
     mApi = api; 
     mPath = dropboxPath; 

     //set number of files uploaded to zero. 
     mFilesUploaded = 0; 
     mFilesToUpload = filesToUpload; 
     mCurrentFileIndex = 0; 

     mDialog = new ProgressDialog(context); 
     mDialog.setMax(100); 
     mDialog.setMessage("Uploading file 1/" + filesToUpload.length); 
     mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
     mDialog.setProgress(0); 
     mDialog.setButton("Cancel", new OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       cancel(true); 
      } 
     }); 
     mDialog.show(); 
    } 

    @Override 
    protected Boolean doInBackground(Void... params) { 
     try { 
      for (int i = 0; i < mToBeUploaded.length; i++) { 
       mCurrentFileIndex = i; 
       File file = mToBeUploaded[i]; 

       // By creating a request, we get a handle to the putFile operation, 
       // so we can cancel it later if we want to 
       FileInputStream fis = new FileInputStream(file); 
       String path = mPath + file.getName(); 
       mRequest = mApi.putFileOverwriteRequest(path, fis, file.length(), 
         new ProgressListener() { 
        @Override 
        public long progressInterval() { 
         // Update the progress bar every half-second or so 
         return 500; 
        } 

        @Override 
        public void onProgress(long bytes, long total) { 
         if(isCancelled()) { 
          // This will cancel the putFile operation 
          mRequest.abort(); 
         } 
         else { 
          publishProgress(bytes); 
         } 
        } 
       }); 

       mRequest.upload(); 

       if(!isCancelled) { 
        mFilesUploaded++; 
       } 
       else { 
        return false; 
       } 
      } 
      return true; 
     } catch (DropboxUnlinkedException e) { 
      // This session wasn't authenticated properly or user unlinked 
      mErrorMsg = "This app wasn't authenticated properly."; 
     } catch (DropboxFileSizeException e) { 
      // File size too big to upload via the API 
      mErrorMsg = "This file is too big to upload"; 
     } catch (DropboxPartialFileException e) { 
      // We canceled the operation 
      mErrorMsg = "Upload canceled"; 
     } catch (DropboxServerException e) { 
      // Server-side exception. These are examples of what could happen, 
      // but we don't do anything special with them here. 
      if (e.error == DropboxServerException._401_UNAUTHORIZED) { 
       // Unauthorized, so we should unlink them. You may want to 
       // automatically log the user out in this case. 
      } else if (e.error == DropboxServerException._403_FORBIDDEN) { 
       // Not allowed to access this 
      } else if (e.error == DropboxServerException._404_NOT_FOUND) { 
       // path not found (or if it was the thumbnail, can't be 
       // thumbnailed) 
      } else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) { 
       // user is over quota 
      } else { 
       // Something else 
      } 
      // This gets the Dropbox error, translated into the user's language 
      mErrorMsg = e.body.userError; 
      if (mErrorMsg == null) { 
       mErrorMsg = e.body.error; 
      } 
     } catch (DropboxIOException e) { 
      // Happens all the time, probably want to retry automatically. 
      mErrorMsg = "Network error. Try again."; 
     } catch (DropboxParseException e) { 
      // Probably due to Dropbox server restarting, should retry 
      mErrorMsg = "Dropbox error. Try again."; 
     } catch (DropboxException e) { 
      // Unknown error 
      mErrorMsg = "Unknown error. Try again."; 
     } catch (FileNotFoundException e) { 
     } 
     return false; 
    } 

    @Override 
    protected void onProgressUpdate(Long... progress) { 
     Long totalBytes = 0; 
     Long bytesUploaded = 0; 
     for(int i=0;i<mFilesToUpload.length;i++) { 
      Long bytes = mFilesToUpload[i].length() 
      totalBytes += bytes; 

      if(i < mCurrentFileIndex) { 
       bytesUploaded += bytes; 
      } 
     } 
     bytesUploaded += progress[0]; 

     mDialog.setMessage("Uploading file " + (mCurrentFileIndex+1) + "/" + filesToUpload.length); 
     mDialog.setProgress((bytesUploaded/totalBytes) * 100); 
    } 

    @Override 
    protected void onPostExecute(Boolean result) { 
     mDialog.dismiss(); 
     if (result) { 
      showToast("Image successfully uploaded"); 
     } else { 
      showToast(mErrorMsg); 
     } 
    } 

    private void showToast(String msg) { 
     Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG); 
     error.show(); 
    } 
} 
+0

덕분에 나는 그것을 시도 줄 다음 회신 해 드리겠습니다 대한 답변을! – user1616685

+0

안녕하세요, 여기에 조금 붙어 있습니다. 나는 "FileToUpload"클래스를 만들었고 이클립스는 "public void onProgress (long bytes, long total)"및 "public long progressInterval()"의 Override를 제거하고 "@Override"를 구현했다. \t public void onProgress (int progress) " fileList를 Upload 클래스에 전달할 수 있습니다. 당신은 코드의 두 번째 부분으로 내 Upload 클래스를 바꾸실 수 있습니까? 나는 그것에 초보자이다 – user1616685

+0

당신은 할 특별한 변화가 없도록 나의 특별한 수업을 삭제했다. 이제는 이해하기가 더 쉬울 것입니다. – Daverix

1

으로 Daverix의 도움으로, 나는 관리 할 수 ​​있었다. 솔루션에 내가 아래 코드를 게시합니다. 누군가가 진행 막대와 동일한 문제를 가지고있는 경우를 대비하여.

나는 이전 버전에 비해 몇 가지 변수의 이름을 변경 :

public class Upload extends AsyncTask<Void, Long, Boolean> { 

private DropboxAPI<?> mApi; 
private String mPath; 

private UploadRequest mRequest; 
private Context mContext; 
private ProgressDialog mDialog; 

private String mErrorMsg,filename; 

// new class variables: 
private int mFilesUploaded; 
private File[] mFilesToUpload; 
private int mCurrentFileIndex; 

int totalBytes = 0, indBytes = 0; 

public Upload(Context context, DropboxAPI<?> api, String dropboxPath, 
     File[] filesToUpload) { 
    // We set the context this way so we don't accidentally leak activities 
    mContext = context.getApplicationContext(); 
    mApi = api; 
    mPath = dropboxPath; 

    // set number of files uploaded to zero. 
    mFilesUploaded = 0; 
    mFilesToUpload = filesToUpload; 
    mCurrentFileIndex = 0; 

    for (int i = 0; i < mFilesToUpload.length; i++) { 
     Long bytes = mFilesToUpload[i].length(); 
     totalBytes += bytes; 
    } 

    mDialog = new ProgressDialog(context); 
    mDialog.setMax(100); 
    mDialog.setMessage("Uploading file 1/" + filesToUpload.length); 
    mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
    mDialog.setProgress(0); 
    mDialog.setButton("Cancel", new OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
      cancel(true); 
     } 
    }); 
    mDialog.show(); 
} 

@Override 
protected Boolean doInBackground(Void... params) { 
    try { 
     for (int i = 0; i < mFilesToUpload.length; i++) { 
      mCurrentFileIndex = i; 
      File file = mFilesToUpload[i]; 

      int bytes = (int) mFilesToUpload[i].length(); 
      indBytes = bytes; 

      filename= mFilesToUpload[i].getName(); 


      // By creating a request, we get a handle to the putFile 
      // operation, 
      // so we can cancel it later if we want to 
      FileInputStream fis = new FileInputStream(file); 
      String path = mPath + file.getName(); 
      mRequest = mApi.putFileOverwriteRequest(path, fis, 
        file.length(), new ProgressListener() { 
         @Override 
         public long progressInterval() { 
          // Update the progress bar every half-second or 
          // so 
          return 100; 
         } 

         @Override 
         public void onProgress(long bytes, long total) { 
          if (isCancelled()) { 
           // This will cancel the putFile operation 
           mRequest.abort(); 
          } else { 
           publishProgress(bytes); 
          } 
         } 
        }); 

      mRequest.upload(); 

      if (!isCancelled()) { 
       mFilesUploaded++; 
      } else { 
       return false; 
      } 
     } 
     return true; 
    } catch (DropboxUnlinkedException e) { 
     // This session wasn't authenticated properly or user unlinked 
     mErrorMsg = "This app wasn't authenticated properly."; 
    } catch (DropboxFileSizeException e) { 
     // File size too big to upload via the API 
     mErrorMsg = "This file is too big to upload"; 
    } catch (DropboxPartialFileException e) { 
     // We canceled the operation 
     mErrorMsg = "Upload canceled"; 
    } catch (DropboxServerException e) { 
     // Server-side exception. These are examples of what could happen, 
     // but we don't do anything special with them here. 
     if (e.error == DropboxServerException._401_UNAUTHORIZED) { 
      // Unauthorized, so we should unlink them. You may want to 
      // automatically log the user out in this case. 
     } else if (e.error == DropboxServerException._403_FORBIDDEN) { 
      // Not allowed to access this 
     } else if (e.error == DropboxServerException._404_NOT_FOUND) { 
      // path not found (or if it was the thumbnail, can't be 
      // thumbnailed) 
     } else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) { 
      // user is over quota 
     } else { 
      // Something else 
     } 
     // This gets the Dropbox error, translated into the user's language 
     mErrorMsg = e.body.userError; 
     if (mErrorMsg == null) { 
      mErrorMsg = e.body.error; 
     } 
    } catch (DropboxIOException e) { 
     // Happens all the time, probably want to retry automatically. 
     mErrorMsg = "Network error. Try again."; 
    } catch (DropboxParseException e) { 
     // Probably due to Dropbox server restarting, should retry 
     mErrorMsg = "Dropbox error. Try again."; 
    } catch (DropboxException e) { 
     // Unknown error 
     mErrorMsg = "Unknown error. Try again."; 
    } catch (FileNotFoundException e) { 
    } 
    return false; 
} 

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

    mDialog.setMessage("Uploading file " + (mCurrentFileIndex + 1) + "/" 
      + mFilesToUpload.length+"\n"+filename); 
    int percent = (int) (100.0 * (double) progress[0]/indBytes + 0.5); 
    Log.i("pro", percent + " " + progress[0] + "/" + indBytes); 
    mDialog.setProgress(percent); 
} 

@Override 
protected void onPostExecute(Boolean result) { 
    mDialog.dismiss(); 
    if (result) { 
     showToast("Upload finished"); 
    } else { 
     showToast(mErrorMsg); 
    } 
} 

private void showToast(String msg) { 
    Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG); 
    error.show(); 
} 
} 
+0

나는 모든 파일에 대해 progressbar를 원한다고 생각했지만 현재 파일 업로드 상태를보고 싶었다. – Daverix

+0

모든 파일의 진행률 표시 줄은 어떻게됩니까? – Mirko