【问题标题】:Android- show ProgressBar in Async task while sending images to the serverAndroid-在将图像发送到服务器时在异步任务中显示进度条
【发布时间】:2014-02-21 18:04:46
【问题描述】:

我是安卓新手。我试图在将照片发送到服务器时在 aysnc 任务中显示进度条,我想制作与文件一样多的进度条,并且这些进度条将根据发送到服务器的字节百分比更改状态。我进行了搜索,我发现了一些与此相关的问题,但无法修改我的代码,问题是按下按钮后进度条不显示。

这是我的代码

public  class HttpUploader extends AsyncTask<String, Void, String> {
    /*----------------------
    i followed some questions and here i have tried something but caused me an error

   private ProgressDialog dialog;
     private Context context;

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(context);
        dialog.setMessage("Uploading...");
        dialog.setIndeterminate(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setProgress(0);
        dialog.show();
    }

    protected void onPostExecute(final Boolean success) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }-------------------------*/ 
    protected String doInBackground(String... path) {

        String outPut = null;

        for (String sdPath:path) {

            Bitmap bitmapOrg = BitmapFactory.decodeFile(sdPath);
            ByteArrayOutputStream bao = new ByteArrayOutputStream();

            //Resize the image
            double width = bitmapOrg.getWidth();
            double height = bitmapOrg.getHeight();
            double ratio = 400/width;
            int newheight = (int)(ratio*height);

           // System.out.println("———-width" + width);
            //System.out.println("———-height" + height);

            bitmapOrg = Bitmap.createScaledBitmap(bitmapOrg, 400, newheight, true);

            //Here you can define .PNG as well
            bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 95, bao);
            byte[] ba = bao.toByteArray();
            String ba1 = Base64.encodeToString(ba, 0);

            //System.out.println("uploading image now ——–" + ba1);

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("image", ba1));

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://imageuplaod");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();                

                // print responce
                outPut = EntityUtils.toString(entity);
                Log.i("GET RESPONSE—-", outPut);

                //is = entity.getContent();
                Log.e("log_tag ******", "good connection");

                bitmapOrg.recycle();

            } catch (Exception e) {
                Log.e("log_tag ******", "Error in http connection " + e.toString());
            }
        }
        return outPut;
    }


  }

我的MainActivity 班级

 public class MainActivity extends Activity{

    Uri currImageURI;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      Button upload_btn = (Button) this.findViewById(R.id.uploadButton);
        upload_btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {


                upload();
                }});

    }

    public void upload(){         

                ArrayList<Uri> fileName = getFileList();
                for ( int i = 0 ; i < fileName.size() ; i++ )
                {
                HttpUploader uploader = new HttpUploader();

                try {

                      uploader.execute(getRealPathFromURI(fileName.get(i))).get();
                      Thread.sleep(1000);   
                } catch (InterruptedException e) {
                      e.printStackTrace();
                    } catch (ExecutionException e) {
                      e.printStackTrace();
                    }
                }
                TextView tv_path = (TextView) findViewById(R.id.path);
                tv_path.setText(getRealPathFromURI(currImageURI));
            }



    public String getRealPathFromURI(Uri contentUri) {

        String [] proj={MediaStore.Images.Media.DATA};
        android.database.Cursor cursor = managedQuery( contentUri,
        proj,     // Which columns to return
        null,     // WHERE clause; which rows to return (all rows)
        null,     // WHERE clause selection arguments (none)
        null);     // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }


    private ArrayList<Uri> getFileList()
    {
        ArrayList<Uri> fileList = new ArrayList<Uri>();
        try
        {
            String[] proj = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
            Cursor actualimagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
                    null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);

            int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);

            for ( int i = 0 ; i < actualimagecursor.getCount() ; i++ )
            {
                actualimagecursor.moveToPosition(i);
                String fileName = actualimagecursor.getString(actual_image_column_index);
                fileList.add(( Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, fileName )));
                //fileName = ( Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, fileName ).toString() );
            }
            return fileList;
        }
        catch ( Exception e )
        {
            return null;
        }
    }

}

【问题讨论】:

  • 这有什么问题?什么不工作?
  • 那么您对此有何疑问?请明确您的问题
  • 我想显示进度条..我已经更新了我的问题。
  • 表示当所有文件发送到服务器时进度条完成。但目前进度条没有显示
  • 我第二次更新了我的答案。根据提供的信息,我仍然认为它缺少上下文。

标签: android android-asynctask android-progressbar


【解决方案1】:

尝试异步运行 asyncTask。不要使用“get()”函数。相反,通过“onPostExecute”回调获取结果。

【讨论】:

  • 你怎么能写一些代码。抱歉,我是 android 新手
【解决方案2】:
@Override
protected void onProgressUpdate(Integer... values) {
  super.onProgressUpdate(values);
  dialog.setProgress(values[0]);
}

在 doInBackground 中:

publishProgress(someValue);

【讨论】:

    【解决方案3】:

    带有进度编号/百分比/其他的进度条:

            pg = new ProgressDialog(this);
            pg.setCancelable(false);
            pg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pg.setProgress(0);
            pg.setMax(100);
            pg.setMessage("Loading...");
            pg.show();
    
    
    private class someAsyncClass extends AsyncTask<String, String, Void> {
    
        @Override
        protected Void doInBackground(String... params) {
                int percent = calchowfaryouare;
                publishProgress("Loading... "+percent+"%");
    
        }
    
        @Override
        protected void onProgressUpdate(String... progress) {
            super.onProgressUpdate(progress);
            if (pg != null) {
                pg.setMessage(progress[0]);
                pg.show();
            }
        }
    
    }
    

    编辑:您的问题是在您的注释代码中您使用了上下文,但在您的情况下,这将是空的。您永远不会为此分配任何东西。如果您在 Activity 中调用异步任务,只需使用 MainActivity.this 或 getApplication() 之类的东西。

    编辑 2:

    那么我是否正确地认为 HttpUploader 位于一个单独的文件中? 如果是这样,为了最简单的方法,将其复制到您的 MainActivity 中。 只需在最后一个 '}' 之前插入它。 只需将“上下文上下文”更改为“上下文上下文 = MainActivity.this”。

    您也可以只向该类插入一个构造函数并将 HttpUploader 嵌套在它自己的文件中,但这可能会更复杂。

    【讨论】:

    • 但问题是当我按下按钮时我无法首先显示进度条.. 我也发布我的 MainActivity 类代码吗?
    • 您可以编辑您的第一篇文章以添加代码。请参阅我对您的上下文的编辑。我认为那是您的问题,您使用了上下文而没有为其分配上下文。
    • 好吧,当我写这个而不是上下文 pg = new ProgressDialog(this);让我发布我的 MainActivity 代码
    • 是的,你可能不得不使用 MainActivity.this 之类的东西,这取决于你在哪里做。但是,请关注该上下文。您需要获得一个有效的上下文才能首先调用该对话框。
    • 我更新了我的问题。你能看看它并修改它吗?很抱歉,我在 android 上不是很好。我最近才开始学习它
    【解决方案4】:

    使用此代码在 aysnc 任务的 onPreExecute() 中显示进度条。

     pDialog = new ProgressDialog(XMPPChatDemoActivity.this);
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(true);
            pDialog.show();
    

    并在 onPostExecute() 方法中将其称为 pDialog.dissmiss(); 解雇 根据您设置 ProgressDialog 样式和 setCancelable()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-09
      • 1970-01-01
      • 2020-03-13
      相关资源
      最近更新 更多