Monday 27 May 2013

How to call Web Service from Android ?

This is first example about web service in android written by me.This will show you how android will communicate with remote server and fetch and send data to server.

List of things that is included in this post :

  • What is Web Service ?

  • How it's works?

  • How to Decode JSON?

  • How to create Custom Dialog ?

  • How to manage  AsyncTask ?

Note: I have wrote separate post of Custom Dialog and AsynTask So, i will not explain in depth.

What are Web Service ?

  • Web services are application components

  • Web services communicate using open protocols

  • Web services are self-contained and self-describing

  • Web services can be discovered using UDDI

  • Web services can be used by other applications

  • XML is the basis for Web services

How does it works ?

[caption id="" align="aligncenter" width="808"] How its' works ?[/caption]

How to Encode & Decode JSON in android?

Encode :
 
1
2
3
4
5
6
// Create JSON obj
JSONObject json = new JSONObject();
 
// encode your json value
json.put("user_name", "test");
json.put("password", "test123");
 
 

// Create JSON obj 
JSONObject json = new JSONObject();

// encode your json value 
json.put("user_name", "test");
json.put("password", "test123");


Decode

  • Decode JSON Object

  • Decode JSON Array

Decode Object 
 
1
2
JSONObject json_data = new JSONObject(response);
String value = json_data.getString("status");
 
 

JSONObject json_data = new JSONObject(response);
String value = json_data.getString("status");


Decode Array 
 
1
2
3
4
5
6
JSONArray jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++) {
    JSONObject json_data = jArray.getJSONObject(i);
    // add to list
    User_ID.add(json_data.getString("user_id"));
}
 
 

JSONArray jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++) {
    JSONObject json_data = jArray.getJSONObject(i);
    // add to list
    User_ID.add(json_data.getString("user_id"));
}


Now we are able to  encode and decode our value in JSON so now we are going to build android app that will
simply connect with server and send and receive simple value.

We have main five java files to maintain this app.

  • Android_WebService.java  [Task - Handle events and views]

  • AsyncTaskCompleteListener.java [Task - Interface for use response in other file]

  • Background_Task.java [Task - Manage Background task using  AsynTask]

  • Custom_alert_DialogClass.java [Task - Custom alert dialog to update UI]

  • Function.java [Task - All Global function and data member]

we are going to start with all one by one java file with comments so it would be easy to use and understand.

Android_WebService.java

This class will prepare the view and manage action like OnClick and Listener.Also we can say that this is root becasue reset of all other file are handleing in this class.
 
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
public class Android_WebService extends Activity implements
AsyncTaskCompleteListener {
 
    Function fun;
    Background_Task bTask;
    Button call_ws;
    String User_Name = null;
    String TAG = "Android_WebService_Error";
    ArrayList < String > User_Id = new ArrayList < String > ();
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Set_View();
 
        call_ws.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                try {
                    // check for internet connection
                    if (isNetworkAvailable() == true) {
 
                        // clear older parms value
                        fun.URL_Params.clear();
 
                        // add your params here
 
                        // fun.URL_Params.add(new
                        // BasicNameValuePair("key_value",""));
 
                        // pass your parms to constructor
                        bTask = new Background_Task(fun.URL_Params,
                            Android_WebService.this);
 
                        // show a message while loader is loading
                        fun.Alert_Msg = "Please Wait...\nWe are Authenticating your details";
                        fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);
 
                        // call web service in asyn class
                        bTask.execute("http://chintankhetiya.wordpress.com/");
 
                    } else {
                        fun.Alert_Msg = "Sorry..\n Try to connect Internet first.";
                        fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    fun.Alert_Msg = "Sorry..\n Try to connect internet first.";
                    fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);
                }
            }
        });
 
    }
 
    public void Call_My_Blog(View v) {
        Intent intent = new Intent(Android_WebService.this, My_Blog.class);
        startActivity(intent);
 
    }
 
    @Override
    public void onTaskComplete(String result) {
        // TODO Auto-generated method stub
        fun.Hide_Loader();
        if (result != null) {
 
            // call and edit below function as per your needs
            /*
             * Response_JSON_Object(result); Response_JSON_Array(result);
             */
 
            fun.Alert_Msg = "congrats ..\n You have create web-service example successfully.";
            fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);
 
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    fun.Hide_Loader(); // when the task active then close the
                    // dialog
                    t.cancel(); // also just top the timer thread,
                    // otherwise, you may receive a crash report
                }
            }, fun.Dialog_Time_Limit); // after 2 second (or 2000
            // miliseconds), the task will
            // be active.
 
        } else {
            fun.Alert_Msg = "Sorry..\n We are not able connect with Chintan Khetiya's Blog due to slow Internet Connction.\n Reset WI-FI or Try Later";
            fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);
 
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    fun.Hide_Loader(); // when the task active then close the
                    // dialog
                    t.cancel(); // also just top the timer thread,
                    // otherwise, you may receive a crash report
                }
            }, fun.Dialog_Time_Limit); // after 2 second (or 2000
            // miliseconds), the task will
            // be active.
 
        }
 
    }
 
    public String Response_JSON_Object(String Buffer_Response) {
        try {
            JSONObject json_data = new JSONObject(Buffer_Response);
            User_Name = json_data.getString("User_Name").toString();
            return User_Name;
        } catch (Exception e) {
            Log.e(TAG, "Json Object issue" + e);
        }
        return User_Name;
 
    }
 
    public ArrayList < String > Response_JSON_Array(String Buffer_Response) {
        try {
            JSONArray jArray = new JSONArray(Buffer_Response);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                // add to list
                User_Id.add(json_data.getString("user_id"));
            }
 
        } catch (Exception e) {
            // TODO: handle exception
            Log.e(TAG, "Json array issue" + e);
        }
        return User_Id;
    }
 
    public void Set_View() {
        fun = new Function(getApplicationContext());
        call_ws = (Button) findViewById(R.id.call);
 
    }
 
    public boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        // if no network is available networkInfo will be null
        // otherwise check if we are connected
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        }
        return false;
    }
}
 
 

