Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Post any data using POST Method in Android

Please tell me where to place the code.

I am creating an app to,

  1. Get location,
  2. When location is got,And the Post button is clicked,
  3. Quickly, Send it using POST (HTTP) Method to my PHP page.

As In Below App Screenshot, you can see two input box with LAT & LONG & Name values:

Screen Shot

I have the following code to get location:

public class MainActivity extends Activity implements LocationListener {
EditText lat;
EditText lng;

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

    /********** get Gps location service LocationManager object ***********/

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

            /* CAL METHOD requestLocationUpdates */

    // Parameters :
    //   First(provider)    :  the name of the provider with which to register
    //   Second(minTime)    :  the minimum time interval for notifications,
    //                         in milliseconds. This field is only used as a hint
    //                         to conserve power, and actual time between location
    //                         updates may be greater or lesser than this value.
    //   Third(minDistance) :  the minimum distance interval for notifications, in meters
    //   Fourth(listener)   :  a {#link LocationListener} whose onLocationChanged(Location)
    //                         method will be called for each location update


    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
            3000,   // 3 sec
            10, this);

    /********* After registration onLocationChanged method  ********/
    /********* called periodically after each 3 sec ***********/
}

/************* Called after each 3 sec **********/
@Override
public void onLocationChanged(Location location) {

    lat = (EditText)findViewById(R.id.lat);
    lng = (EditText)findViewById(R.id.lng);
    lat.setText(""+location.getLatitude());
    lng.setText(""+location.getLongitude());

    String str = "Latitude: "+location.getLatitude()+"Longitude: "+location.getLongitude();

    Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
}


@Override
public void onProviderDisabled(String provider) {

    /******** Called when User off Gps *********/

    Toast.makeText(getBaseContext(), "GPS is OFF, Turn it on", Toast.LENGTH_LONG).show();
}

@Override
public void onProviderEnabled(String provider) {

    /******** Called when User on Gps  *********/

    Toast.makeText(getBaseContext(), "GPS ON ", Toast.LENGTH_LONG).show();
    Toast.makeText(getBaseContext(), "Waiting for location..... ", Toast.LENGTH_LONG).show();
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}




@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}    

That was the code to get location and fill LAT & LONG values to an input box, When GPS gets a fix.

Now, I need the code for POSTing all datas it into my PHP Page.

like image 689
Ravi Avatar asked Oct 19 '22 14:10

Ravi


1 Answers

If it helps you. It is not the whole thing you need proper async task to run following code. I hope you know that to enable permission in manifest for network. i.e.:

<uses-permission android:name="android.permission.INTERNET" />

HttpResponse YourMethod(String data,String url){       

     // Create a new HttpClient and Post Header
       HttpClient httpClient= new DefaultHttpClient();
        HttpResponse response = null;
        HttpConnectionParams.setSoTimeout(httpClient.getParams(), 60000);
        HttpPost httpPost = new HttpPost(url);
        StringEntity se = new StringEntity(data,"UTF-8"); 
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"text/html"));
        httpPost.setEntity(se);

        response = httpClient.execute(httpPost);

     }

Now data is the String where you need to send the data of lat long

There is another way to send data to your server

   public HttpResponse YourMethod(String lat,String lon,Strig url) {
         HttpResponse response =null;
           // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new    HttpPost(url);

     try {

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair(<lat key from php>, lat));
    nameValuePairs.add(new BasicNameValuePair(<lat key from php>, lon));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


    HttpResponse response = httpclient.execute(httppost);

     } catch (Exception e) {

   }
    finally{
       return response 
      }

 } 
like image 107
Koushik Avatar answered Oct 22 '22 07:10

Koushik