使用AsyncTask的IllegalArgumentException

时间:2012-07-17 03:43:55

标签: android image file-upload android-asynctask

我最初使用自定义方法上传一些照片,但我决定使用AsyncTask上传照片,因为我想显示ProgessBar并且不明白如何在上传过程中使用原始方法中的一个。当我执行AsyncTask时,会抛出IllegalArgumentException,但我不明白为什么。

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

2 个答案:

答案 0 :(得分:0)

在UI线程上调用

OnPostExecute。尝试将方法更改为;

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

答案 1 :(得分:0)

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

中一样
  

AsyncTask可以正确,轻松地使用UI线程。这个班   允许执行后台操作并在UI上发布结果   线程,而不必操纵线程和/或处理程序。

     

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

阅读documentation以便更好地理解。

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

Toast.makeText(News_Edit.this,"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();