2012-07-05 51 views
1

我的程序正在從SD卡上傳視頻沒有問題,但我試圖添加一個進度對話框來顯示迄今以百分比上傳的字節數。我正在使用異步任務。但是,儘管我能夠在屏幕上顯示對話框。該對話框沒有更新。上傳完成後,它變爲100/100,消失。你能幫我嗎我如何更新進度對話框?在上傳過程中更新進度對話框

package com.isoft.uploader2; 

import java.io.DataOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.database.Cursor; 
import android.net.Uri; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.os.Handler; 
import android.provider.MediaStore; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 

public class Proje2Activity extends Activity 
{ 
@Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     Button select =(Button)findViewById(R.id.select); 
     Button back =(Button)findViewById(R.id.back1); 
     Button camera =(Button)findViewById(R.id.camera); 

     //Select a video from SD-Card 
     select.setOnClickListener(new View.OnClickListener() 
     { 
      @Override 
      public void onClick(View arg0) 
      { 
       // TODO Auto-generated method stub 
       openGaleryVideo(); 
      } 
     }); 

     //Turn back 
     back.setOnClickListener(new View.OnClickListener() 
     { 
      @Override 
      public void onClick(View arg0) 
      { 
       // TODO Auto-generated method stub 
       finish(); 
      } 
     }); 

     //Record a video 
     camera.setOnClickListener(new View.OnClickListener() 
     { 
      @Override 
      public void onClick(View arg0) 
      { 
       // TODO Auto-generated method stub 
       Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
       startActivity(intent); 
      } 
     }); 
    } 
/** Called when the activity is first created. */ 
public static final int SELECT_VIDEO=1; 
public static final String TAG="UploadActivity"; 
String path=""; 

//Open Gallery 
public void openGaleryVideo() 
{ 
    Intent intent=new Intent(); 
    intent.setType("video/*"); 
    intent.setAction(Intent.ACTION_GET_CONTENT); 
    startActivityForResult(Intent.createChooser(intent, "Select Video"),SELECT_VIDEO); 
} 

//Select the video and start to execute the upload class 
public void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    super.onActivityResult(requestCode, resultCode, data); 
    if (resultCode == RESULT_OK) 
    { 
     if (requestCode == SELECT_VIDEO) 
     { 
      Uri videoUri = data.getData(); 
      path= getPath(videoUri); 
      upload upload = new upload(); 
      upload.execute(); 
     } 
    } 
} 

//Getting the URİ from the SD Card 
public String getPath(Uri uri) 
{ 
    String[] projection = { MediaStore.Video.Media.DATA}; 
    Cursor cursor = managedQuery(uri, projection, null, null, null); 
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA); 
    cursor.moveToFirst(); 
    return cursor.getString(column_index); 
} 

//ASYNC TASK Upload Class which uploads the file and shows the progress via a dialog 
public class upload extends AsyncTask<Object, Integer, Void> 
{ 
    //Initializations 
    public ProgressDialog dialog; 
    File file=new File(path); 
    String urlServer = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; 
    String filename=file.getName(); 
    int bytesRead, bytesAvailable, bufferSize,progress; 
    byte[] buffer; 
    int maxBufferSize = 20*1024*1024; 

    //Before start to upload the file creating a dialog 
    @Override 
    public void onPreExecute() 
    { 
     dialog = new ProgressDialog(Proje2Activity.this); 
     dialog.setMessage("Uploading..."); 
     dialog.setIndeterminate(false); 
     dialog.setTitle("UPLOADING"); 
     dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
     dialog.setProgress(0); 
     dialog.setMax(100); 
     dialog.show(); 
      //Burada işlemi yapmadan önce ilk olarak ne yaptırmak istiyorsak burada yaparız. 
      //Örneğin burada dialog gösterip "onPostExecute()" metodunda dismiss edebiliriz. 
    } 

