0

Can someone help me figure this out? I am trying to upload an image in base64 string format to a .Net webservices (web server) using ksoap on android. I was able to upload the file successfully when i click the submit button on the android app but it freezes and stop responding. I have checked everywhere for a solution, I couldn't find anything. Most solution where using Post method to PHP server. Please help! Thanks in advance.

Here is my code;

btnSubmit.setOnClickListener(new OnClickListener(){
       public void onClick(View v)
       {           


          //save image to path///////////////////
          try{
          String ImageData = lblEncodedImage.getText().toString();            
          imagefile = lblTargetUri.getText().toString();

              //webservice class for android.
          WebServiceCaller DWSCaller = new WebServiceCaller();
          int uploadResult = DWSCaller.UploadFile(ImageData, imagefile);

          if(uploadResult == 1){                
            //do something              
            lblStatus.setText("Submitted!");

          }
          else
          {
            lblStatus.setText("Error Submitting");
          }
          }
          catch(Exception e) {
                e.printStackTrace();
                lblStatus.setText("Error Submitting" + e.getMessage());
          }

          ////////////////////////////////////////
       }
   });


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

    if(resultCode == RESULT_OK){

        try { 
        Uri targetUri = data.getData();
        //txtTargetUri.setText(targetUri.toString());       

        String fileName  = getRealPathFromURI(targetUri);
        File aFile = new File(fileName);

        ///////////////////////

        lblTargetUri.setText(aFile.getName());
        lblImagePath.setText(fileName);

        Bitmap bitmap;

    //bitmap =                                                                 BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
              //Or use decodefile method
bitmap = BitmapFactory.decodeFile(fileName);

              targetImage.setImageBitmap(bitmap);

              //base 64     conversion                                

              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

              byte[] byteArray = baos.toByteArray();

              //Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
              //targetImage.setImageBitmap(bm);

              encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);

              lblEncodedImage.setText(encodedImage);

             } catch (Exception e) {
              // TODO Auto-generated catch block                     
              e.printStackTrace();
             }

    }
}

