0

I have created the following code to connect to a .net Web Service API and upload a image. I am however presented with an error. Can someone please explain how this can be resolved?

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

 }

The error showed in LogCat are

    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

and

     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)

Can someone tell me where I went wrong so that I can learn and correct my mistake.

Thank in advance.

1 Answer 1

1

Do not acces your UI-Thread from AsyncTask, your Toast tries to acces it. So please make all UI-Thread Actions in the onPostExecute and overgive this method something to work with, eg. an Object with your Bitmap and some string with a error.

//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

}
Sign up to request clarification or add additional context in comments.

5 Comments

Hi, A.S. Thanks for your reply. Can you please correct the coding and send me back. I don't understand what you said...
Made you a code, but please look out for a Android book, it has no sense to only copy it, becouse the next time you are going to use it you have no idea what to do!
Thank you so much A.S. I am just a newbee. I'll study the android book as you adviced...
sorry for the delay A.S.
@MKD I agree with A.S. Simply copying code is not going to be helpful to you for the future should you face similar problems again. Instead, learn and revise the code; understand what each code block is doing so that you can learn and create custom code; and you will find that you can debug better since you will understand the code. Good luck

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.