Android - 图像上传到.net Web服务错误

时间:2013-10-19 13:37:24

标签: android .net web-services android-asynctask android-file

我创建了以下代码以连接到.net Web Service API并上传图像。然而,我遇到了一个错误。有人可以解释一下如何解决这个问题吗?

 private static int RESULT_LOAD_IMAGE = 1;
 Button imageLoad, uploadBtn;
 ImageView imageView;
 TextView imagePath, message;
 String imgPath;
 private Bitmap bitmap;
 private ProgressDialog dialog;

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

    imageLoad = (Button) findViewById(R.id.buttonLoadPicture);
    uploadBtn = (Button) findViewById(R.id.upload);
    imageView = (ImageView) findViewById(R.id.imgView);
    imagePath = (TextView) findViewById(R.id.imagePath);
    message = (TextView) findViewById(R.id.message);

    imageLoad.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {               
            Intent i = new Intent(
                    Intent.ACTION_PICK,
   android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(i, RESULT_LOAD_IMAGE);               

        }
    });

    uploadBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            dialog = ProgressDialog.show(MainActivity.this, "", "Uploading 
      file...", true);
            new uploadFile().execute();
        }
    });
 }

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        Log.d("Selected image URI", selectedImage.toString());

        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Log.d("Image Path Column", filePathColumn.toString());

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        Log.d("Picture Path", picturePath);
        imagePath.setText(picturePath);
        imgPath = picturePath;
        ImageView imageView = (ImageView) findViewById(R.id.imgView);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

    }
 }


 class uploadFile extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {

        Bitmap bm = BitmapFactory.decodeFile(imgPath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] b = baos.toByteArray();

        Log.d("b", b.toString());
        Log.d("baos", baos.toString());


        SoapObject request = new SoapObject("http://tempuri.org/", "sendImage");        
        request.addProperty("myImage", b);

        SoapSerializationEnvelope envelope=new   
     SoapSerializationEnvelope(SoapEnvelope.VER11);
        new MarshalBase64().register(envelope);
        envelope.dotNet = true; 
        envelope.setOutputSoapObject(request);

        try {
            Toast.makeText(getApplicationContext(), "Sending Pic", 
                       Toast.LENGTH_LONG).show();
            Toast.makeText(getApplicationContext(), "array length=" + b.length, 
                              Toast.LENGTH_LONG).show();
            HttpTransportSE androidHttpTransport = new 
                  HttpTransportSE("http://www.letstrend.com/spursService.asmx?WSDL");
            androidHttpTransport.call("http://tempuri.org/sendImage", envelope);
            SoapObject result = (SoapObject)envelope.bodyIn;
            Log.d("Soap Response", result.toString());
        } catch (Exception e) {
            e.printStackTrace();            
            Toast.makeText(getApplicationContext(), "in catch e=" + e.getMessage(), 
                  Toast.LENGTH_LONG).show();
            Toast.makeText(getApplicationContext(), "fault=" + ((SoapFault) 
                  envelope.bodyIn).faultstring, Toast.LENGTH_LONG).show();
        }

        return null;
    }

 }

LogCat中显示的错误是

    FATAL EXCEPTION: AsyncTask #1
 java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
 Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not 
 called Looper.prepare()
at android.os.Handler.<init>(Handler.java:197)
at android.os.Handler.<init>(Handler.java:111)
at android.widget.Toast$TN.<init>(Toast.java:324)
at android.widget.Toast.<init>(Toast.java:91)
at android.widget.Toast.makeText(Toast.java:238)
atcom.maan.fileuploadbinary.MainActivity$uploadFile.doInBackground(MainActivity.java:150)
atcom.maan.fileuploadbinary.MainActivity$uploadFile.doInBackground(MainActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
... 4 more

     Activity com.maan.fileuploadbinary.MainActivity has leaked  windowcom.android.internal.policy.impl.PhoneWindow$DecorView{40cd31e8 V.E..... R.....ID 0,0- 456,144} that was originally android.view.WindowLeaked: 
     Activity com.maan.fileuploadbinary.MainActivity has leaked window    com.android.internal.policy.impl.PhoneWindow$DecorView{40cd31e8 V.E..... R.....ID 0,0-456,144} that was originally added here
     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
     at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
 at android.app.Dialog.show(Dialog.java:281)
 at android.app.ProgressDialog.show(ProgressDialog.java:116)
 at android.app.ProgressDialog.show(ProgressDialog.java:99)
 at com.maan.fileuploadbinary.MainActivity$2.onClick(MainActivity.java:71)
 at android.view.View.performClick(View.java:4204)
 at android.view.View$PerformClick.run(View.java:17355)
 at android.os.Handler.handleCallback(Handler.java:725)
 at android.os.Handler.dispatchMessage(Handler.java:92)
 at android.os.Looper.loop(Looper.java:137)
 at android.app.ActivityThread.main(ActivityThread.java:5041)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:511)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
 at dalvik.system.NativeStart.main(Native Method)

有人可以告诉我哪里出错了,这样我就可以学习并纠正错误。

提前感谢。

1 个答案:

答案 0 :(得分:1)

不要从AsyncTask访问您的UI-Thread,您的Toast会尝试访问它。因此,请在onPostExecute中制作所有UI-Thread动作并覆盖此方法,例如。带有Bitmap的Object和带错误的字符串。

//DEFINE TO RETURN A SOAP OBJECT
class uploadFile extends AsyncTask<Void, Void, SoapObject> {


//DEFINE TO RETURN A SOAP OBJECT
@Override
protected SoapObject doInBackground(Void... params) {

    Bitmap bm = BitmapFactory.decodeFile(imgPath);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] b = baos.toByteArray();

    Log.d("b", b.toString());
    Log.d("baos", baos.toString());


    SoapObject request = new SoapObject("http://tempuri.org/", "sendImage");        
    request.addProperty("myImage", b);

    SoapSerializationEnvelope envelope=new   
    SoapSerializationEnvelope(SoapEnvelope.VER11);
    new MarshalBase64().register(envelope);
    envelope.dotNet = true; 
    envelope.setOutputSoapObject(request);

    try {
    // ---> THIS IS BAD!!!!
        Toast.makeText(getApplicationContext(), "Sending Pic", 
                   Toast.LENGTH_LONG).show();
        Toast.makeText(getApplicationContext(), "array length=" + b.length, 
                          Toast.LENGTH_LONG).show();
   //<------- DELETE IT

        HttpTransportSE androidHttpTransport = new 
              HttpTransportSE("http://www.letstrend.com/spursService.asmx?WSDL");
        androidHttpTransport.call("http://tempuri.org/sendImage", envelope);
        SoapObject result = (SoapObject)envelope.bodyIn;
        Log.d("Soap Response", result.toString());
    } catch (Exception e) {
        e.printStackTrace();  

// ---> THIS IS BAD!!!!      
        Toast.makeText(getApplicationContext(), "in catch e=" + e.getMessage(), 
              Toast.LENGTH_LONG).show();
        Toast.makeText(getApplicationContext(), "fault=" + ((SoapFault) 
              envelope.bodyIn).faultstring, Toast.LENGTH_LONG).show();
//<------- DELETE IT

    }
    //TRY TO RETURN A MORE PROPRIATE OBJECT LIKE YOUR RESULT! AND HANDLE IT IN onPostExecute
    return result ;
}

@Override
onPostExecute(SoapObject result){

     if(result == null){
         Toast.makeText(_context, "Something went wrong", Toast.LENGTH_SHORT).show();
         return;
     }
     //HANDLE YOUR RESULT HERE

}