public class Android_WebService extends Activity implements
AsyncTaskCompleteListener {

    Function fun;
    Background_Task bTask;
    Button call_ws;
    String User_Name = null;
    String TAG = "Android_WebService_Error";
    ArrayList < String > User_Id = new ArrayList < String > ();

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

        call_ws.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    // check for internet connection
                    if (isNetworkAvailable() == true) {

                        // clear older parms value
                        fun.URL_Params.clear();

                        // add your params here

                        // fun.URL_Params.add(new
                        // BasicNameValuePair("key_value",""));

                        // pass your parms to constructor
                        bTask = new Background_Task(fun.URL_Params,
                            Android_WebService.this);

                        // show a message while loader is loading
                        fun.Alert_Msg = "Please Wait...\nWe are Authenticating your details";
                        fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);

                        // call web service in asyn class
                        bTask.execute("http://chintankhetiya.wordpress.com/");

                    } else {
                        fun.Alert_Msg = "Sorry..\n Try to connect Internet first.";
                        fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    fun.Alert_Msg = "Sorry..\n Try to connect internet first.";
                    fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);
                }
            }
        });

    }

    public void Call_My_Blog(View v) {
        Intent intent = new Intent(Android_WebService.this, My_Blog.class);
        startActivity(intent);

    }

    @Override
    public void onTaskComplete(String result) {
        // TODO Auto-generated method stub
        fun.Hide_Loader();
        if (result != null) {

            // call and edit below function as per your needs
            /*
             * Response_JSON_Object(result); Response_JSON_Array(result);
             */

            fun.Alert_Msg = "congrats ..\n You have create web-service example successfully.";
            fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);

            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    fun.Hide_Loader(); // when the task active then close the
                    // dialog
                    t.cancel(); // also just top the timer thread,
                    // otherwise, you may receive a crash report
                }
            }, fun.Dialog_Time_Limit); // after 2 second (or 2000
            // miliseconds), the task will
            // be active.

        } else {
            fun.Alert_Msg = "Sorry..\n We are not able connect with Chintan Khetiya's Blog due to slow Internet Connction.\n Reset WI-FI or Try Later";
            fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);

            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    fun.Hide_Loader(); // when the task active then close the
                    // dialog
                    t.cancel(); // also just top the timer thread,
                    // otherwise, you may receive a crash report
                }
            }, fun.Dialog_Time_Limit); // after 2 second (or 2000
            // miliseconds), the task will
            // be active.

        }

    }

    public String Response_JSON_Object(String Buffer_Response) {
        try {
            JSONObject json_data = new JSONObject(Buffer_Response);
            User_Name = json_data.getString("User_Name").toString();
            return User_Name;
        } catch (Exception e) {
            Log.e(TAG, "Json Object issue" + e);
        }
        return User_Name;

    }

    public ArrayList < String > Response_JSON_Array(String Buffer_Response) {
        try {
            JSONArray jArray = new JSONArray(Buffer_Response);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                // add to list
                User_Id.add(json_data.getString("user_id"));
            }

        } catch (Exception e) {
            // TODO: handle exception
            Log.e(TAG, "Json array issue" + e);
        }
        return User_Id;
    }

    public void Set_View() {
        fun = new Function(getApplicationContext());
        call_ws = (Button) findViewById(R.id.call);

    }

    public boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        // if no network is available networkInfo will be null
        // otherwise check if we are connected
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        }
        return false;
    }
}


