Wednesday, July 11, 2012

Android Httpclient

In this tutorial I'm going to build a simple BMI calculator to show how we can post data to a URL using HTTP POST.

Here is the sample php code that you can use
<?php
       $userWeight = $_POST['weight'];
       $userHeight = $_POST['height'];
       $powerOfHeight = pow($userHeight,2);
       echo($userWeight/$powerOfHeight);
?>

Android activity
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class AndroidWebActivity extends Activity implements OnClickListener {
 Button calculate;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        calculate = (Button)findViewById(R.id.button1);
        calculate.setOnClickListener((OnClickListener) this);
    }
   
    public void bmi(){
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://codeincloud.tk/bmi.php");
     
        try{
     EditText weight = (EditText) findViewById(R.id.editText1);
     String myWeight = weight.getText().toString();
     
     EditText height = (EditText) findViewById(R.id.EditText01);
     String myHeight = height.getText().toString();
     
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
         nameValuePairs.add(new BasicNameValuePair("weight", myWeight));
         nameValuePairs.add(new BasicNameValuePair("height", myHeight));
         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
         HttpResponse response = httpclient.execute(httppost);
         
         String bmiResult = inputStreamToString(response.getEntity().getContent()).toString();
         TextView result = (TextView) findViewById(R.id.textView4);
         result.setText("Your BMI : "+bmiResult);
     }
     
        catch(Exception e){
      e.printStackTrace();
     }
    }
    
    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        
        try {
         while ((rLine = rd.readLine()) != null) {
          answer.append(rLine);
           }
        } 
        
        catch (IOException e) {
            e.printStackTrace();
         }
        return answer;
       }
    
    public void onClick(View view) {
        if(view == calculate){
         bmi();
        }
      }
}

Here is the code of main.xml used in above application

    
    
   
    
       
    
    
    
   
    

Add internet permission to the Manifest file


    
    

    
        
            
                

                
            
        
    


Click here download the Android project.

4 comments:

  1. Hello! I know this is kind of off topic but I was wondering which blog platform are you using for this website?
    I'm getting fed up of Wordpress because I've had problems with hackers and I'm looking at alternatives for another platform. I would be awesome if you could point me in the direction of a good platform.
    Feel free to surf my blog bmi calc

    ReplyDelete
  2. Its such as you learn my mind! You seem to grasp a lot about this, like you wrote the book in it or something.
    I feel that you just can do with a few % to drive the message home a bit, however instead of that, this is excellent blog. A fantastic read. I will definitely be back.
    Feel free to visit my weblog : how to lower bad cholesterol naturally

    ReplyDelete
  3. i run this project in my eclipse when i debugged the program it give me error in android.jar any attachment error....and after execute method it does not work.

    ReplyDelete
  4. i debug your code in my eclipse it give me error in android.jar any attachment error...and execute method in class is not execute ..pls help me asap

    ReplyDelete