Here is my method to connect to server and get the response in MyUtilitiesActivity (timeout code based on this answer by kuester2000).
private static response = "";
public static String send(final Activity act, final String url, final String keys[], final String values[])
{
try{
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
if(keys == null && values == null)
{
HttpGet get = new HttpGet(url);
// Execute HTTP Get Request
response = httpclient.execute(get, new BasicResponseHandler()).trim();
}
else if(keys != null && values != null && keys.length == values.length)
{
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (int i = 0; i < values.length; i++)
{
nameValuePairs.add(new BasicNameValuePair(keys[i], values[i]));
}
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(post, new BasicResponseHandler()).trim();
}
}
catch (Exception e)
{
response = e + "";
e.printStackTrace();
}
return response ;
}
And i'am calling the above method on click of a button in MyTestActivity.
public onClick(View v)
{
String response = MyUtilitiesActivity.send(MyTestActivity.this, "http://www.google.com", null, null);
//the code to be execute after getting the response from server
}
Where do i display the progress bar? Inside onclick of a button or inside send() method? How to display it ? Please help me.
Use AsyncTask concept which is known as Painless Threading in Android.
doInBackGround()
onPostExecute()
.