安卓:上传数据到服务器的进度条

3
在我的应用程序中有一些数据被包装成一个对象。 我将这个对象发送到服务器。一切都正常工作。 在此,当数据正在加载到服务器时,我想显示进度条。 为此,我使用以下代码:
ProgressThread progThread;
ProgressDialog progDialog;

int typeBar;
int delay = 40; 
int maxBarValue = 200;
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case 1:
        progDialog = new ProgressDialog(this);
        progDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progDialog.setMax(maxBarValue);
        progDialog.setMessage("Data uploading to the Server..");
        progThread = new ProgressThread(handler);
        progThread.start();
        return progDialog;

    default:
        return null;
    }
}


final Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        // Get the current value of the variable total from the message data
        // and update the progress bar.
        int total = msg.getData().getInt("total");
        progDialog.setProgress(total);
        if (total <= 0) {
            dismissDialog(typeBar);
            progThread.setState(ProgressThread.DONE);
        }
    }
};

private class ProgressThread extends Thread {

    final static int DONE = 0;
    final static int RUNNING = 1;

    Handler mHandler;
    int mState;
    int total;

    ProgressThread(Handler h) {
        mHandler = h;
    }


    @Override
    public void run() {
        mState = RUNNING;
        total = maxBarValue;
        while (mState == RUNNING) {

            connectServerClass.saveOnServer(Object);

            Message msg = mHandler.obtainMessage();
            Bundle b = new Bundle();
            b.putInt("total", total);
            msg.setData(b);
            mHandler.sendMessage(msg);

            total--; // Count down
        }
    }
    public void setState(int state) {
        mState = state;
    }
}

当用户点击按钮时:
typeBar = 1;
showDialog(typeBar);

通过上面的代码,我正在将对象发送到服务器。实际上,我将数据发送到另一个名为connectServerClass的类中,该类将对象发送到服务器。

但是这段代码不正常工作。它与服务器连接了很多次。

我使用以下代码:

private class Uploader extends AsyncTask<Void, String, Integer>
    {
        private List<File> files;
        private boolean canceled;
        private int uploaded;
        private Account account;
        private ProgressDialog uploadSeekBar;

        public Uploader(Account a, List<File> files)
        {
            this.account = a;
            this.files = files;
        }

        @Override
        protected void onPreExecute()
        {
            uploadSeekBar.setMax(files.size());
            uploadSeekBar.setProgress(0);
            uploadSeekBar.setVisibility(View.VISIBLE);  //Error: the method setVisibility is undefined
        }

        @Override
        protected void onPostExecute(Integer result)
        {
            uploadSeekBar.setVisibility(View.INVISIBLE);
            Toast.makeText(Upload.this, result + " files uploaded", // Error: Upload cannot be resolved to a type
                    Toast.LENGTH_LONG).show();
        }

        @Override
        protected void onCancelled()
        {
            // XXX need a way to actually cancel the last upload
            Toast.makeText(Upload.this, "canceling upload", Toast.LENGTH_LONG)
                    .show();
            this.canceled = true;
            uploadSeekBar.setVisibility(View.INVISIBLE);

        }

        @Override
        protected Integer doInBackground(Void... voids)
        {
            uploaded = 0;
            try
            {
                Iterator<File> it = this.files.iterator();
                while (!canceled && it.hasNext())
                {
                    File file = it.next();
                    it.remove();

                    String msg = "";

                    try
                    {
                        if (debugMode)  // what is this debugMode
                        {
                                                //Put your uploading code here.
                            msg = ("fake uploading " + file);
                            Thread.sleep(3000);
                        } else
                        {
                            msg = ("uploading: " + file);
                            controller.uploadFile(file, this.account); //Error: controller cannot be resolved
                        }

                        uploaded++;
                        publishProgress(msg);

                    } catch (IOException e)
                    {
                        controller.te("error uploading file: " + file);
                        controller.te("error uploading file: " + e);
                    } catch (InterruptedException e)
                    {
                    }
                }
            } catch (Exception e)
            {
                publishProgress("error uploading: " + e);
            }

            return uploaded;
        }

        @Override
        protected void onProgressUpdate(String... strings)
        {
            uploadSeekBar.setProgress(uploaded);
            updateUploadMessage(files.size());
            Toast.makeText(Upload.this, strings[0], Toast.LENGTH_LONG).show(); //Error: The method updateUploadMessage(int) is undefined for the type FirstActivity.Uploader 
        }
    }

