进度中的AsyncTask没有显示上载进度、AsyncTask

2023-09-12 10:09:38 作者:话少爱笑.

谁能告诉我,为什么未启用进度显示拍摄照片时被上传。我复制AsyncTask的结构,从我的老项目中,它的工作原理。在我的老项目中,我使用的AsyncTask下载来自Web服务器的图片,并显示进度,同时下载。 这是我的code:

Can someone tell me, why progressbar isnt showing when picture is being uploaded. I copied asynctask structure from my old project where it works. In my old project i use asynctask to download pictures from web server, and to show progressbar while downloading. Here is my code:

public class PreviewPostActivity extends Activity {

ImageView imageView;

TextView tvComment;
Button submit;
MyLocationListener locationListener;
List<NameValuePair> list = new ArrayList<NameValuePair>();
private final String url = "***"; //Url of php script
ProgressDialog pDialog;
String responseMessage="";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.preview_post);

    Intent intent = this.getIntent();
    imageView = (ImageView)findViewById(R.id.imgPerview);
    tvComment = (TextView)findViewById(R.id.txtPreviewComment);
    submit = (Button)findViewById(R.id.btnPreviewSubmit);

    Bitmap image = (Bitmap)intent.getParcelableExtra("picture");
    String comment = intent.getStringExtra("comment");
    locationListener = (MyLocationListener)intent.getSerializableExtra("location");
    String imagePath = intent.getStringExtra("imagePath");
    String date = intent.getStringExtra("date");

    imageView.setImageBitmap(image);
    tvComment.setText(comment);

    //tvComment.append("\n"+locationListener.latitude + "\n"+locationListener.longitude);

    list.add(new BasicNameValuePair("image", imagePath));
    list.add(new BasicNameValuePair("comment", comment));
    list.add(new BasicNameValuePair("longitude", Double.toString(locationListener.longitude)));
    list.add(new BasicNameValuePair("latitude", Double.toString(locationListener.latitude)));
    list.add(new BasicNameValuePair("date", date));

    submit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            new uploadPost().execute();

        }
    });

}

public void post(List<NameValuePair> nameValuePairs) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
    HttpConnectionParams.setSoTimeout(httpParameters, 200000);
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpContext localContext = new BasicHttpContext();
    HttpPost httpPost = new HttpPost(url);

    try {
        MultipartEntity entity = new MultipartEntity();

        for(int index=0; index < nameValuePairs.size(); index++) {
            if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
                // If the key equals to "image", we use FileBody to transfer the data

                entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File(nameValuePairs.get(index).getValue()),"image/jpeg"));
            } else {
                // Normal string data
                entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
            }
        }

        httpPost.setEntity(entity);

        HttpResponse response = httpClient.execute(httpPost, localContext);
        HttpEntity httpEntity = response.getEntity();
        String responseMessage = EntityUtils.toString(httpEntity);

        tvComment.setText(responseMessage);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

class uploadPost extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(PreviewPostActivity.this);
        pDialog.setMessage("Uploading post. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Getting product details in background thread
     * */
    protected String doInBackground(String... params) {

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {

                    //post(list);
                HttpParams httpParameters = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
                HttpConnectionParams.setSoTimeout(httpParameters, 200000);
                HttpClient httpClient = new DefaultHttpClient(httpParameters);
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost(url);

                try {
                    MultipartEntity entity = new MultipartEntity();

                    for(int index=0; index < list.size(); index++) {
                        if(list.get(index).getName().equalsIgnoreCase("image")) {
                            // If the key equals to "image", we use FileBody to transfer the data

                            entity.addPart(list.get(index).getName(), new FileBody(new File(list.get(index).getValue()),"image/jpeg"));
                        } else {
                            // Normal string data
                            entity.addPart(list.get(index).getName(), new StringBody(list.get(index).getValue()));
                        }
                    }

                    httpPost.setEntity(entity);

                    HttpResponse response = httpClient.execute(httpPost, localContext);
                    HttpEntity httpEntity = response.getEntity();
                    responseMessage = EntityUtils.toString(httpEntity);

                    //tvComment.setText(responseMessage);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once got all details
        tvComment.setText(responseMessage);
        pDialog.dismiss();
    }
}

所以,当我打键上传,画面冻结,并保持冻结,直到上传完成后,和一个进度条心不是显示在所有。有时它显示了,但它的RLY后方,我不知道为什么。我已经打过电话后()从doInBackground体类方法insted的全code(code的身体是一样的post()方法),但效果是一样的,所以我想我没有做什么正确的创建进度。但是,我再说我复制从旧项目整体的AsyncTask code在女巫它能正常工作。

So when i hit button for upload, screen freezes and stay frozen until upload is complete, and progress bar isnt showing at all. Sometimes it shows, but its rly rear and i dont know why. I have tried calling Post() method from class in doInBackground body insted of whole code (code in body is the same as in post() method) but effect is the same, so i guess i didnt do something right in creating progressbar. But again i say i copied whole asynctask code from old project in witch it worked fine.

编辑:

我只是tryed在previewPostActivity.class构造函数创建进度条之后,我做出构造的AsyncTask类,但它仍然dosent工作。我RLY困惑becouse它曾在我的旧程序。 这里是code从他:

I just tryed creating progress bar in constructor of PreviewPostActivity.class and after that i made constructor for asynctask class but it still dosent work. I am rly confused becouse it worked in my old program. Here is code from him:

class GetSlike extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(KlubSlikeActivity.this);
        pDialog.setMessage("Ucitavanje u toku. Molimo vas sacekajte...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Getting product details in background thread
     * */
    protected String doInBackground(String... params) {

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {

                    String id = Integer.toString(k.getId());
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("klub",id));

                    slikeUrl = JSONAdapter.getSlike(params);
                    gv.setAdapter(new SlikeAdapter(slikeUrl,KlubSlikeActivity.this));
            }
        });

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once got all details
        pDialog.dismiss();
    }
}

唯一不变的是doInBackground身体......

Only thing changed is doInBackground body...

编辑:

Dialog是在 runOnUiThread显示()被执行。

Dialog is display after runOnUiThread() is executed.

推荐答案

在AsyncTask的doinbackground UI线程的run()是不正确的。你也正在返回空值在doInBackground(),你有参数file_url在onPostExecute()。在doInbackground()返回值onPostExecute()。免费获赠价值

Run on ui thread in asynctask doinbackground() is not correct. Also you are returning null in doInBackground() and you have parameter file_url in onPostExecute(). Return value in doInbackground() recieve value in onPostExecute().

doInBackGround()在后台运行,所以你不能访问或更新UI这里。

doInBackGround() runs in background so you cannot access or update ui here.

要更新的用户界面,您可以使用onPostExecute()。

To update ui you can use onPostExecute().

您AsyncTask的应该是如下图所示。你是做了错误的方式。

Your AsyncTask should be something like below. You are doing it the wrong way.

http://developer.android.com/reference/android/os/ AsyncTask.html 。 查看下的4个步骤的话题

 pd= new ProgressDialog(this);
 pd.setTitle("Posting data");
 new PostTask().execute();

private class PostTask extends AsyncTask<VOid, Void, Void> {

protected void onPreExecute()
{//display dialog.
  pd.show();
}
protected SoapObject doInBackground(Void... params) {
// TODO Auto-generated method stub
       //post request. do not update ui here. runs in background
return null;
}

protected void onPostExecute(Void param)
{   

 pd.dismiss();
 //update ui here
}