Android gets the wrong location of the emulator - java

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:

Related

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 take on selected item from list view to autocomplete textview

I want to show item of list view in autocomplete text view when click on that item in the list view using the following code.
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, AdapterView.OnItemClickListener {
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
GoogleMap mMap;
SupportMapFragment mFragment;
Marker CurrentMarker,FindMarker;
Location mLastLocation;
CustomAutoCompleteTextView atvPlaces = null;
DownloadTask placesDownloadTask;
DownloadTask placeDetailsDownloadTask;
ParserTask placesParserTask;
ParserTask placeDetailsParserTask;
final int PLACES=0;
final int PLACES_DETAILS=1;
LatLng latLng;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mFragment.getMapAsync(this);
// Getting a reference to the AutoCompleteTextView
atvPlaces = (CustomAutoCompleteTextView) findViewById(R.id.atv_places);
atvPlaces.setThreshold(1);
// Adding textchange listener
atvPlaces.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Creating a DownloadTask to download Google Places matching "s"
placesDownloadTask = new DownloadTask(PLACES);
// Getting url to the Google Places Autocomplete api
String url = getAutoCompleteUrl(s.toString());
// Start downloading Google Places
// This causes to execute doInBackground() of DownloadTask class
placesDownloadTask.execute(url);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
lv = (ListView) findViewById(R.id.list);
lv.setOnItemClickListener(this);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)){
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
}else{
return true;
}
}
private String getAutoCompleteUrl(String place){
// Obtain browser key from https://code.google.com/apis/console
String key = "key=AIzaSyC_7RaIknbxXauB6n2xHNTZgRjg0eo5xog";
// place to be be searched
String input = "input="+place;
// place type to be searched
String types = "types=geocode";
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = input+"&"+types+"&"+sensor+"&"+key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;
return url;
}
private String getPlaceDetailsUrl(String ref){
// Obtain browser key from https://code.google.com/apis/console
String key = "key=AIzaSyC_7RaIknbxXauB6n2xHNTZgRjg0eo5xog";
// reference of place
String reference = "reference="+ref;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = reference+"&"+sensor+"&"+key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/details/"+output+"?"+parameters;
return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
//Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
// mLocationRequest.setInterval(1000);
// mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if(CurrentMarker != null){
CurrentMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
MarkerOptions markerOption = new MarkerOptions();
markerOption.position(latLng);
markerOption.title("Current Position");
markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
CurrentMarker = mMap.addMarker(markerOption);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(13));
if(mGoogleApiClient != null){
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
==PackageManager.PERMISSION_GRANTED){
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResult){
switch (requestCode){
case MY_PERMISSIONS_REQUEST_LOCATION: {
if(grantResult.length > 0
&& grantResult[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if(mGoogleApiClient == null){
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}else {
Toast.makeText(this, "permisison denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
String str = ((TextView) view.findViewById(R.id.place_name)).getText().toString();
Toast.makeText(this,str, Toast.LENGTH_SHORT).show();
}
private class DownloadTask extends AsyncTask<String, Void, String> {
private int downloadType = 0;
// Constructor
public DownloadTask(int type) {
this.downloadType = type;
}
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
switch (downloadType) {
case PLACES:
// Creating ParserTask for parsing Google Places
placesParserTask = new ParserTask(PLACES);
// Start parsing google places json data
// This causes to execute doInBackground() of ParserTask class
placesParserTask.execute(result);
break;
case PLACES_DETAILS:
// Creating ParserTask for parsing Google Places
placeDetailsParserTask = new ParserTask(PLACES_DETAILS);
// Starting Parsing the JSON string
// This causes to execute doInBackground() of ParserTask class
placeDetailsParserTask.execute(result);
}
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
int parserType = 0;
public ParserTask(int type) {
this.parserType = type;
}
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
JSONObject jObject;
List<HashMap<String, String>> list = null;
try {
jObject = new JSONObject(jsonData[0]);
switch (parserType) {
case PLACES:
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
// Getting the parsed data as a List construct
list = placeJsonParser.parse(jObject);
break;
case PLACES_DETAILS:
PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();
// Getting the parsed data as a List construct
list = placeDetailsJsonParser.parse(jObject);
}
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return list;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
switch (parserType) {
case PLACES:
String[] from = new String[]{"description"};
int[] to = new int[]{R.id.place_name};
// Creating a SimpleAdapter for the AutoCompleteTextView
//SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);
// Setting the adapter
// atvPlaces.setAdapter(lv);
// list adapter
ListAdapter adapter = new SimpleAdapter(MainActivity.this, result,R.layout.list_item,from,to);
// Adding data into listview
lv.setAdapter(adapter);
break;
case PLACES_DETAILS:
String location = atvPlaces.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
break;
}
}
}
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
#Override
protected List<Address> doInBackground(String... locationName) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
for(int i=0;i<addresses.size();i++){
Address address = (Address)addresses.get(i);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Find Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
FindMarker = mMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(13).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
}
}
I want to show selected item in autocompleteTextview from listView when click on that item. Please tell me using my source code.
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
String str = ((TextView) view.findViewById(R.id.place_name)).getText().toString();
Toast.makeText(this,str, Toast.LENGTH_SHORT).show();
atvPlaces.setText(str);
atvPlaces.dismissDropDown();
}
Pls check this code, I modified.
String mSelectedItem;
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int ClikedPosition, long id) {
//Getting clicked item from list view
mSelectedItem=adapter.getItem(ClikedPosition);
//Setting to auto complete text view
mAutoCompleteTextView.setText(mSelectedItem);
}
});

How to determine location in android?

I am working in small project and the location will be part of the log in, so I want to determine location which is easier than writing location but there was an error how can fix this code please ?
public class RequestUs extends AppCompatActivity {
private Button bLocation;
private TextView tvCoordinate;
private LocationManager lm;
private LocationListener ls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request_us);
bLocation = (Button) findViewById(R.id.bLocation);
tvCoordinate = (TextView) findViewById(R.id.tvCoordinate);
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
ls = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
tvCoordinate.append("\n" + location.getLatitude()+" "+ location.getLatitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] {
Manifest.permission.ACCESS_FINE_LOCATION ,
Manifest.permission.ACCESS_COARSE_LOCATION ,
Manifest.permission.INTERNET
}, 10);
return;
}else
{
ConfigureButton();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 10:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
ConfigureButton();
}
}
private void ConfigureButton() {
bLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lm.requestLocationUpdates("gps", 5000, 0, ls);
}
});
}
}
find location based on input(address)
public JSONObject getLocationInfo(String address) {
JSONObject json = null;
try {
address = address.replaceAll(" ", "%20");
String url = "https://maps.google.com/maps/api/geocode/json?address="
+ address + "&sensor=true&language=en&key=AIzaSyA1pAWC5_88Xy8UpxMvojUTNt-fQqON4Xc";
json = JSONParser.readJsonFromUrl(url);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
public static JSONObject readJsonFromUrl(String url) throws IOException,
JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is,
Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}

Impossible to connect to location manager android

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)

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) {
}
}

Categories