在上载过程中更新进度对话框 [英] Updating the progress dialog on an uploading process

查看:105
本文介绍了在上载过程中更新进度对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序正在从SD卡上传视频而没有任何问题,但我正在尝试添加一个进度对话框,以显示目前为止上传的字节数百分比。我正在使用异步任务。但是,尽管我能够在屏幕上显示对话框。对话框未更新。上传完成后,它变为100/100并且消失。你能帮我解决一下如何更新进度对话框吗?

My program is uploading a video from SD Card without a problem but I am trying to add a progress dialog to show how much bytes uploaded so far in percentage. I am using async task. However, altough I am able to show the dialog on the screen. The dialog is not updating. After the upload finished it turns to 100/100 and it dissappears. Could you please help me how can I update the progress dialog?

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


推荐答案

我注意到的问题是:


  • 你的 bufferSize 可以是文件总长度。所以,在一个读取本身,缓冲区可以是满的。我将其更改为512以在进度条中获得显着更改

  • 您的重置进度循环内的变量

  • 另外,您正在将整个缓冲区(即从 0 bufferSize )写入输出流。不是实际的`bytesRead。在最后一部分你可能会得到错误值。

  • 再次阅读之前,你没有停留缓冲区

  • your bufferSize can be total file length. so, in one read itself, the buffer can be full. i changed it to 512 to get noticeable change in progressbar
  • your resets progress variable inside the loop
  • also, you are writing the entire buffer (ie from 0 to bufferSize) to the output stream. not the actual `bytesRead. at the last portions you may get error values.
  • before reading again, you are not restting the 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();

这篇关于在上载过程中更新进度对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