0

I wrote Android client like this:

Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tests.com.myapplication">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- other codes.... -->

Activity class

public class Registration extends ActionBarActivity {
    /***************** local variables ******************/
    int gun, ay, il;
    Button submit, clear;
    TextView profile_pic, birthday;
    EditText username, password, name, surname, graduated_from, graduated_in, born_place;
    ImageView imageview;
    private String convertedImage = null;
    private byte[] inputData = null;
    /***************** local variables ******************/

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


    /***************** get values from view elements ******************/
    submit = (Button) findViewById(R.id.submit);
    clear = (Button) findViewById(R.id.clear);
    username = (EditText) findViewById(R.id.username);
    password = (EditText) findViewById(R.id.password);
    name = (EditText) findViewById(R.id.name);
    surname = (EditText) findViewById(R.id.surname);
    graduated_from = (EditText) findViewById(R.id.graduated_from);
    graduated_in = (EditText) findViewById(R.id.graduated_in);
    born_place = (EditText) findViewById(R.id.born_place);
    birthday = (TextView) findViewById(R.id.birthday);
    profile_pic = (TextView) findViewById(R.id.profile_pic);
    imageview = (ImageView) findViewById(R.id.imageView);
    /***************** get values from view elements ******************/


    /***************** set calendar to current date ******************/
    final Calendar calendar = Calendar.getInstance();
    gun = calendar.get(Calendar.DATE);
    ay = calendar.get(Calendar.MONTH);
    il = calendar.get(Calendar.YEAR);
    calendar.setFirstDayOfWeek(Calendar.MONDAY);
    /***************** set calendar to current date ******************/


    View.OnClickListener button_click = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.submit: // "Submit" button
                    String istiad = username.getText().toString();
                    String sifre = password.getText().toString();
                    String ad = name.getText().toString();
                    String soyad = surname.getText().toString();
                    String bitirdiyi_mekteb = graduated_from.getText().toString();
                    String bitirdiyi_il = graduated_in.getText().toString();
                    String dogum_yeri = born_place.getText().toString();
                    String dogum_ili = birthday.getText().toString();
                    String profile_pic = convertedImage;

    // construct URL for async task
                    String URL = "http://localhost/wcf/Service.svc/register/" + istiad + "/" + sifre + "/" + ad + "/" + soyad + "/" + bitirdiyi_mekteb + "/" + bitirdiyi_il + "/" + dogum_yeri + "/" + dogum_ili; //+ "/" + profile_pic;
                    // call WebService
                    new HttpAsyncTask().execute(URL);
                    break;
                case R.id.clear:  // "Clear" button
                    ViewGroup group = (ViewGroup) findViewById(R.id.form);
                    clearForm(group);
                    break;
                case R.id.birthday: // "birthday" TextView
                    showDialog(0);
                    break;
                case R.id.profile_pic: // "profile_pic" TextView
                    getImage();
                    break;
            }
        }

    };

    submit.setOnClickListener(button_click);
    clear.setOnClickListener(button_click);
    birthday.setOnClickListener(button_click);
    profile_pic.setOnClickListener(button_click);
    }

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

    switch (requestCode) {
            case 0:
                if (resultCode == RESULT_OK) {
                    Uri selectedImage = imageReturnedIntent.getData();

    imageview.setImageURI(selectedImage);

    Bitmap bitmap = ((BitmapDrawable) imageview.getDrawable()).getBitmap();
                    convertedImage = Base64.encodeToString(getBytesFromBitmap(bitmap), Base64.URL_SAFE);
                    name.setText(convertedImage);
                }
                break;
        }
    }

    public byte[] getBytesFromBitmap(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        return stream.toByteArray();
    }

    public static String GET(String URL) {
        String result = "";

    try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(URL);
            HttpResponse response;
            try {
                response = httpclient.execute(httpget);
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            result = e.getLocalizedMessage();
        }
        return result;
    }


    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            return GET(urls[0]);
        }

    @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Done!", LENGTH_LONG).show();
        }
    }
}

