Impossible to connect to location manager android - java

public class locationservice extends Service implements LocationListener
{
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
protected Context mContext;
boolean canGetLocation = false;
protected LocationManager locationManager;
Location location;
double latitude;
double longitude;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public locationservice() {
//this.mContext = context;
getLocation();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
new start().execute();
scheduleNextUpdate();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
private void scheduleNextUpdate()
{
Intent intent = new Intent(this, this.getClass());
PendingIntent pendingIntent =
PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// The update frequency should often be user configurable. This is not.
long currentTimeMillis = System.currentTimeMillis();
long nextUpdateTimeMillis = currentTimeMillis + 1* DateUtils.MINUTE_IN_MILLIS;
Time nextUpdateTime = new Time();
nextUpdateTime.set(nextUpdateTimeMillis);
/* if (nextUpdateTime.hour < 8 || nextUpdateTime.hour >= 18)
{
nextUpdateTime.hour = 8;
nextUpdateTime.minute = 0;
nextUpdateTime.second = 0;
nextUpdateTimeMillis = nextUpdateTime.toMillis(false) + DateUtils.DAY_IN_MILLIS;
}*/
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, nextUpdateTimeMillis, pendingIntent);
}
public void getLocation()
{
try
{
locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
// no network provider is enabled
}
else
{
this.canGetLocation = true;
//First get location from Network Provider
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
0,
0, (android.location.LocationListener) this);
Log.d("Network", "Network");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0, (android.location.LocationListener) this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
}
public void updateGPSCoordinates()
{
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
public double getLatitude()
{
if (location != null)
{
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if (location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
class start extends AsyncTask<String, Void,String> {
private Exception exception;
protected void onPreExecute() {
}
protected String doInBackground(String... urls) {
try {
// open a connection to the site
URL url = new URL("http://192.168.1.2/mylocation/update_location.php");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
// send your parameters to your site
ps.print("latlong="+latitude+"$"+longitude);
ps.print("&mobile=7803214029");
// we have to get the input stream in order to actually send the request
con.getInputStream();
// close the print stream
ps.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
// TODO: check this.exception
// TODO: do something with the feed
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
}
Im trying to get longitudes and latitudes from a service but im getting a null pointer expression and it also says that impossible to connect to the location manager.at android.content.ContextWrapper.getSystemService(ContextWrapper.java:526)

Related

Android gets the wrong location of the emulator

I made an app that stores the position of the device (latitude and longitude) and to actually test it I tried to change the GPS location of the emulator from the default location in Mountain View to a random location in Rome. I followed this thread to do it. The problem is that my app still stores the default location rather than the new location I set.
This is how I access the location:
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 m
private static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
Location location = null;
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
throw new Exception("GPS must be turned on!");
}
else {
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission((Activity)mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission((Activity)mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
throw new Exception("Permission needed for location!");
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return location;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS turned off");
alertDialog.setMessage("Turn on the GPS!");
alertDialog.setPositiveButton("Impostazioni", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
}
This is how I use those methods and actually store the location on the Database:
public class HomeActivity extends AppCompatActivity {
private GPSTracker gpsTracker;
String ServerURL = "http://10.0.2.2/api/insert.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
final Button bottone1 = findViewById(R.id.bottone1);
bottone1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(HomeActivity.this, MainActivity.class);
gpsTracker = new GPSTracker(HomeActivity.this);
Location location = gpsTracker.getLocation();
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date datenotformatted = new Date(location.getTime());
String date = format.format(datenotformatted);
String lat = String.valueOf(latitude);
String lon = String.valueOf(longitude);
startActivity(intent);
insertData(lat, lon, date);
}
else {
gpsTracker.showSettingsAlert();
}
}
});
}
private void insertData(final String latitude, final String longitude, final String date){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String first = latitude;
String second = longitude;
String third = date;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(ServerURL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("latitudine", first));
nameValuePairs.add(new BasicNameValuePair("longitudine", second));
nameValuePairs.add(new BasicNameValuePair("data", third));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
Toast.makeText(HomeActivity.this, "Errore.", Toast.LENGTH_LONG).show();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "Success.";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(latitude, longitude, date);
}
The location the app gets everytime:
The actual location of the emulator I set:

Android Studio GPS connect return result from web server

I am trying to connect to a webserver and take specific information from a JSON format and display it in a text box on my emulator/Android Phone, however i cant seem to get any result other than error.
here is my current code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new SictMode.ThreadPolicy.Builder().permitAll().build();
setThreadPolicy(policy);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{
"android.permission.ACCESS_FINE_LOCATION",
"android.permission.ACCESS_COARSE_LOCATION"}, 1);
} else {
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double lng = location.getLongitude();
double lat = location.getLatitude();
((TextView) findViewById(R.id.latTextView)).setText("" + lat);
((TextView) findViewById(R.id.lngTextView)).setText("" + lng);
//String url = "http://zebedee.kriswelsh.com:8080/stations?lat=" + lat + "&lng=" + lng;
String url = "http://zebedee.kriswelsh.com:8080/stations?lat=53.4355&lng=3.0508";
search(url);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
});
}
}
public String search(String url) {
ArrayList<String> listItems = new ArrayList<String>();
String resultsOut = "";
try {
URL fhr = new URL(url);
URLConnection tc = fhr.openConnection();
InputStreamReader isr = new InputStreamReader(tc.getInputStream());
BufferedReader in = new BufferedReader(isr);
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString("StationName"));
listItems.add(jo.getString("Lattitude"));
}
}
for(String s : listItems)
{
resultsOut =resultsOut.concat(s+ "\n");
}
return resultsOut;
}
catch (MalformedURLException e ){e.printStackTrace();}
catch (IOException e){e.printStackTrace();}
catch (JSONException e){e.printStackTrace();}
return "error";
}
public void onClick (View v) {
TextView results = (TextView) findViewById(R.id.results);
results.setText(search(String.valueOf(v)));
}
#Override
public void onStop() {
super.onStop();
}
}

