Unable to send GPS coordinates to server - java

I am trying to send GPS coordinates to server got by my app,it is showing GPS coordinates correctly, but unable to send it to server, the problem is in my MainActivity.java
Here is my code
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
int lat,lng;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_location);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
lat = (int) (location.getLatitude());
lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
private class LoadServerASYNC extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return null;
}
void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://182.18.144.140:80"); //your php file path
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("lat", "1.0256"));
nameValuePairs.add(new BasicNameValuePair("lng", "1.0256"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
I am not getting what is the problem

You are not initializing and executing the LoadServerAsync anywhere.
If you want to send coordinates every time you update the text views, you should do this:
#Override
public void onLocationChanged(Location location) {
lat = (int) (location.getLatitude());
lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
LoadServerASYNC task = new LoadServerASYNC();
task.execute();
}
And you should call postData method inside doInBackground();

Related

Implement google map like Uber

I am completely new to android.I am trying to implement a draggable google map like uber app.I have found out a code from somewhere,But when I try running few issues were coming like
Error:(24, 37) error: cannot find symbol class GooglePlayServicesClient
Error:(26, 39) error: cannot find symbol class LocationClient
In my dependencies I have added
compile 'com.google.android.gms:play-services:8.4.0'
Following is the code I have used.
package com.rakyow.taxifinder.taxifinder;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.app.Dialog;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends Activity implements
ConnectionCallbacks, OnConnectionFailedListener {
// A request to connect to Location Services
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
public static String ShopLat;
public static String ShopPlaceId;
public static String ShopLong;
// Stores the current instantiation of the location client in this object
private GoogleApiClient mLocationClient;
boolean mUpdatesRequested = false;
private TextView markerText;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
markerText = (TextView) findViewById(R.id.locationMarkertext);
Address = (TextView) findViewById(R.id.adressText);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
// Getting Google Play availability status
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mLocationClient = new GoogleApiClient(this, this, this);
mLocationClient.connect();
}
}
private void stupMap() {
try {
LatLng latLong;
// TODO Auto-generated method stub
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
if (mLocationClient.getLastLocation() != null) {
latLong = new LatLng(mLocationClient.getLastLocation()
.getLatitude(), mLocationClient.getLastLocation()
.getLongitude());
ShopLat = mLocationClient.getLastLocation().getLatitude() + "";
ShopLong = mLocationClient.getLastLocation().getLongitude()
+ "";
} else {
latLong = new LatLng(12.9667, 77.5667);
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLong).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Clears all the existing markers
mGoogleMap.clear();
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
markerText.setText(" Set your Location ");
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
markerLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
LatLng latLng1 = new LatLng(center.latitude,
center.longitude);
Marker m = mGoogleMap.addMarker(new MarkerOptions()
.position(latLng1)
.title(" Set your Location ")
.snippet("")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.add_marker)));
m.setDraggable(true);
markerLayout.setVisibility(View.GONE);
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuilder str;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected void onPreExecute() {
Address.setText(" Getting location ");
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (geocoder.isPresent()) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
My requirement is something similar to this .
Please help me in solving this issue.Any help would be appreciated.
Thanks in advance
I recommend that you use GoogleApiClient because LocationClient is no longer supported in newer versions of play-services they removed it starting Google Play Services 6.5.87 if I am not mistaken. Here is the link for the example implementation. If you really want to use LocationClient, which I do not recommend, you can use an older version of the play-services
cannot find symbol class GooglePlayServicesClient Error:(
GooglePlayServicesClient was removed. The documentation explicitly says that you should be using GoogleApiClient
Note: If you have an existing app that connects to Google Play
services with a subclass of GooglePlayServicesClient, you should
migrate to GoogleApiClient as soon as possible.
here you can find more about it.
Use GoogleApiClient instead of Location Client.
LocationClient is deprecated. The replacement class is the
GoogleApiClient. It has similar functions so its easy to replace.
Source

ANDROID: Code not working after inserting Date string to GET Url

I am making a android client that reports its location to my server after every 10 seconds.
For server I'm using dynamic DNS. I have to sent latitude, longitude and time-stamp as GET parameters.
I made the following working code:
package in.kirancity.trackapp;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity
{
TextView textLat;
TextView textLong;
TextView textRes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLat = (TextView)findViewById(R.id.textLat);
textLong = (TextView)findViewById(R.id.textLong);
textRes = (TextView)findViewById(R.id.textRes);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new myLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, ll);
}
class myLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location arg0)
{
if(arg0 != null)
{
double plong = arg0.getLongitude();
double plat = arg0.getLatitude();
String url = "http://vishalhome.myftp.org/insert.php?la="+Double.toString(plat)+"&ln="+Double.toString(plong)+"&d='Arbitrary'";
textLat.setText(Double.toString(plat));
textLong.setText(Double.toString(plong));
new RequestTask().execute(url);
}
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
class RequestTask extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
TextView tv=(TextView)findViewById(R.id.textRes);
tv.setText(result);
}
}
#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;
}
}
This code works fine for me. But instead of sending actual time-stamp i sent "Arbitrary" string.
After successfully executing asyncTask, the values are inserted and Response is: "inserted"(Returned by my php page).
But when I'm trying this in onLocationChanged:
String url = "http://vishalhome.myftp.org/insert.php?la="+Double.toString(plat)+"&ln="+Double.toString(plong)+"&d=\'";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
url = url + currentDateandTime + "\'";
the application crashes on location change event.
I tried to put try catch blocks, but no clue of problem.
I think problem is coming out after new RequestTask(url) is called.
Please assist !
I think you should encode the url before using it. Try this:
currentDateandTime = URLEncoder.encode(currentDateandTime, "utf-8");
url = url + currentDateandTime + "\'";
Please see URL encoding in Android

