1

我本来是用自定义方法上传一些照片,但我决定用anAsyncTask来上传照片,因为我想在上传的过程中显示aProgessBar并且不明白如何在我的原始方法中使用一个。当我执行时,我AsyncTask的 anIllegalArgumentException被抛出,但我不明白为什么。

private void doFileUpload(){

        Log.d("imagepath", "imagepath: " + imagepath);
                    finalPath = new File(imagepath);
                    if (!finalPath.exists()){
                        try {
                              finalPath.createNewFile();
                              copyFile(new File(filePath), finalPath);
                        } catch (IOException e) {
                                 // TODO Auto-generated catch block
                               e.printStackTrace();
                        }
                    }

                    Bitmap bmpPic = BitmapFactory.decodeFile(imagepath);
                    int MAX_IMAGE_SIZE = 300000; // max final file size
                    if ((bmpPic.getWidth() >= 600) && (bmpPic.getHeight() >= 600)) {
                          BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
                          bmpOptions.inSampleSize = 1;
                          while ((bmpPic.getWidth() >= 600) && (bmpPic.getHeight() >= 600)) {
                              bmpOptions.inSampleSize++;
                              bmpPic = BitmapFactory.decodeFile(filePath, bmpOptions);
                          }
                            Log.d("bmpOptions.inSampleSize", "Resize: " + bmpOptions.inSampleSize);
                        }
                        int compressQuality = 104; // quality decreasing by 5 every loop. (start from 99)
                        int streamLength = MAX_IMAGE_SIZE;
                        while (streamLength >= MAX_IMAGE_SIZE) {
                           ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
                           compressQuality -= 5;
                           Log.d("compressQuality", "Quality: " + compressQuality);
                           bmpPic.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream);
                           byte[] bmpPicByteArray = bmpStream.toByteArray();
                           streamLength = bmpPicByteArray.length;
                           Log.d("streamLength", "Size: " + streamLength);
                        }
                    try {
                        FileOutputStream bmpFile = new FileOutputStream(finalPath);
                        bmpPic.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpFile);
                        bmpFile.flush();
                        bmpFile.close();
                    } catch (Exception e) {
                        Log.e("ERROR", "Error on saving file");
                    }

        File file1 = new File(imagepath);
        try
        {

             HttpClient client = new DefaultHttpClient();
             HttpPost post = new HttpPost(URL);

             FileBody bin1 = new FileBody(file1,imageType);
             //String abc=bin1.getMediaType();
             //System.out.println("abc :"+abc);
             System.out.println("imageType :"+imageType);
             MultipartEntity reqEntity = new MultipartEntity();

             if(use.equals("EditData")){
                 reqEntity.addPart("uploadedfile1", bin1);
                 reqEntity.addPart("uID", new StringBody(md5_id));
                 reqEntity.addPart("uPWD", new StringBody(md5_pass));
                 reqEntity.addPart("TYPE", new StringBody("NWPHOTO"));
                 reqEntity.addPart("REF", new StringBody(Ref));
                 reqEntity.addPart("CAT", new StringBody(cat0));
                 System.out.println("imageType :"+imageType+" "+md5_id+" "+md5_pass+" "+Ref+" "+cat0);
             }else if(use.equals("NewData")){
                 reqEntity.addPart("uploadedfile1", bin1);
                 reqEntity.addPart("uID", new StringBody(md5_id));
                 reqEntity.addPart("uPWD", new StringBody(md5_pass));
                 reqEntity.addPart("TYPE", new StringBody("INSERTNW"));
                 reqEntity.addPart("Title", new StringBody(newTitle));
                 reqEntity.addPart("News", new StringBody(newNews));
                 reqEntity.addPart("CAT", new StringBody(cat0));
                 reqEntity.addPart("use", new StringBody("NewData"));
                 System.out.println("imageType :"+imageType+" "+md5_id+" "+md5_pass+" "+cat0+" "+newNews+" "+newTitle);
             }

             post.setEntity(reqEntity);
             HttpResponse response = client.execute(post);
             resEntity = response.getEntity();
             final String response_str = EntityUtils.toString(resEntity,"UTF-8");
             if (resEntity != null) {

                 Log.i("RESPONSE PHOTO",response_str);
                 runOnUiThread(new Runnable(){
                        public void run() {

                             try {
                                System.out.println("n Response photo from server : " + response_str);
                                Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
                            } catch (Exception e) {
                                e.printStackTrace();
                                Log.e("log_tag", "error"+e.toString());
                            }
                        }
                   });
             }
        }
        catch (Exception ex){
             Log.e("Debug", "error: " + ex.getMessage(), ex);
        }

}

堆栈跟踪

07-17 11:22:34.715: E/AndroidRuntime(18379): FATAL EXCEPTION: main
07-17 11:22:34.715: E/AndroidRuntime(18379): java.lang.IllegalArgumentException: View not attached to window manager
07-17 11:22:34.715: E/AndroidRuntime(18379):    at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:380)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:225)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at android.view.Window$LocalWindowManager.removeView(Window.java:432)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at android.app.Dialog.dismissDialog(Dialog.java:278)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at android.app.Dialog.access$000(Dialog.java:71)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at android.app.Dialog$1.run(Dialog.java:111)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at android.app.Dialog.dismiss(Dialog.java:268)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at com.planbiz.net.News_Edit$UploadImage.onPostExecute(News_Edit.java:1019)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at com.planbiz.net.News_Edit$UploadImage.onPostExecute(News_Edit.java:1)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at android.os.AsyncTask.finish(AsyncTask.java:417)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at android.os.AsyncTask.access$300(AsyncTask.java:127)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at android.os.Looper.loop(Looper.java:130)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at android.app.ActivityThread.main(ActivityThread.java:3687)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at java.lang.reflect.Method.invokeNative(Native Method)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at java.lang.reflect.Method.invoke(Method.java:507)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
07-17 11:22:34.715: E/AndroidRuntime(18379):    at dalvik.system.NativeStart.main(Native Method)