How to move the marker in Google map when the latitude and longitude changes in webservices?

In my application am plotting a set of latitude and longitude from web services to Google map but when the Latitude and longitude changes in the web services the marker is not moving. when I close and open the application it updates the changes, but I need to move the marker without closing and restarting the application. My Updated code is given below .
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout_one, container, false);
MapsInitializer.initialize(getActivity());
mMapView = (MapView)rootView.findViewById(R.id.mapView);
mMapView.onCreate(mBundle);
MapsInitializer.initialize(getActivity());
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/* new DownloadJSON().execute();
setUpMapIfNeeded(rootView); */
/*
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
Log.d("Data in Log", "");
}
}, 10*1000);*/
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
LocationManager locman = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
//locman.requestLocationUpdates(minTime, minDistance, criteria, intent);
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 000, 10, this);
return rootView;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.setMyLocationEnabled(true);
Location myLocation = mMap.getMyLocation();
if (mMap != null) {
// setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (int i = 0; i < arraylist1.size(); i++) {
final LatLng position = new LatLng(Double
.parseDouble(arraylist1.get(i).get("Latitude")),
Double.parseDouble(arraylist1.get(i).get(
"Longitude")));
String ime1 = arraylist1.get(i).get("IME");
final MarkerOptions options = new MarkerOptions()
.position(position);
mMap.addMarker(options);
mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
//options.title(ime1);
builder.include(position);
}
LatLng latLng = new LatLng(arg0.getLatitude(), arg0
.getLongitude());
mMap.setMyLocationEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// mMap.setOnMapClickListener(null);
mMap.setOnMarkerClickListener(null);
mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
}
});
}
}
}
/* protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
new DownloadJSON().execute();
} */
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
String result="";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
arraylist1 = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
String result = "";
json = jParser.getJSONFromUrl(SERVICE_URL);
try {
arraylist1.clear();
jsonarray = json.getJSONArray("SingleIMEs");
Log.d("Haaaaaaaaaaaa", "" + json);
for (int i = 0; i < jsonarray.length(); i++) {
Log.d("H11111111111111111111111111",
"" + jsonarray.length());
map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
// pubname = json.getString("PubName");
latitude = json.getDouble("Latitude");
longitude = json.getDouble("Longitude");
ime = json.getString("IME");
// map.put("PubName", json.getString("PubName"));
//map.put("PubID", json.getString("PubID"));
map.put("Latitude", json.getString("Latitude"));
map.put("Longitude", json.getString("Longitude"));
map.put("IME", json.getString("IME"));
arraylist1.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
result="Error";
e.printStackTrace();
}
}catch(Exception e){
result="Error";
}
return null;
}
protected void onPostExecute(Void args) {
// mProgressDialog.dismiss();
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "onLocationUpdated!!!", Toast.LENGTH_SHORT).show();
Log.d("onLocationUpdated!!!","");
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
}
#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
}
}
You can use handler for updating the location.Inside run() just call that webservice.And just put the marker in current location.
// Call current location API after 3 Min
handler.postDelayed(run, 3000 * 60);
Runnable run = new Runnable() {
#Override
public void run() {
if (isConnected(context)) {
new CurrentPosTask().execute();
} else {
Toast.makeText(context, "No internet connection",
Toast.LENGTH_LONG).show();
}
}
};
Don't forget call below method into onDestroy() method
// Stop the handler
handler.removeCallbacks(run);
Hope it will help you. Let me know once done.
You have to set repeat alarm to check the web service at intervel
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() +
60 * 1000, alarmIntent);
// Set the alarm to start at approximately 2:00 p.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 14);
// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
5000, alarmIntent);
and in alarm reciever class call web service and update the map position
public class AlarmReceiverextends WakefulBroadcastReceiver {
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
}
for full tutorial look developers.android
https://developer.android.com/training/scheduling/alarms.html