As you see, with these Java codes I'm getting values from EditTexts, TextView's and etc. And I'm calling the web service method using the URL below. And then the web service method (should) inserts the incoming data to database. I'm having trouble about sending the image to web service. Because, the length of URL is longer than 100.000 chars...

I think this method (calling URL in android app) is not useful.

The web service codes:

IService.cs

namespace WebService
{
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/register/{username}/{password}/{name}/{surname}/{graduated_from}/{graduated_in}/{born_place}/{birthday}/{profile_pic}")]
        string register(string username, string password, string name, string surname, string graduated_from, string graduated_in, string born_place, string birthday, string profile_pic);     
    }
}

Service.svc.cs

namespace WebService
{
    public class Service : IService
    {
        private static MySqlConnection connection = new MySqlConnection("server=45.35.4.29;uid=root;password=connection;database=db_webservice");

        // http://stackoverflow.com/q/472906
        // http://stackoverflow.com/q/1003275
        // http://stackoverflow.com/q/10513976
        public class Convert
        {
            public static byte[] ConvertToBytes (string str)
            {
                byte[] bytes = new byte[str.Length * sizeof(char)];
                Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);

                return bytes;
            }

            public static string ConvertToString (byte[] bytes)
            {
                char[] chars = new char[bytes.Length / sizeof(char)];
                Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);

                return new string(chars);
            }
        }


        // https://youtu.be/iqrY9IaUY24
        // https://youtu.be/AMH4plUP0uo
        public string register (string username, string password, string name, string surname, string graduated_from, string graduated_in, string born_place, string birthday) //, string profile_pic)
        {
            bool result = false;

            string query_insert = @"INSERT INTO users(username, password, name, surname, graduated_from, graduated_in, born_place, birthday) VALUES( ' " + username + " ', ' " + password + " ', ' " + name + " ', ' " + surname + " ', ' " + graduated_from + " ', ' " + graduated_in + " ', ' " + born_place + " ', ' " + birthday + " ' );";

            if (connection.State == ConnectionState.Closed)
                connection.Open();

            using (MySqlCommand insert = new MySqlCommand(query_insert, connection))
            {
                insert.ExecuteNonQuery();
                result = true;
            }

            if (result)
                return "success";
            else
                return "fail";
        }
    }
}

Any comment and/or answer will be appreciated!

Thanks. :)

Mirjalal
  • 1,292
  • 1
  • 17
  • 40

1 Answers1

0

To upload an image from android device to remote server you can use the below code.

HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 200000);
    String resFromServer = "";
    HttpResponse response;

    HttpPost httppost = new HttpPost(api_url);
    File file = new File(imagePath);
    ContentBody cbFile = new FileBody(file, "image/jpeg");
    try {
        MultipartEntity reqEntity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("user_profile_image", cbFile);
        httppost.setEntity(reqEntity);
        httppost.addHeader("enctype", "multipart/form-data");
        String base64EncodedCredentials = Base64.encodeToString(
                credentials.getBytes(), Base64.NO_WRAP);
        httppost.addHeader("Authorization", "Basic "
                + base64EncodedCredentials);

        response = client.execute(httppost);
        resFromServer = org.apache.http.util.EntityUtils.toString(response
                .getEntity());
    }catch(Exception exp){
     exp.printStack();
    }

import org.apache.http.entity.mime.content.ContentBody ,org.apache.http.entity.mime.content.FileBody packages to implement it.For that you have to include following jar files to your project

apache-mime4j-0.6.jar httpmime-4.1-beta1.jar

Jinosh P
  • 341
  • 2
  • 8
  • thanks! what's the `ContentBody` and `FileBody` classes? – Mirjalal Jul 04 '15 at 11:48
  • import org.apache.http.entity.mime.content.ContentBody ,org.apache.http.entity.mime.content.FileBody packages to implement it.For that you have to include following jar files to your project.I updated the answer – Jinosh P Jul 05 '15 at 04:53
  • can you explain please what's the wrong in my android application? and why? thanks. – Mirjalal Jul 05 '15 at 05:53