0

i am sending image from android studio to wcf service both codes are correct and when i click on sendToServer button the app gone crashed. i don't know what is wrong with my code. here is the code for MainActivity.java

public class MainActivity extends AppCompatActivity 
{
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       StrictMode.ThreadPolicy policy = new 
     StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        private static final int CAMERA_REQUEST = 1888;
        private int PICK_IMAGE_REQUEST = 1;
        public PlaceholderFragment() {
        }
        private final static String SERVICE_URI = "http://localhost:24895/WcfAndroidImageService/WcfAndroidImageService.svc";
        ImageView imageView = null;
        byte[] photoasbytearray = null;
        Photo ph = null;
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
                Bitmap photo = (Bitmap) data.getExtras().get("data");


                imageView.setImageBitmap(photo);

                //getting photo as byte array
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                photo.compress(Bitmap.CompressFormat.JPEG, 100,stream);
                photoasbytearray = stream.toByteArray();

                //give a name of the image here as date
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HHmm");
                String currentDateandTime = sdf.format(new Date());

                ph = new Photo();

                String encodedImage = Base64.encodeToString(photoasbytearray,Base64.DEFAULT);
                ph.photoasBase64=encodedImage;

                ph.photoName= currentDateandTime+".png";
            }
        }


        private void SendToServer(Photo ph2) throws UnsupportedEncodingException {
            // TODO Auto-generated method stub
            HttpPost httpPost = new HttpPost(SERVICE_URI+"LoadPhoto");

            httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
            HttpClient httpClient = new DefaultHttpClient(getHttpParameterObj(17000,17000));
            // Building the JSON object.

            com.google.gson.Gson gson = new GsonBuilder().disableHtmlEscaping().create();
            String json = gson.toJson(ph2);
            StringEntity entity = new StringEntity(json,"UTF_8");
            Log.d("WebInvoke", "data : " + json);
            httpPost.setEntity(entity);
            // Making the call.
            HttpResponse response = null;
            try
            {
                response = httpClient.execute(httpPost);

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                Log.d("Exception",e.toString());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // Getting data from the response to see if it was a success.
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()
                        ));
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block

                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.d("IO_Exception",e.toString());
            }
            String jsonResultStr = null;
            try {
                jsonResultStr = reader.readLine();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Log.d("WebInvoke", "donnen  deger : " + jsonResultStr);
        }



        private HttpParams getHttpParameterObj(int timeOutConnection, int timeOutSocket)
        {
            HttpParams httpParameters = new BasicHttpParams();
            // Set the timeout in milliseconds until a connection is established.
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeOutConnection);
            // Set the default socket timeout (SO_TIMEOUT)
            // in milliseconds which is the timeout for waiting for data.
            HttpConnectionParams.setSoTimeout(httpParameters, timeOutSocket);
            return httpParameters;
        }



        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.activity_photo, container,
                    false);
            imageView  = (ImageView)rootView.findViewById(R.id.imageView1);
            Button btnOpenCam = (Button) rootView.findViewById(R.id.btnOpenCam);
            Button btnSendServer = (Button) rootView.findViewById(R.id.btnSendServer);
            Button btnOpenImage = (Button)rootView.findViewById(R.id.openImage);

            btnOpenCam.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Start camera activity here
                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);
                }
            });
            btnOpenImage.setOnClickListener(new View.OnClickListener() {


                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    // Show only images, no videos or anything else
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                     // Always show the chooser (if there are multiple options available)
                    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
                }
            });

            btnSendServer.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    try {
                        SendToServer(ph);
                       // Toast.makeText(getActivity(),"Image Sent to Server!", Toast.LENGTH_SHORT).show();
                        //Toast.makeText(getActivity(),"Server got the image!", Toast.LENGTH_SHORT).show();
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            });
            return rootView;
        }
    }
}

here is Photo.java

package com.example.haier.leafclassification;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Photo {
    public String  photoasBase64;
    public String photoName ;
}

On the server end here is IWcfAndroidImageService.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfAndroidPhotoServis
{
    [ServiceContract]
    public interface IWcfAndroidImageService
    {
        [OperationContract]
        [WebInvoke(Method = "POST",
                RequestFormat = WebMessageFormat.Json,
                ResponseFormat = WebMessageFormat.Json,
            // BodyStyle = WebMessageBodyStyle.Wrapped,
                UriTemplate = "LoadPhoto")]
        string LoadPhoto(Photo photo);

    }
}

And here is the WcfAndroidImageService.svc file code

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using WcfAndroidPhotoServis.Helper;

namespace WcfAndroidPhotoServis
{
    public class WcfAndroidImageService : IWcfAndroidImageService
    {

        public string LoadPhoto(Photo photo)
        {

            //get photofolder path
            string photofolderName = "LoadedPhotos";
            string photopath = "";
            photopath = System.Web.Hosting.HostingEnvironment.MapPath("~/"+photofolderName);
            //convert byte array to image
            Image _photo = ImageHelper.Base64ToImage(photo.photoasBase64);
            photopath = photopath + "/" + photo.photoName;
            //save photo to folder

            _photo.Save(photopath);
            //chech if photo saved correctlly into folder
            bool result = File.Exists(photopath);
           // string result = "Server got the image!";
            return result.ToString();
        }

    }

    [DataContract]
    public class Photo
    {
        //device id
        [DataMember]
        public string photoasBase64 { get; set; }

        [DataMember]
        public string photoName { get; set; }

    }
}

here is the message i got in the main activity log

W/System.err: org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:24895 refused

and here are the three line numbers main activity log is showing

java.lang.NullPointerException: Attempt to invoke interface method 'org.apache.http.HttpEntity org.apache.http.HttpResponse.getEntity()' on a null object reference
                      at com.example.haier.leafclassification.MainActivity$PlaceholderFragment.SendToServer(MainActivity.java:378)
                      at com.example.haier.leafclassification.MainActivity$PlaceholderFragment.access$100(MainActivity.java:293)
                      at com.example.haier.leafclassification.MainActivity$PlaceholderFragment$3.onClick(MainActivity.java:463)

and these lines have the following code

Line 378: reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()
Line 293:   public static class PlaceholderFragment extends Fragment {

Line 463:   SendToServer(ph);
Junaid Bashir
  • 152
  • 3
  • 15
  • Possible duplicate of [Unfortunately MyApp has stopped. How can I solve this?](http://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) – Vladyslav Matviienko Apr 26 '17 at 12:36
  • We have no context here. What does the app do, what is it not doing, what does the stack trace show, and how do we reproduce the problem? To work it out from your question would mean reading the code in its entirity, and compiling it locally then testing it. Knowning nothing about your environment or aims makes it very difficult to help. People on SO are usually incredibly helpful, but you need to meet them half way by poviding enough detail. – Alex Apr 26 '17 at 13:02
  • i have edited my post now check it. i have mentioned the errors i have getting in main activity log block. – Junaid Bashir Apr 26 '17 at 13:35

0 Answers0