但是我遇到了一些错误,我在那行右侧的注释中提到了这些错误,请给我建议。


我的这个答案可能对你有帮助。 - Lucifer
1个回答

3
我强烈推荐您使用AsyncTask。
以下代码片段将帮助您了解您的AsyncTask应该是什么样子。
package org.sample;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import android.accounts.Account;
import android.os.AsyncTask;
import android.view.View;
import android.widget.Toast;

    private class Uploader extends AsyncTask<Void, String, Integer>
    {
        private List<File> files;
        private boolean canceled;
        private int uploaded;

        public Uploader(Account a, List<File> files)
        {
            this.account = a;
            this.files = files;
        }

        @Override
        protected void onPreExecute()
        {
            uploadSeekBar.setMax(files.size());
            uploadSeekBar.setProgress(0);
            uploadSeekBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(Integer result)
        {
            uploadSeekBar.setVisibility(View.INVISIBLE);
            Toast.makeText(Upload.this, result + " files uploaded",
                    Toast.LENGTH_LONG).show();
        }

        @Override
        protected void onCancelled()
        {
            // XXX need a way to actually cancel the last upload
            Toast.makeText(Upload.this, "canceling upload", Toast.LENGTH_LONG)
                    .show();
            this.canceled = true;
            uploadSeekBar.setVisibility(View.INVISIBLE);

        }

        @Override
        protected Integer doInBackground(Void... voids)
        {
            uploaded = 0;
            try
            {
                Iterator<File> it = this.files.iterator();
                while (!canceled && it.hasNext())
                {
                    File file = it.next();
                    it.remove();

                    String msg = "";

                    try
                    {
                        if (debugMode)
                        {
                                                //Put your uploading code here.
                            msg = ("fake uploading " + file);
                            Thread.sleep(3000);
                        } else
                        {
                            msg = ("uploading: " + file);
                            controller.uploadFile(file, this.account);
                        }

                        uploaded++;
                        publishProgress(msg);

                    } catch (IOException e)
                    {
                        controller.te("error uploading file: " + file);
                        controller.te("error uploading file: " + e);
                    } catch (InterruptedException e)
                    {
                    }
                }
            } catch (Exception e)
            {
                publishProgress("error uploading: " + e);
            }

            return uploaded;
        }

        @Override
        protected void onProgressUpdate(String... strings)
        {
            uploadSeekBar.setProgress(uploaded);
            updateUploadMessage(files.size());
            Toast.makeText(Upload.this, strings[0], Toast.LENGTH_LONG).show();
        }
    }

谢谢Vipul...所以我需要在doInBackground方法中编写代码,即connectServerClass.saveOnServer(Object)。 - Vinit ...
完美!!您可以在doInBackground中编写上传代码,完成后可以在onPostExecute中显示成功/失败消息!! - Vipul
如果这个答案解决了你的问题,那么你可以将其标记为“已接受的答案”,这样可以帮助其他人。 - Vipul
@ Vipul,我知道如何放置进度条了。但是还有一个问题,我需要在doInBackground()和onProgressUpdate()方法中编写什么代码。请帮助我。 我在这个链接中提出了这个问题:http://stackoverflow.com/questions/10979739/android-progress-bar-to-upload-object-into-server#comment14340402_10979739 - Vinit ...
@VipulShah,您能否解释一下如何使用您的代码在服务器上上传单个图像,并在底部使用进度条。因为您的代码似乎适用于多个文件,它会增加每个文件上传的计数并通过计数更新进度条。 - kamil
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接