Dec 7, 2011

How to send Post data to PHP server in android

public boolean PostData() {
try {
// creating default Client
HttpClient mClient = new DefaultHttpClient();
// Connect URL
StringBuilder sb=new StringBuilder("URL_OF_WEB_SERVER");
// Establishing post connection to Specified URL
HttpPost mpost = new HttpPost(sb.toString());
// NameValuePair : A simple class encapsulating an attribute/value pair.
// List Size is 8 atributes
List nameValuepairs = new ArrayList(8);
// adding attributes to List
nameValuepairs.add(new BasicNameValuePair(name1,val1));
nameValuepairs.add(new BasicNameValuePair(name2,val2));
nameValuepairs.add(new BasicNameValuePair(name3,val3));
nameValuepairs.add(new BasicNameValuePair(name3,val3));
nameValuepairs.add(new BasicNameValuePair(name4,val4);
nameValuepairs.add(new BasicNameValuePair(name5,val5));
nameValuepairs.add(new BasicNameValuePair(name6,val6);
nameValuepairs.add(new BasicNameValuePair(name7,val7));
// UrlEncodedFormEntity :An entity composed of a list of url-encoded pairs. This is typically
// useful while sending an HTTP POST request.
mpost.setEntity(new UrlEncodedFormEntity(nameValuepairs));
// excute request and get response
HttpResponse responce = mClient.execute(mpost);
// get response content
HttpEntity entity = responce.getEntity();
// convert stream to String
BufferedReader buf = new BufferedReader(new InputStreamReader(entity.getContent()));
StringBuilder sb1 = new StringBuilder();
String line = null;
while ((line = buf.readLine()) != null) {
sb1.append(line+"\n");
}
Toast.makeText(getApplicationContext(), sb1.toString()+"",1).show();
tv.setText(sb1.toString());
isPosted = true;
} catch (UnsupportedEncodingException e) {
Log.w(" error ", e.toString());
} catch (Exception e) {
Log.w(" error ", e.toString());
}
return isPosted;
}

Retain ( Get 2 ) precision with Doubles in java

private void getRound() {
// this is very simple and interesting
double a = 5, b = 3, c;
c = a / b;
System.out.println(" round val is " + c);

// round val is : 1.6666666666666667
// if you want to only two precision point with double we
// can use formate option in String
// which takes 2 parameters one is formte specifier which
// shows dicimal places another double value
String s = String.format("%.2f", c);
double val = Double.parseDouble(s);
System.out.println(" val is :" + val);
// now out put will be : val is :1.67
}