    //Uploading the file in background with showing the progress 
    @Override 
    public Void doInBackground(Object... arg0) 
    { 
     // TODO Auto-generated method stub 
     try 
     { 
     final FileInputStream fileInputStream = new FileInputStream(file); 
     URL url = new URL(urlServer); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setFixedLengthStreamingMode((int) file.length()); 

     // Allow Inputs & Outputs 
     connection.setDoInput(true); 
     connection.setDoOutput(true); 
     connection.setUseCaches(false); 

     // Enable POST method 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Connection", "Keep-Alive"); 
     connection.setRequestProperty("Content-Type", "multipart/form-data"); 
     connection.setRequestProperty("SD-FileName", filename);//This will be the file name 
     final DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); 
     bytesAvailable = fileInputStream.available(); 
     bufferSize = Math.min(bytesAvailable, maxBufferSize); 
     buffer = new byte[bufferSize]; 
     // Read file 
     bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

     while (bytesRead > 0) 
     { 
      progress=0; 
      progress+=bytesRead; 
      outputStream.write(buffer, 0, bufferSize); 
      bytesAvailable = fileInputStream.available(); 
      publishProgress((int)((progress*100)/(file.length()))); 
      bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
      progress+=bytesRead; 
     }//end of while statement 
     fileInputStream.close(); 
     publishProgress(100); 
     outputStream.flush(); 
     outputStream.close(); 
     }//end of try body 

     catch (Exception ex) 
     { 
      //ex.printStackTrace(); 
      Log.e("Error: ", ex.getMessage()); 
     } 

     return null; 
    }//end of doInBackground method 

    //making an update on progress 
    @Override 
    public void onProgressUpdate(Integer... values) 
     { 
      super.onProgressUpdate(values); 
      dialog.setProgress(values[0]); 
     }//end of onProgressUpdate 

    //After finishing the progress the dialog will disappear! 
    @Override 
    public void onPostExecute(Void result) 
     { 
      try 
      { 
       dialog.dismiss(); 
      } //End of the second try body 
      catch(Exception e) 
      { 

      } 
     }//end of onPostExecute method 
}// end of asyncTask class 
}//end of main 
+3

哪裏是你的代碼? – 2012-07-05 08:44:51

+0

發佈你的代碼... – Aerrow 2012-07-05 08:45:19

+0

我現在發佈 – answer88 2012-07-05 08:50:06

回答

2

問題,我注意到有:

  • bufferSize可總文件長度。所以,在一個自我閱讀中,緩衝區可以是滿的。我改成了512的進度得到顯着的變化
  • 您重置progress變量循環
  • 也,你(從0bufferSize)寫入整個緩衝區輸出流中。不是實際的`bytesRead。在最後的部分你可能會得到錯誤值。
  • 再次閱讀之前,你是不是restting的buffer

更新的代碼

bufferSize = 512; 
buffer = new byte[bufferSize]; 
// Read file 
bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
progress=0; 

while (bytesRead > 0) 
{ 

    progress+=bytesRead; 
    outputStream.write(buffer, 0, bytesRead); 
    bytesAvailable = fileInputStream.available(); 
    publishProgress((int)((progress*100)/(file.length()))); 
    bufferSize = Math.min(bytesAvailable, maxBufferSize); 
    buffer = new byte[bufferSize]; 
    bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
}//end of while statement 
fileInputStream.close(); 
publishProgress(100); 
outputStream.flush(); 
outputStream.close(); 
+0

非常感謝你!那是我想要得到的答案! – answer88 2012-07-05 10:32:33

0

你的循環應該看起來像這樣,你的代碼中有幾個邏輯錯誤。

// Read file 
bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
progress=0; 
progress+=bytesRead; 

while (bytesRead > 0) 
{ 
    outputStream.write(buffer, 0, bufferSize); 
    bytesAvailable = fileInputStream.available(); 
    publishProgress((int)((progress/file.length())*100)); 
    bufferSize = Math.min(bytesAvailable, maxBufferSize); 
    bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
    progress+=bytesRead; 
}//end of while statement 

更新:我剛纔注意到,您使用帶有20MB緩衝區,切換到maxBufferSizeint maxBufferSize = 1024,它應該工作。

+0

我試過了,但問題仍然是一樣的,對話框沒有進展 – answer88 2012-07-05 08:57:26

+0

我更新了我的答案。 **首先**您在循環中將'bytesRead'添加到'progress'兩次。 **第二**在循環的每次迭代中將進度設置爲0。 **第三**你的數學計算百分比是錯誤的。 – 2012-07-05 09:05:33