Sending json Post date in android with parameter

I'm trying to make a POST request with Android, but I'm not succeeding. I think the problem is in how to set the parameters for resquisição and Header. Below is my method I do the request ...
public void testPostDate() {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
Gson gson = new Gson();
CrimePOST.Crime crime = new CrimePOST().new Crime(10, "São Paulo",
"descrição", 10.00, 30.00);
CrimePOST crimePost = new CrimePOST();
crimePost.setCrime(crime);
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("token",
"0V1AYFK12SeCZHYgXbNMew==$tRqPNplipDwtbD0vxWv6GPJIT6Yk5abwca3IJa6JhMs="));
String json = gson.toJson(crimePost);
String paramString = URLEncodedUtils.format(params, Utils.ENCODE);
try {
HttpPost post = new HttpPost(
"http://safe-sea-4024.herokuapp.com/crimes/mobilecreate"
+ "?" + paramString);
post.setHeader("Content-Type", "application/json");
StringEntity entitty = new StringEntity(json);
entitty.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(entitty);
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = toString(in);
System.out.println(a);
}
} catch (Exception e) {
e.printStackTrace();
}
}
This method is responsible for converting an inputStream to String
private String toString(InputStream is) throws IOException {
byte[] bytes = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int lidos;
while ((lidos = is.read(bytes)) > 0) {
baos.write(bytes, 0, lidos);
}
return new String(baos.toByteArray());
}
Really I am passing the Header correctly?
You have to do this in an AsyncTask
I wrote this tutorial while back. it does send json data via HTTP Post to a url. Check it out. Original post can be found here:http://androidhappenings.blogspot.com/2013/03/android-app-development-201-1st.html
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
public class MainActivity extends Activity implements LocationListener{
private TextView textView =null;
LocationManager locationManager=null;
Location location=null;
protected String url;
protected JSONObject jsonData=null;
private EditText urlText=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(gpsEnabled!=true) {
Toast.makeText(getApplicationContext(), "GPS Disbled! Please Enable to Proceed!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
textView = (TextView)findViewById(R.id.textView);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, this);
urlText = (EditText)findViewById(R.id.urlTextbox);
Button submitButton = (Button)findViewById(R.id.submitUrl);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (urlText.getText()!=null) {
url=urlText.getText().toString();
System.out.println(url);//for testing only, not required
Toast.makeText(getApplicationContext(), "Url Submitted, Sending data to Web Service at url: " + url, Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onLocationChanged(final Location location) {
this.location=location;
final Handler handler = new Handler();
Timer ourtimer = new Timer();
TimerTask timerTask = new TimerTask() {
int cnt=1;
public void run() {
handler.post(new Runnable() {
public void run() {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
Double altitude = location.getAltitude();
Float accuracy = location.getAccuracy();
textView.setText("Latitude: " + latitude + "\n" + "Longitude: " + longitude+ "\n" + "Altitude: " + altitude + "\n" + "Accuracy: " + accuracy + "meters"+"\n" + "Location Counter: " + cnt);
try {
jsonData = new JSONObject();
jsonData.put("Latitude", latitude);
jsonData.put("Longitude", longitude);
jsonData.put("Altitude", altitude);
jsonData.put("Accuracy", accuracy);
System.out.println(jsonData.toString());//not required, for testing only
if(url!=null) {
new HttpPostHandler().execute();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cnt++;
}
});
}};
ourtimer.schedule(timerTask, 0, 120000);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public class HttpPostHandler extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... arg0) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity dataEntity = null;
try {
dataEntity = new StringEntity(jsonData.toString());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httpPost.setEntity(dataEntity);
httpPost.setHeader("Content-Type", "application/json");
try {
httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
this.finalize();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Data not changed while inserting data from android to mysql database

I have a problem in inserting data (latitude and longitude) to mysql. when I first run the app, the lat and long are inserted but when I updated the location (lat and long) and insert the data again, only the longitude changes, and the latitude stays the same value as the previous data inserted. I'm totally confused why it doesnt work. I'd be very glad if anyone could help me with this.
This is my code
package com.android.tyegah;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class TyegahActivity extends Activity {
private LocationManager locationManager;
private Location latestLocation;
private double lat;
private double longi;
private Button updateButton;
private TextView locUpdate;
public String url = "http://servername/file.php";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager =(LocationManager)getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,onLocationChange);
locUpdate = (TextView)findViewById(R.id.locUpdate);
updateButton = (Button)findViewById(R.id.updateButton);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,onLocationChange);
if (latestLocation.getLatitude() != lat && latestLocation.getLongitude() != longi ) {
lat = latestLocation.getLatitude();
longi = latestLocation.getLongitude();
}
String latitude = Double.toString(lat);
String longitude = Double.toString(longi);
url += "?latitude=" + latitude + "&longitude=" + longitude;
locUpdate.setText(latitude + "," + longitude);
getRequest(url);
Toast.makeText(getBaseContext(),
"Location updated : Lat: " + latestLocation.getLatitude() +
" Lng: " + latestLocation.getLongitude(),
Toast.LENGTH_LONG).show();
}
});
}
public void getRequest(String Url) {
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
} catch (Exception ex) {
locUpdate.setText(ex.toString());
}
}
LocationListener onLocationChange = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
latestLocation = location;
if (latestLocation.getLatitude() != lat && latestLocation.getLongitude() != longi ) {
Toast.makeText(getBaseContext(),
"Location updated : Lat: " + latestLocation.getLatitude() +
" Lng: " + latestLocation.getLongitude(),
Toast.LENGTH_LONG).show();
}
}
};
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, onLocationChange);
}
}
This is the php file :
<?php
mysql_connect("localhost","root","");
mysql_select_db("php");
$longitude = $_GET['longitude'];
$latitude = $_GET['latitude'];
if($latitude && $longitude){
$string= "insert into table (latitude, longitude)values('".$latitude."','".$longitude."')";
mysql_query($string);
}
mysql_close();
?>
just change two lines and try it
in android
u have written
if (latestLocation.getLatitude() != lat && latestLocation.getLongitude() != longi )
instead that write
if (latestLocation.getLatitude() != lat || latestLocation.getLongitude() != longi )
AND in php
u have putten
$string= "insert into table (latitude, longitude)values('".$latitude."','".$longitude."')";
instead put
$string= "insert into table (latitude, longitude) values('".$latitude."','".$longitude."')";
try it, i think it'll work
You are updating url on onCreate() method and please check Activity life cycle onCreate() method will call first time when activity is created or activity is re created.
I will suggest you to make a call back mechanism to fetch location data whenever you are creating url for server request.