AsyncTaskCompleteListener.java

This is separate class to handle incoming parmas value form root class and run task in background thread.
It will redirect when task will complete.
 
1
2
3
4
public interface AsyncTaskCompleteListener {
    // it will call when background process finish
    public void onTaskComplete(String result);
}
 
 

public interface AsyncTaskCompleteListener {
    // it will call when background process finish
    public void onTaskComplete(String result);
}


Background_Task.java
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
public class Background_Task extends AsyncTask {
 
    public Activity activity;
    Context context;
    public AsyncTaskCompleteListener callback;
    ArrayList URL_Params = new ArrayList();
    Function fun = new Function();
    ProgressDialog Loader_Dialog;
    Custom_alert_DialogClass cad;
 
    public Background_Task(ArrayList URL_Params, Activity act) {
        this.URL_Params = URL_Params;
 
        this.activity = act;
        this.callback = (AsyncTaskCompleteListener) act;
    }
 
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        try {
 
            Log.i("onPre", "call");
        } catch (Exception e) {
            // TODO: handle exception
            Log.e("onPre", "" + e);
        }
 
    }
 
    @Override
    protected String doInBackground(String...web_url) {
        try {
            // this will send req in post
            // here [0] mean URL & passing params
            Log.i("onDO", "call");
 
            fun.Send_Simple_Detail_To_Server(web_url[0], URL_Params);
 
            Log.i("onDO", "SEND");
 
            // this will get stream response
            fun.Buffer_Response();
            Log.i("onDO", "GET RES");
 
        } catch (Exception e) {
            // TODO: handle exception
            Log.e("onDo", "" + e);
        }
 
        return fun.Buffer_String_Response;
    }
 
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // check is dialog open ? THEN HIDE DIALOG
        try {
            Log.i("onPOST", "DONE");
            Log.i("onPOST", "" + result);
 
            callback.onTaskComplete(result);
        } catch (Exception e) {
            Log.e("onPost", "" + e);
            // TODO: handle exception
        }
 
    }
 
}
 
 

public class Background_Task extends AsyncTask {

    public Activity activity;
    Context context;
    public AsyncTaskCompleteListener callback;
    ArrayList URL_Params = new ArrayList();
    Function fun = new Function();
    ProgressDialog Loader_Dialog;
    Custom_alert_DialogClass cad;

    public Background_Task(ArrayList URL_Params, Activity act) {
        this.URL_Params = URL_Params;

        this.activity = act;
        this.callback = (AsyncTaskCompleteListener) act;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        try {

            Log.i("onPre", "call");
        } catch (Exception e) {
            // TODO: handle exception
            Log.e("onPre", "" + e);
        }

    }

    @Override
    protected String doInBackground(String...web_url) {
        try {
            // this will send req in post
            // here [0] mean URL & passing params
            Log.i("onDO", "call");

            fun.Send_Simple_Detail_To_Server(web_url[0], URL_Params);

            Log.i("onDO", "SEND");

            // this will get stream response
            fun.Buffer_Response();
            Log.i("onDO", "GET RES");

        } catch (Exception e) {
            // TODO: handle exception
            Log.e("onDo", "" + e);
        }

        return fun.Buffer_String_Response;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // check is dialog open ? THEN HIDE DIALOG
        try {
            Log.i("onPOST", "DONE");
            Log.i("onPOST", "" + result);

            callback.onTaskComplete(result);
        } catch (Exception e) {
            Log.e("onPost", "" + e);
            // TODO: handle exception
        }

    }

}


Custom_alert_DialogClass.java