public String getRealPathFromURI(Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(contentUri, proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

I also created a different class called WebServiceCaller here is the code;

public class WebServiceCaller {

private final String NAMESPACE = "http://tempuri.org/"; 
private final String URL = "http://10.0.2.2:63097/service.asmx?WSDL";   

public int UploadFile(String imageData, String filename){
    int result = 0;
    final String SOAP_ACTION = "http://tempuri.org/CreateFileFromBase64String";     
    final String METHOD_NAME = "CreateFileFromBase64String";

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);    

    PropertyInfo propInfo1 =new PropertyInfo();
    propInfo1.setName("_imageData");
    propInfo1.setValue(imageData);
    propInfo1.setType(String.class);
    request.addProperty(propInfo1);

    PropertyInfo propInfo2 =new PropertyInfo();
    propInfo2.setName("_filename");
    propInfo2.setValue(filename);
    propInfo2.setType(String.class);
    request.addProperty(propInfo2);

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true; // put this only if the web service is .NET one
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    try {
        androidHttpTransport.call(SOAP_ACTION, envelope);
        SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
        Log.i("myApp", response.toString());
        if(response.toString().equalsIgnoreCase("true")){
            result = 1;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
}

Here is my web method for my .Net web service

 [WebMethod]
    public bool CreateFileFromBase64String(string _imageData, string _filename)
    {
        try
        {

            string path = @"C:\inetpub\wwwroot\web\";
            MemoryStream msf = new MemoryStream(Convert.FromBase64String(_imageData));
            Stream stem = new FileStream(path + _filename, FileMode.Create);
            msf.WriteTo(stem);
            msf.Flush();
            msf.Close();
            stem.Close();

            return true;
        }
        catch { return false; }
    }

I have this in my manifest. When I change the SDKVersion, it stops saving the file and still freezes. any recommendation.

<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

LogCat:

06-29 16:08:48.522: D/dalvikvm(8660): threadid=1: still suspended after undo (sc=1 dc=1) 06-29 16:10:26.225: D/AndroidRuntime(8660): Shutting down VM 06-29 16:10:26.225: W/dalvikvm(8660): threadid=1: thread exiting with uncaught exception (group=0x409c01f8) 06-29 16:10:26.292: E/AndroidRuntime(8660): FATAL EXCEPTION: main 06-29 16:10:26.292: E/AndroidRuntime(8660): java.lang.NullPointerException 06-29 16:10:26.292: E/AndroidRuntime(8660): at com.micsoftwares.iltc.GalleryRegister$UploadTask.onPostExecute(GalleryRegister.java:51) 06-29 16:10:26.292: E/AndroidRuntime(8660): at com.micsoftwares.iltc.GalleryRegister$UploadTask.onPostExecute(GalleryRegister.java:1) 06-29 16:10:26.292: E/AndroidRuntime(8660): at android.os.AsyncTask.finish(AsyncTask.java:602) 06-29 16:10:26.292: E/AndroidRuntime(8660): at android.os.AsyncTask.access$600(AsyncTask.java:156) 06-29 16:10:26.292: E/AndroidRuntime(8660): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615) 06-29 16:10:26.292: E/AndroidRuntime(8660): at android.os.Handler.dispatchMessage(Handler.java:99) 06-29 16:10:26.292: E/AndroidRuntime(8660): at android.os.Looper.loop(Looper.java:137) 06-29 16:10:26.292: E/AndroidRuntime(8660): at android.app.ActivityThread.main(ActivityThread.java:4424) 06-29 16:10:26.292: E/AndroidRuntime(8660): at java.lang.reflect.Method.invokeNative(Native Method) 06-29 16:10:26.292: E/AndroidRuntime(8660): at java.lang.reflect.Method.invoke(Method.java:511) 06-29 16:10:26.292: E/AndroidRuntime(8660): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 06-29 16:10:26.292: E/AndroidRuntime(8660): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 06-29 16:10:26.292: E/AndroidRuntime(8660): at dalvik.system.NativeStart.main(Native Method)

dejobo
  • 113
  • 8
  • Please use the debugger to check where it stuck and add the stacktrace of the UI thread to your question. If there are messages in the log (LogCat view), then you could post them as well. – Codo Jun 28 '12 at 07:45
  • stackTrace shows null and detailMessage shows "Fail to connect to camera service". – dejobo Jun 28 '12 at 18:44
  • You need to provide more information about the error. You have a detail message. So you obviously have an exception. Where does it occur? What kind of exception is it? Use the log facility to print the stack trace or wrap it in a RuntimeException and throw it so it gets automatically logged. – Codo Jun 28 '12 at 21:14
  • I have a RuntimeException; java.lang.RuntimeException: Fail to connect to camera service. Please give me an example of how to log this and also how to view the log. I am sorry but I am really new to eclipse IDE and android dev. Thanks, you are very helpful. – dejobo Jun 28 '12 at 23:43
  • First, you shouldn't swallow exceptions. Instead of using `printStackTrace()` do not catch the exception, or if it's a checked exception that needs to be caught, then use `throw new RuntimeException(e);`. The exception details including the full stacktrace will then be written to the log visible in the LogCat view of Eclipse. Add that relevant LogCat output to your question. If no exception is thrown, the run your app with the debugger. When the app doesn't react anymore, press the pause button in the Debug view and add a screen shot of the view with the main thread expanded. – Codo Jun 29 '12 at 10:26
  • I am not allowed to post images as I am a new user. Please do you an email I can send it to? I have also added the log from LogCat. I hope this helps. Thanks. – dejobo Jun 29 '12 at 15:51
  • I figured it out. Mainly because of you. I won't have found the issue if I never used throw new RuntimeException(e) and explaining how to use debug on eclipse. Thanks Codo, you are the man! – dejobo Jun 29 '12 at 16:23

1 Answers1

0

It seems you are uploading the file on the main UI thread. You should not do that and make yourself familiar with AsyncTask instead (which moves the heavy work into a separate thread).

tiguchi
  • 5,392
  • 1
  • 33
  • 39
  • A good recommendation but not the cause of the problem. And possibly not even a solution. – Codo Jun 28 '12 at 07:46
  • Codo is right. I am still getting the same problem. I am getting "Fail to connect to camera service" but i added permissions. – dejobo Jun 28 '12 at 18:46