Get longitude and latitude values to post into url - Android

I am creating an Android app that pulls XML data. I want to be able to use the longitude and latitude values to post into the web link to get specific XML data for the users current location.
Here is my code so far, which does not work:
public class GeoSplashActivity extends Activity {
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
private String GEORSSFEEDURL = "http://www.socialalertme.com/mobilealerts.xml?lat="+latitude+"lng="+longitude+"&distance=20";
GeoRSSFeed feed3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash2);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null
&& !conMgr.getActiveNetworkInfo().isConnected()
&& !conMgr.getActiveNetworkInfo().isAvailable()) {
// No connectivity - Show alert
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
GeoDOMParser myParser = new GeoDOMParser();
feed3 = myParser.parseXml(GEORSSFEEDURL);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed3);
// launch List activity
Intent intent = new Intent(GeoSplashActivity.this, GeoListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
}
}
I have never used the location stuff before, so I'm not entirely sure what I'm doing here. If anyone could give some pointers, I'd really appreciate it!
Hopefully you are not forgetting
<uses-permission android:name=“android.permission.ACCESS_FINE_LOCATION”></uses-permission>
in your manifest file. This tutorial can help you to get better understanding.
Edit
Google already have provided Training to get current Location.
//Get coordinates if available:
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Location loc;
double latitude=0,longitude=0;
if ( ( loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) )!=null ){
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}else if( ( loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) )!=null ){
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
//If any coordinate value is recieved, use it.
if(latitude!=0 || longitude!=0){
String latitude = String.valueOf(latitude);
String longitude = String.valueOf(longitude);
//TODO post into url
}
You should move initialization of location variables to the onCreate method. Also you should also check if location != null:
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
longitude = location.getLongitude();
latitude = location.getLatitude();
GEORSSFEEDURL = "http://www.socialalertme.com/mobilealerts.xml?lat="+latitude+"lng="+longitude+"&distance=20";
} else {
...
}
I am doing the same thing, and this works for me!
But, the server I am requestiong is a node.js server, and the data is in JSON.
public class GetWeatherDataRest extends AsyncTask<Void, Void, String> {
private static final String TAG = "GetWeatherDataRest";
// get lat and long from main activity
double lat = MyActivity.lat;
double lng = MyActivity.lng;
// the url
String url = "http://ThisIsTheAddress/weather/5days?lat="+lat+"&lng="+lng;
public MyActivity context;
private List<Weather> posts;
public GetWeatherDataRest(MyActivity activity){
this.context = activity;
}
#Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
//Perform the request and check the status code
HttpResponse response = client.execute(get);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
posts = new ArrayList<Weather>();
posts = Arrays.asList(gson.fromJson(reader, Weather[].class));
content.close();
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
}
return null;
}
#Override
protected void onPostExecute(String result) {
context.updateFields(posts);
}
}
Okey! This is my GpsFragment, where I get the lng and lat!
I am not done with this yet, so It might not look like much, but it works, also it gives an address from the lng & lat using geocoder
You should implement the LocationListener.
public class GpsFragment extends Fragment implements LocationListener{
public Location location;
LocationManager locationManager;
String provider;
List<Address> mAddresses;
TextView mAddress1;
TextView mAddress2;
public static double lat;
public static double lng;
private static final String TAG = "MyGps";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myInflatedView = inflater.inflate(R.layout.gps_fragment, container,false);
mAddress1 = (TextView) myInflatedView.findViewById(R.id.address_text);
mAddress2 = (TextView) myInflatedView.findViewById(R.id.address_text2);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 100, 1, this);
if(location != null){
onLocationChanged(location);
Log.v(TAG, "Location available!");
}
else{
mAddress1.setText("No location");
Log.e(TAG, "Location not available!");
}
return myInflatedView;
}
// So i think this is what you need! the 'onLocationChanged'
#Override
public void onLocationChanged(Location location) {
this.location = location;
lat = location.getLatitude();
lng = location.getLongitude();
Geocoder mLocation = new Geocoder(getActivity().getApplicationContext(), Locale.getDefault());
try {
mAddresses = mLocation.getFromLocation(lat, lng, 1);
if(mAddresses != null) {
Address returnedAddress = mAddresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
// mAddress.setText(strReturnedAddress.toString());
//mAddress1.setText("lat"+lat);
//mAddress2.setText("lng"+lng);
mAddress1.setText("Address: "+returnedAddress.getAddressLine(0).toString());
mAddress2.setText("City: "+returnedAddress.getAddressLine(1).toString());
}
else{
// mAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//mAddress.setText("Cannot get Address!");
}
((MyActivity)getActivity()).fetchData();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}

Why can't I retrieve the name of the current location?

I am making an application in which i have to display the the name of the current location. I am getting latitude and longitude but cannot get the name of the location.
The code I am trying to do this is:
context = getApplicationContext();
Location location;
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
double lon, lat;
try
{
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lon = location.getLongitude();
lat = location.getLatitude();
Toast.makeText(context, "Lat: "+lat+"\nLon: "+lon, Toast.LENGTH_LONG).show();
List<Address> mAddresses = null;
Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
try
{
mAddresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
}
catch (IOException e)
{
e.printStackTrace();
}
#SuppressWarnings("unchecked")
String cityName = (mAddresses != null) ? ((List<Address>) mAddresses).get(0)
.getLocality() : TimeZone.getDefault().getID();
#SuppressWarnings("unchecked")
String countryName = (mAddresses != null) ? ((List<Address>) mAddresses).get(0)
.getCountryName() : Locale.getDefault().getDisplayCountry()
.toString();
try
{
lm.clearTestProviderLocation(LocationManager.GPS_PROVIDER);
}
catch(Exception e)
{}
Toast.makeText(context, "Using GPS Provider", Toast.LENGTH_SHORT).show(); }
catch(Exception exp1){
try
{
location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
lon= location.getLongitude();
lat = location.getLatitude();
Toast.makeText(context, "Lat: "+lat+"\nLon: "+lon, Toast.LENGTH_LONG).show();
List<Address> mAddresses = null;
Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
try
{
mAddresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
}
catch (IOException e)
{
e.printStackTrace();
}
#SuppressWarnings("unchecked")
String cityName = (mAddresses != null) ? ((List<Address>) mAddresses).get(0).getLocality() : TimeZone.getDefault().getID();
#SuppressWarnings("unchecked")
String countryName = (mAddresses != null) ? ((List<Address>) mAddresses).get(0).getCountryName() : Locale.getDefault().getDisplayCountry().toString();
try
{
lm.clearTestProviderLocation(LocationManager.NETWORK_PROVIDER);
}
catch(Exception e)
{}
Toast.makeText(context, "Using Network Provider", Toast.LENGTH_SHORT).show();
}
It is better to do it in Async task like
private class LocationTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... parms) {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(),
true);
Location locations = locationManager.getLastKnownLocation(provider);
List<String> providerList = locationManager.getAllProviders();
if (null != locations && null != providerList
&& providerList.size() > 0) {
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(),
Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(
latitude, longitude, 1);
if (null != listAddresses && listAddresses.size() > 0) {
String _Location = listAddresses.get(0).getAddressLine(
1);
// 1000).show();
return _Location;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return " ";
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onPostExecute(String locOutcome) {
//Use locOutcome here
}
}
Don't forget to add permission
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Categories