Custom Dialog to updating UI status so user get notify that what is going on.
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class Custom_alert_DialogClass extends Dialog {
 
    public Activity a;
    public String Msg;
    public Dialog d;
    public Button no;
    public Context context;
    public TextView alert_infromation_text;
    ProgressBar pb;
    LinearLayout exit_layout;
 
    public Custom_alert_DialogClass(Activity a, String Msg) {
        super(a);
        // TODO Auto-generated constructor stub
        this.a = a;
        this.Msg = Msg;
 
    }
 
    /**
     * Constructor for Custom_alert_DialogClass.java Called for initializing
     * object of Custom_alert_DialogClass.java.
     *
     * @param function
     * @param alert_Msg
     */
    public Custom_alert_DialogClass(Context c, String alert_Msg) {
        // TODO Auto-generated constructor stub
 
        super(c);
        this.context = c;
        this.Msg = alert_Msg;
 
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.custom_alert_dialog);
        Create_Alert_DialogView();
 
        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dismiss();
 
                a.finish();
 
            }
        });
 
    }
 
    public void Create_Alert_DialogView() {
 
        no = (Button) findViewById(R.id.Dailog_Exit);
        exit_layout = (LinearLayout) findViewById(R.id.exit_layout);
        exit_layout.setVisibility(View.GONE);
        alert_infromation_text = (TextView) findViewById(R.id.alert_infromation_text);
        alert_infromation_text.setText(Msg);
        pb = (ProgressBar) findViewById(R.id.progressBar1);
        no.setVisibility(View.GONE);
    }
 
}
 
 

public class Custom_alert_DialogClass extends Dialog {

    public Activity a;
    public String Msg;
    public Dialog d;
    public Button no;
    public Context context;
    public TextView alert_infromation_text;
    ProgressBar pb;
    LinearLayout exit_layout;

    public Custom_alert_DialogClass(Activity a, String Msg) {
        super(a);
        // TODO Auto-generated constructor stub
        this.a = a;
        this.Msg = Msg;

    }

    /**
     * Constructor for Custom_alert_DialogClass.java Called for initializing
     * object of Custom_alert_DialogClass.java.
     * 
     * @param function
     * @param alert_Msg
     */
    public Custom_alert_DialogClass(Context c, String alert_Msg) {
        // TODO Auto-generated constructor stub

        super(c);
        this.context = c;
        this.Msg = alert_Msg;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.custom_alert_dialog);
        Create_Alert_DialogView();

        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dismiss();

                a.finish();

            }
        });

    }

    public void Create_Alert_DialogView() {

        no = (Button) findViewById(R.id.Dailog_Exit);
        exit_layout = (LinearLayout) findViewById(R.id.exit_layout);
        exit_layout.setVisibility(View.GONE);
        alert_infromation_text = (TextView) findViewById(R.id.alert_infromation_text);
        alert_infromation_text.setText(Msg);
        pb = (ProgressBar) findViewById(R.id.progressBar1);
        no.setVisibility(View.GONE);
    }

}


Function.java

All data member and function are written here so it will easy to execute and understand.
 
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
public class Function {
    public ConnectivityManager cm;
    public NetworkInfo ni;
    public InputStream is;
    Context ctx;
    JSONObject jObjec = new JSONObject();
    String Buffer_String_Response = null;
    Custom_alert_DialogClass cad;
    public ArrayList URL_Params = new ArrayList();
    String Alert_Msg;
    long Dialog_Time_Limit = 3000;
 
    public Function(Context context) {
        this.ctx = context;
    }
 
    public Function() {
 
    }
 
    public void Send_JSON_Encode_Detail_To_Server(String URL, JSONObject jobj) {
        try {
 
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(URL);
            httppost.setHeader("Content-type", "application/json");
            StringEntity se = new StringEntity(jobj.toString());
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
            httppost.setEntity(se);
            HttpResponse response = httpclient.execute(httppost);
            String temp = EntityUtils.toString(response.getEntity());
            Log.i("tag", temp);
 
        } catch (ConnectTimeoutException e) {
            Log.e("Timeout Exception: ", e.toString());
 
        } catch (SocketTimeoutException ste) {
            Log.e("Timeout Exception: ", ste.toString());
 
        } catch (Exception e) {
            Log.e("HTTP_Execption", "Error in http connection " + e.toString());
 
        }
    }
 
    public void Send_Simple_Detail_To_Server(String URL,
        ArrayList nameValuePairs)
 
    {
        try {
 
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(URL);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
 
            is = entity.getContent();
 
        } catch (ConnectTimeoutException e) {
            Log.e("Timeout Exception: ", e.toString());
 
        } catch (SocketTimeoutException ste) {
            Log.e("Timeout Exception: ", ste.toString());
 
        } catch (Exception e) {
            Log.e("HTTP_Execption", "Error in http connection " + e.toString());
 
        }
    }
 
    public void Buffer_Response() {
        try {
            Buffer_String_Response = null;
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            Buffer_String_Response = sb.toString();
 
        } catch (Exception e) {
            Log.e("Loading Runnable Error converting result :", e.toString());
 
        }
 
    }
 
