2014-02-21 30 views
0

我是android新手。我試圖在aysnc Task中顯示一個進度條,同時發送照片到服務器,我希望製作與文件一樣多的進度條,並且這些進度條將根據發送到服務器的字節百分比更改狀態。我做了搜索,發現了一些與此相關的問題,但無法修改我的代碼,問題是進度條在按下按鈕後沒有顯示。Android-在將圖像發送到服務器時顯示ProgressBar中的異步任務

這裏是我的代碼

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

} 
+0

這是什麼問題?什麼不起作用? – Merlevede

+0

那麼你最近的問題呢?請清除您的問題 –

+0

我想顯示進度條..我已更新我的問題。 – hellosheikh

回答

0

嘗試運行的AsyncTask異步。不要使用「get()」函數。相反,通過「onPostExecute」回調獲得結果。

+0

你怎麼寫一些代碼。對不起,我是新的android – hellosheikh

0

進度與進步號/個/什麼:

 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中。 只需在最後'}'之前插入它。 只需將'Context context'更改爲'Context context = MainActivity.this'。

你也可以在這個類中插入一個構造函數,並使HttpUploader嵌套在它自己的文件中,但這可能會更復雜。

+0

,但問題是我不能顯示進度條,當我按下按鈕..第一次我也發佈我的MainActivity類代碼嗎? – hellosheikh

+0

你可以編輯你的第一篇文章來添加代碼。請參閱我的關於您的上下文的編輯。我認爲這是你的問題,你使用上下文而不分配上下文。 – tritop

+0

嗯,我得到一個錯誤,當我寫這個而不是上下文pg = new ProgressDialog(this);讓我發佈我的MainActivity代碼 – hellosheikh

0
@Override 
protected void onProgressUpdate(Integer... values) { 
    super.onProgressUpdate(values); 
    dialog.setProgress(values[0]); 
} 

而且在doInBackground:

publishProgress(someValue); 
0

使用此代碼顯示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()方法調用它dissmiss爲pDialog.dissmiss(); 集ProgressDialog風格和setCancelable()ACC給你。