Android:将数据上传到服务器的进度条 [英] Android: Progress Bar to Upload Data to the Server

查看:483
本文介绍了Android:将数据上传到服务器的进度条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,有一些数据被包装到一个对象中。
我将此对象发送到服务器。一切正常。
这里我想显示数据加载到服务器时的进度条。
为此我使用此代码:

In my application some data is there which is wrapped into an object. I am sending this object to the server. Everything work correctly. Here I want to show progress bar when the data is loading to the server. For this I am using this code:

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.saveOnServer(Object)
由上面一行我发送对象到服务器。实际上我将数据发送到另一个类connectServerClass,这个类将对象发送到服务器。
但此代码无法正常工作。这段代码很多时候连接到服务器。

connectServerClass.saveOnServer(Object) by the above line I am sending object to the server. Actually I am sending data to the other class which is connectServerClass and this class send object to the server. but this code not work correctly. This code connect to the server lots of time.

我使用以下代码:

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 
        }
    }

但是我面临一些错误,我在该行的右侧提到了评论。请建议我。

But I facing some error which I mention as comment in the right side of that line. Please suggest me.

推荐答案

我强烈建议您使用AsyncTask。

I will strongly recommend you to Use AsyncTask.

下面的代码片段将帮助您了解AsyncTask的外观。

Below Code snippet will help you on How your AsyncTask should look like.

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();
        }
    }

这篇关于Android:将数据上传到服务器的进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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