getting the gps position not working

I dont know why, but i am unable to get the GPS Position...
lm.getLastKnownLocation always returns null and onLocationChanged is never called.
But i can see the gps icon on my system tray.
any ideas?
package com.localfotos;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.service.wallpaper.WallpaperService;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
/*
* This animated wallpaper draws a rotating wireframe cube.
*/
public class MyWallpaperService extends WallpaperService implements LocationListener{
private final String TAG = "WallpaperService============================";
private LocationManager lm;
private final Handler mHandler = new Handler();
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "got location!");
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onCreate() {
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
lm.removeUpdates(this);
}
#Override
public Engine onCreateEngine() {
return new CubeEngine(this);
}
class CubeEngine extends Engine{
MyWallpaperService mws;
private final Runnable mDrawCube = new Runnable() {
public void run() {
drawFrame();
}
};
private boolean mVisible;
private double lat = -1;
private double lon = -1;
CubeEngine(MyWallpaperService mymws) {
mws = mymws;
}
#Override
public void onDestroy() {
super.onDestroy();
mHandler.removeCallbacks(mDrawCube);
}
#Override
public void onVisibilityChanged(boolean visible) {
mVisible = visible;
if (visible) {
drawFrame();
} else {
mHandler.removeCallbacks(mDrawCube);
}
}
#Override
public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
super.onSurfaceChanged(holder, format, width, height);
drawFrame();
}
#Override
public void onSurfaceCreated(SurfaceHolder holder) {
super.onSurfaceCreated(holder);
}
#Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
super.onSurfaceDestroyed(holder);
mVisible = false;
mHandler.removeCallbacks(mDrawCube);
}
#Override
public void onOffsetsChanged(float xOffset, float yOffset,
float xStep, float yStep, int xPixels, int yPixels) {
drawFrame();
}
/*
* Store the position of the touch event so we can use it for drawing later
*/
#Override
public void onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
}
/*
* Draw one frame of the animation. This method gets called repeatedly
* by posting a delayed Runnable. You can do any drawing you want in
* here. This example draws a wireframe cube.
*/
void drawFrame() {
final SurfaceHolder holder = getSurfaceHolder();
Canvas c = null;
try {
c = holder.lockCanvas();
if (c != null) {
// draw something
drawCube(c);
}
} finally {
if (c != null) holder.unlockCanvasAndPost(c);
}
// Reschedule the next redraw
mHandler.removeCallbacks(mDrawCube);
if (mVisible) {
mHandler.postDelayed(mDrawCube, 1000 * 10);
}
}
/*
* Draw a wireframe cube by drawing 12 3 dimensional lines between
* adjacent corners of the cube
*/
//taken from http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/
private JSONObject getJSONfromURL(String url){
//initialize
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
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();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//try parse the string to a JSON object
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
String getPanoramioUrl(double minx, double maxx, double maxy, double miny){
return "http://www.panoramio.com" +
"/map/get_panoramas.php?" +
"set=public&from=0&to=1&minx="+minx+"&miny="+miny+"&maxx="+maxx+"&maxy="+maxy;
}
void drawCube(Canvas canvas) {
//canvas.save();
//canvas.translate(0, 0);
//c.drawColor(0xff00aa00);
Location loc = mws.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try{
if (lat == loc.getLatitude() && lon == loc.getLongitude()){
return;
}
}catch(NullPointerException exc){
Log.d(TAG, "gps not ready");
return;
}
lat = loc.getLatitude();
lon = loc.getLongitude();
}
}
}
<application android:icon="#drawable/icon" android:label="#string/app_name">
<service android:name=".MyWallpaperService"
android:label="#string/app_name"
android:icon="#drawable/icon"
android:permission="android.permission.BIND_WALLPAPER">
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
</intent-filter>
<meta-data android:name="android.service.wallpaper"
android:resource="#xml/livewallpaper" />
</service>
</application>
You need to add
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
to use the GPS. To use network location, use:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
I think this will work for you.

Categories

Resources