2013-03-22 58 views
2

有人可以告訴我,爲什麼progressbar在圖片上傳時不顯示。我從我的舊項目中複製了asynctask結構。在我的舊項目中,我使用asynctask從Web服務器下載圖片,並在下載時顯示進度條。 這裏是我的代碼:asynctask中的ProgressBar沒有顯示上傳

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

所以,當我打鍵上傳,畫面凍結,保持凍結,直到上傳完成後,和進度條顯示的心不是在所有。有時它顯示,但它的後方,我不知道爲什麼。我已經嘗試從doInBackground主體中的類中調用Post()方法,該主體內部整體代碼(body中的代碼與post()方法中的代碼相同),但效果相同,所以我想我在創建進度條時沒有做正確的事情。但是,我再次說,我從舊項目中複製了整個asynctask代碼,它的工作正常。

編輯:

我只是tryed創造PreviewPostActivity.class的構造進度條之後,我做出構造函數的AsyncTask類,但它仍然dosent工作。因爲它在我的舊程序中有效,所以我很困惑。 這裏是代碼他:

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體...

編輯:

對話框是顯示執行runOnUiThread()後。

+0

的AsyncTask運行在background.you必須更新onPostExecute() – Raghunandan 2013-03-22 14:27:00

+0

http://developer.android.com/reference/android/os/AsyncTask UI。 HTML。看到4個步驟。 – Raghunandan 2013-03-22 14:27:36

+0

我關閉onPostExecute();中的progressbar。 – toskebre 2013-03-22 14:29:34

回答

3

在asynctask doinbackground()中的ui線程上運行不正確。你也在doInBackground()中返回null,並且你在onPostExecute()中有參數file_url。 doInbackground()中的返回值接收onPostExecute()中的值。

doInBackGround()在後臺運行,因此您無法在此處訪問或更新ui。

要更新ui,您可以使用onPostExecute()。

你的AsyncTask應該像下面這樣。你做錯了。

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

我編輯了我的問題 – toskebre 2013-03-22 14:54:43

+0

您正在更改ui在doInBackground()中。在後臺運行在後臺線程中運行。所以在postexecute上更新ui。還要刪除doInBackground()中的runonuithread。 – Raghunandan 2013-03-22 14:57:28

+0

你可以在你的plz c/p行中更新ui doInBackground嗎?我不能看到它們,或者我不明白...我不知道 – toskebre 2013-03-22 15:04:44

5

我發現這個庫,它是完美的完成上傳任務,並提供可用於設置ProgressBar值的進度處理程序:

https://github.com/nadam/android-async-http

它可以用來像下面...設置onClickHandler的上傳按鈕:

@Override 
public void onClick(View arg0) { 
    try { 
     String url = Uri.parse("YOUR UPLOAD URL GOES HERE") 
       .buildUpon() 
       .appendQueryParameter("SOME PARAMETER IF NEEDED 01", "VALUE 01") 
       .appendQueryParameter("SOME PARAMETER IF NEEDED 02", "VALUE 02") 
       .build().toString(); 

     AsyncHttpResponseHandler httpResponseHandler = createHTTPResponseHandler(); 

     RequestParams params = new RequestParams(); 
     // this path could be retrieved from library or camera 
     String imageFilePath = "/storage/sdcard/DCIM/Camera/IMG.jpg"; 
     params.put("data", new File(imageFilePath)); 

     AsyncHttpClient client = new AsyncHttpClient(); 
     client.post(url, params, httpResponseHandler); 
    } catch (IOException e) { 
     e.printStackTrace();     
    } 
} 

則此方法添加到您的活動代碼:

public AsyncHttpResponseHandler createHTTPResponseHandler() { 
    AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() { 
     @Override 
     public void onStart() { 
      super.onStart(); 
     } 

     @Override 
     public void onProgress(int position, int length) { 
      super.onProgress(position, length); 

      progressBar.setProgress(position); 
      progressBar.setMax(length); 
     } 

     @Override 
     public void onSuccess(String content) { 
      super.onSuccess(content); 
     } 

     @Override 
     public void onFailure(Throwable error, String content) { 
      super.onFailure(error, content); 
     } 

     @Override 
     public void onFinish() { 
      super.onFinish(); 
     } 
    }; 

    return handler; 
} 
+0

THnq這麼多人...最後我完成了我的應用程序... – 2014-08-16 10:27:51