我的AsyncTask

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

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(News_Edit.this);
                pDialog.setMessage("Loading ...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(false);
                pDialog.show();
            }

            protected String doInBackground(String... args) {
            Log.d("imagepath", "imagepath: " + imagepath);
                        finalPath = new File(imagepath);
                        if (!finalPath.exists()){
                            try {
                                  finalPath.createNewFile();
                                  copyFile(new File(filePath), finalPath);
                            } catch (IOException e) {
                                     // TODO Auto-generated catch block
                                   e.printStackTrace();
                            }
                        }

                        Bitmap bmpPic = BitmapFactory.decodeFile(imagepath);
                        int MAX_IMAGE_SIZE = 300000; // max final file size
                        if ((bmpPic.getWidth() >= 600) && (bmpPic.getHeight() >= 600)) {
                              BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
                              bmpOptions.inSampleSize = 1;
                              while ((bmpPic.getWidth() >= 600) && (bmpPic.getHeight() >= 600)) {
                                  bmpOptions.inSampleSize++;
                                  bmpPic = BitmapFactory.decodeFile(filePath, bmpOptions);
                              }
                                Log.d("bmpOptions.inSampleSize", "Resize: " + bmpOptions.inSampleSize);
                            }
                            int compressQuality = 104; // quality decreasing by 5 every loop. (start from 99)
                            int streamLength = MAX_IMAGE_SIZE;
                            while (streamLength >= MAX_IMAGE_SIZE) {
                               ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
                               compressQuality -= 5;
                               Log.d("compressQuality", "Quality: " + compressQuality);
                               bmpPic.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream);
                               byte[] bmpPicByteArray = bmpStream.toByteArray();
                               streamLength = bmpPicByteArray.length;
                               Log.d("streamLength", "Size: " + streamLength);
                            }
                        try {
                            FileOutputStream bmpFile = new FileOutputStream(finalPath);
                            bmpPic.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpFile);
                            bmpFile.flush();
                            bmpFile.close();
                        } catch (Exception e) {
                            Log.e("ERROR", "Error on saving file");
                        }

                File file1 = new File(imagepath);
                try
                {

                     HttpClient client = new DefaultHttpClient();
                     HttpPost post = new HttpPost(URL);

                     FileBody bin1 = new FileBody(file1,imageType);
                     //String abc=bin1.getMediaType();
                     //System.out.println("abc :"+abc);
                     System.out.println("imageType :"+imageType);
                     MultipartEntity reqEntity = new MultipartEntity();

                     if(use.equals("EditData")){
                         reqEntity.addPart("uploadedfile1", bin1);
                         reqEntity.addPart("uID", new StringBody(md5_id));
                         reqEntity.addPart("uPWD", new StringBody(md5_pass));
                         reqEntity.addPart("TYPE", new StringBody("NWPHOTO"));
                         reqEntity.addPart("REF", new StringBody(Ref));
                         reqEntity.addPart("CAT", new StringBody(cat0));
                         System.out.println("imageType :"+imageType+" "+md5_id+" "+md5_pass+" "+Ref+" "+cat0);
                     }else if(use.equals("NewData")){
                         reqEntity.addPart("uploadedfile1", bin1);
                         reqEntity.addPart("uID", new StringBody(md5_id));
                         reqEntity.addPart("uPWD", new StringBody(md5_pass));
                         reqEntity.addPart("TYPE", new StringBody("INSERTNW"));
                         reqEntity.addPart("Title", new StringBody(newTitle));
                         reqEntity.addPart("News", new StringBody(newNews));
                         reqEntity.addPart("CAT", new StringBody(cat0));
                         reqEntity.addPart("use", new StringBody("NewData"));
                         System.out.println("imageType :"+imageType+" "+md5_id+" "+md5_pass+" "+cat0+" "+newNews+" "+newTitle);
                     }

                     post.setEntity(reqEntity);
                     HttpResponse response = client.execute(post);
                     resEntity = response.getEntity();
                     response_str = EntityUtils.toString(resEntity,"UTF-8");
                }catch (Exception ex){
                     Log.e("Debug", "error: " + ex.getMessage(), ex);
                }
                return null;
            }

            protected void onPostExecute(String file_url) {
                if (resEntity != null) {
                    pDialog.dismiss();
                         Log.i("RESPONSE PHOTO",response_str);
                         runOnUiThread(new Runnable(){
                                public void run() {
                                    try {
                                        System.out.println("n Response photo from server : " + response_str);
                                        Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        Log.e("log_tag", "error"+e.toString());
                                    }
                                }
                           });
                     }
                }
        }
4

2 回答 2

0

OnPostExecute在 UI 线程上调用。尝试将方法更改为;

@Override
protected void onPostExecute(String file_url) {
    if (resEntity != null) {
        pDialog.dismiss();
        Log.i("RESPONSE PHOTO",response_str);
        Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
    }
}
于 2012-07-17T04:46:28.733 回答
0

您不需要在 AsyncTask 中启动新线程。尝试在不使用新线程的情况下完成所有任务。(就像在你的onPostExecute()

AsyncTask 允许正确和轻松地使用 UI 线程。此类允许在 UI 线程上执行后台操作并发布结果,而无需操作线程和/或处理程序。

异步任务由在后台线程上运行的计算定义,其结果在 UI 线程上发布

阅读文档以获得更好的理解。

还尝试替换吐司中的上下文值

Toast.makeText(News_Edit.this,"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
于 2012-07-17T04:55:37.533 回答