    public void Show_Loader(Activity a, String Text_Message) {
 
        cad = new Custom_alert_DialogClass(a, Text_Message);
        cad.show();
    }
 
    public void Hide_Loader()
 
    {
        if (cad != null && cad.isShowing()) {
            cad.dismiss();
        }
 
    }
 
}
 
 

public class Function {
    public ConnectivityManager cm;
    public NetworkInfo ni;
    public InputStream is;
    Context ctx;
    JSONObject jObjec = new JSONObject();
    String Buffer_String_Response = null;
    Custom_alert_DialogClass cad;
    public ArrayList URL_Params = new ArrayList();
    String Alert_Msg;
    long Dialog_Time_Limit = 3000;

    public Function(Context context) {
        this.ctx = context;
    }

    public Function() {

    }

    public void Send_JSON_Encode_Detail_To_Server(String URL, JSONObject jobj) {
        try {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(URL);
            httppost.setHeader("Content-type", "application/json");
            StringEntity se = new StringEntity(jobj.toString());
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
            httppost.setEntity(se);
            HttpResponse response = httpclient.execute(httppost);
            String temp = EntityUtils.toString(response.getEntity());
            Log.i("tag", temp);

        } catch (ConnectTimeoutException e) {
            Log.e("Timeout Exception: ", e.toString());

        } catch (SocketTimeoutException ste) {
            Log.e("Timeout Exception: ", ste.toString());

        } catch (Exception e) {
            Log.e("HTTP_Execption", "Error in http connection " + e.toString());

        }
    }

    public void Send_Simple_Detail_To_Server(String URL,
        ArrayList nameValuePairs)

    {
        try {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(URL);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();

            is = entity.getContent();

        } catch (ConnectTimeoutException e) {
            Log.e("Timeout Exception: ", e.toString());

        } catch (SocketTimeoutException ste) {
            Log.e("Timeout Exception: ", ste.toString());

        } catch (Exception e) {
            Log.e("HTTP_Execption", "Error in http connection " + e.toString());

        }
    }

    public void Buffer_Response() {
        try {
            Buffer_String_Response = null;
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            Buffer_String_Response = sb.toString();

        } catch (Exception e) {
            Log.e("Loading Runnable Error converting result :", e.toString());

        }

    }

    public void Show_Loader(Activity a, String Text_Message) {

        cad = new Custom_alert_DialogClass(a, Text_Message);
        cad.show();
    }

    public void Hide_Loader()

    {
        if (cad != null && cad.isShowing()) {
            cad.dismiss();
        }

    }

}


Don't forget to update your manifest with Permission
 
1
2
uses - permission android: name = "android.permission.INTERNET"
uses - permission android: name = "android.permission.ACCESS_NETWORK_STATE
 
 

uses - permission android: name = "android.permission.INTERNET"
uses - permission android: name = "android.permission.ACCESS_NETWORK_STATE


Get Full Source code 

GitHub-download

18 comments:

  1. Prajwal Ravishankar23 January 2014 at 01:20

    Excellent

    ReplyDelete
  2. it's very helpful. The source code download link is not available, please email me the link if you have.
    Thanks

    ReplyDelete
  3. nicely explained....if u dnt mind can u tell how i can connect android with ms sql database using webservice

    ReplyDelete
  4. Thank you very very much for this code...

    ReplyDelete
  5. You have to learn how to create web service in php using mysql database. Try to Google there are lots of example available.

    ReplyDelete
  6. You can get all example in my Github account https://github.com/khetiyachintan :)

    ReplyDelete
  7. Thanks a lot for this tutorial.. But, can you tell me how to fetch the Database which is located on company server by calling the provided web service ? How can i show database located on server in android mobile ?

    ReplyDelete
  8. i want to connect my sql server to android without using php code. is any possibility are there please tell me

    ReplyDelete
  9. how you will connect your database ? you can't.

    ReplyDelete
  10. i want to connect matlab to android app.is their any way to do this?

    ReplyDelete
  11. How can i store my values in SQL server in android?

    ReplyDelete
  12. Rohit shrivastava26 March 2015 at 22:50

    sir you are Genious...

    ReplyDelete
  13. How i can connect android with sql server database using webservice

    ReplyDelete
  14. Hi, For that you need to learn how to call web service and access remote database.

    ReplyDelete
  15. can i ask qstn i can't learn android till is it possible as fresher to call the web services in android

    ReplyDelete
  16. actually you can but it is not advisable.
    It is better, for security reason, to use web services to connect to you sql server. This does not have to necessarily be in php. You can you C# etc

    ReplyDelete