I am getting weather info in my app and had it working. Now I am getting a null pointer exception and I'm not sure why, especially since it was working and I haven't changed any of this code.
package com.kentuckyfarmbureau.kyfb;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class WeatherLocation extends Activity
{
EditText locationText;
TextView label;
Button getWeather;
String enteredText;
String url = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=%s&format=json&num_of_days=5&key=37a5fj42xpyptvjgkhrx5rwu";
String newURL;
String currentLocationText;
LocationManager lm;
Location location;
double longitude;
double latitude;
String longString;
String latString;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.weatherlocation);
locationText = (EditText) findViewById(R.id.locationTextView);
label = (TextView) findViewById(R.id.label);
getWeather = (Button) findViewById(R.id.showWeather);
locationText.setText("Current Location");
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
longString = String.valueOf(longitude);
latString = String.valueOf(latitude);
currentLocationText = (latString + "+" + longString);
enteredText = currentLocationText;
newURL = String.format(url, enteredText);
locationText.setOnEditorActionListener(new OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE)
{
if(locationText.getText().toString().equals("Current Location"))
{
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
longString = String.valueOf(longitude);
latString = String.valueOf(latitude);
currentLocationText = (latString + "+" + longString);
enteredText = currentLocationText;
}
else
{
enteredText = locationText.getText().toString();
enteredText = enteredText.replaceAll(" ", "+");
}
System.out.println(enteredText);
// hide the virtual keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.RESULT_UNCHANGED_SHOWN);
newURL = String.format(url, enteredText);
System.out.println("Formatted URL: " + newURL);
handled = true;
}
return handled;
}
});
// Get Weather button
getWeather.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent weather = new Intent(WeatherLocation.this, Weather.class);
weather.putExtra("INTENT_KEY_URL", newURL);
weather.putExtra("CURRENT_LOCATION", locationText.getText().toString());
startActivity(weather);
}
});
}
}
The problem seems to be line 48, longitude = location.getLongitude();
If line 48 is causing the issues, then most likely your
location is null. This can be null if you call getLastKnownLocation() while the provider is disabled as noted in the android documentation.
I fixed this by adding a location listener.
final LocationListener locationListener = new LocationListener()
{
#Override
public void onLocationChanged(Location currentLocation)
{
latitude = currentLocation.getLatitude();
longitude = currentLocation.getLongitude();
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
And adding:
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 1, locationListener);
Related
I'm quite new to android development and I was wondering if it is possible for me to locate the nearest marker to a user and knowing which marker is closest direct the user there using a polyline and google directions api. The locations of the markers are taken from a database that I have parsed into a list array which I then use to place the markers on the map. I have tried to find help from other questions however they do not seem to fit in my project.
If it is possible for me to find the nearest marker to the user how can I do it if not is there an alternative method I could use??
This is my code for my main activity:
package com.example.defiblocator;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,
LocationListener,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
public static TextView data;
public static String location;
GoogleMap mapAPI;
SupportMapFragment mapFragment;
Location mLastLocation;
Marker mCurrLocationMarker;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
String delimiter = ",";
List<String> full = new ArrayList<>();
List<String> size = new ArrayList<>();
private ArrayList<LatLng> markerCoords = new ArrayList<LatLng>();
String info;
String name;
Double lat;
Double lng;
Button emergency;
LatLng mark;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapAPI);
mapFragment.getMapAsync(this);
data = findViewById(R.id.fetchdata);
new fetchData(new CallbackClass()).execute();
emergency = findViewById(R.id.button);
emergency.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mapAPI = googleMap;
mapAPI.getUiSettings().setZoomControlsEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mapAPI.setMyLocationEnabled(true);
//mapAPI.setOnMyLocationChangeListener(this);
}
} else {
buildGoogleApiClient();
mapAPI.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
#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 (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}*/
//Place current location marker
LatLng patient = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(patient);
markerOptions.title("Patient");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
mCurrLocationMarker = mapAPI.addMarker(markerOptions);
//move map camera
mapAPI.animateCamera(CameraUpdateFactory.zoomTo(11));
mapAPI.moveCamera(CameraUpdateFactory.newLatLng(patient));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public class CallbackClass implements CallbackInterface {
#Override
public void onSuccess(String callbackData) {
info = callbackData;
full = Arrays.asList(info.split(delimiter));
size = Arrays.asList(info.split(delimiter));
Integer x = 0;
while(x != size.size()){
name = full.get(x);
x += 1;
lat = Double.valueOf(full.get(x));
x += 1;
lng = Double.valueOf(full.get(x));
x += 1;
LatLng pos = new LatLng(lat, lng);
mapAPI.addMarker(new MarkerOptions().position(pos).title(name));
mark = new LatLng(lat,lng);
markerCoords.add(mark);
}
}
#Override
public void onFailure() {
}
}
}
and this is the code for parsing the JSON from the database any help would be greatly appreciated.
package com.example.defiblocator;
import android.app.Application;
import android.os.AsyncTask;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchData extends AsyncTask <Void,Void,Void>{
CallbackInterface callbackInterface;
String data = "";
String json_url;
String singleParsed = "";
public String dataParsed = "";
String sent;
public fetchData(CallbackInterface callbackInterface) {
this.callbackInterface = callbackInterface;
}
public Integer x = 0;
#Override
protected void onPreExecute(){
json_url = "http://defiblocator.ml/json_get_data.php";
dataParsed = "";
}
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
for(int i =0 ; i <JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = JO.get("name") + "," + JO.get("lat") + "," +JO.get("lng") + "," ;
dataParsed = dataParsed + singleParsed ;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException | JSONException e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
MainActivity.data.setText(dataParsed);
callbackInterface.onSuccess(dataParsed);
}
}
You could use a simple distance formula to archive this:
private Double distance(Double lat1, Double lon1, Double lat2, Double lon2) {
return Math.sqrt (Math.pow((lat1 - lat2), 2) - Math.pow((lon1 - lon2), 2));
}
// The user Location
currentLat = xxxx;
currentLon = xxxx;
if ((markerCoords != null) && (markerCoords.size() > 0)) {
LatLng near = markerCoords.get(0);
for (int x = 1; x < markerCoords.size(); x++) {
Double lat = markerCoords.get(x).latitude;
Double lon = markerCoords.get(x).longitude;
Double currentMarkerdistance = distance(
currentLat,
currentLon,
markerCoords.get(x).latitude,
markerCoords.get(x).longitude);
Double nearMarkerdistance = distance(
currentLat,
currentLon,
near.latitude,
near.longitude);
if (currentMarkerdistance < nearMarkerdistance) {
near = markerCoords.get(x);
}
}
}
// After this process the near variable will hold the near marker
In this code, I need to send name and number to the location database with the map's long and lat. Marker's long and lat sending to the firebase without any issue but name and number not sending to the firebase. I cannot find the issue of the code because in the logcat there are not showing any issue. Can you please help me to fix this.
package com.example.policeemergencysystem;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.FragmentActivity;
import android.os.Build;
import android.os.Bundle;
import com.example.policeemergencysystem.Prevelant.Prevelant;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
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;
import com.example.policeemergencysystem.Model.AdminOrders;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
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;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.example.policeemergencysystem.Prevelant.Prevelant;
import com.google.firebase.database.ValueEventListener;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{
private GoogleMap mMap;
private Button doneBtn;
TextView backBtn;
Marker myMarker;
LocationManager locationManager;
private static final String TAG = "MainActivity";
private String name;
private String userID = "", userNAME = "", userPHONE = "";
DatabaseReference ordersRef = FirebaseDatabase.getInstance().getReference()
.child("Location")
.child(Prevelant.currentOnlineUser.getUsername());
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
doneBtn = (Button) findViewById(R.id.doneBtn);
backBtn = (TextView) findViewById(R.id.backBtn);
userID = getIntent().getStringExtra("uid");
userNAME = getIntent().getStringExtra("uname");
userPHONE = getIntent().getStringExtra("uphone");
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10);
mLocationRequest.setSmallestDisplacement(10);
mLocationRequest.setFastestInterval(10);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new
LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
Task<LocationSettingsResponse> task= LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
task.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response = task.getResult(ApiException.class);
// All location settings are satisfied. The client can initialize location
// requests here.
} catch (ApiException exception) {
switch (exception.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the
// user a dialog.
try {
// Cast to a resolvable exception.
ResolvableApiException resolvable = (ResolvableApiException) exception;
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
resolvable.startResolutionForResult(
MapsActivity.this,
101);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
} catch (ClassCastException e) {
// Ignore, should be an impossible error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
}
});
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
//Check whether the network provider is enabled
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//Get the Latitude
double latitude = location.getLatitude();
//Get the Longitude
double longitude = location.getLongitude();
//Instantiate the class, LatLng
LatLng latLng = new LatLng(latitude, longitude);
//Instantiate the class, GeoCoder
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getLocality()+",";
str += addressList.get(0).getCountryName()+",";
str += addressList.get(0).getPostalCode();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14.0f));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
else if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//Get the Latitude
double latitude = location.getLatitude();
//Get the Longitude
double longitude = location.getLongitude();
//Instantiate the class, LatLng
LatLng latLng = new LatLng(latitude, longitude);
String name = new String(Prevelant.currentOnlineUser.getUsername());
//Instantiate the class, GeoCoder
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getLocality()+",";
str += addressList.get(0).getCountryName()+",";
str += addressList.get(0).getPostalCode();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng)
.zoom(17).build();
//Zoom in and animate the camera.
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
switch (requestCode) {
case 101:
switch (resultCode) {
case Activity.RESULT_OK:
// All required changes were successfully made
Toast.makeText(MapsActivity.this,states.isLocationPresent()+"",Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to
Toast.makeText(MapsActivity.this,"Canceled",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
break;
}
}
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
Toast.makeText(this, "Please be patience until we find your current location...", Toast.LENGTH_SHORT).show();
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
// First check if myMarker is null
if (myMarker == null) {
// Marker was not set yet. Add marker:
myMarker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Accidnet Location")
.snippet("Put the marker to your accident location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MapsActivity.this, "Your location has been placed!", Toast.LENGTH_SHORT).show();
HashMap<String, Object> userMap = new HashMap<>();
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Location").child(Prevelant.currentOnlineUser.getUsername());
myRef.child("name").setValue(userNAME);
myRef.child("phone").setValue(userPHONE);
myRef.child(Prevelant.currentOnlineUser.getUsername()).updateChildren(userMap);
finish();
Intent intent = new Intent(MapsActivity.this, LoginActivity.class);
startActivity(intent);
}
});
} else {
// Marker already exists, just update it's position
myMarker.setPosition(latLng);
LatLng myLatLng = new LatLng(myMarker.getPosition().latitude, myMarker.getPosition().longitude);
}
HashMap<String, Object> adminMap = new HashMap<>();
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Location").child(Prevelant.currentOnlineUser.getUsername());
LatLng myLatLng = new LatLng(myMarker.getPosition().latitude, myMarker.getPosition().longitude);
myRef.child("latitude").setValue(myLatLng.latitude);
myRef.child("longitude").setValue(myLatLng.longitude);
myRef.child(Prevelant.currentOnlineUser.getUsername()).updateChildren(adminMap);
}
});
}
}
I have an app which shows users current coordinates and update it as every 5 meters.
but i have problem in the line which i call for "requestLocationUpdates" which is in this line:
Location location1 = locationManager.requestLocationUpdates(GpsProvider, 0, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, mylocationListener);
.
if i place Context as last parameter i will get an error which tells(note that "GpsTracker" is my Main Activity) :
"Cannot resolve method 'requestLocationUpdates(java.lang.String, int, long, com.project.gpstrackerr.GpsTracker)'"
and if i place my locationlistener i will get an error which tells:
Incompatible types.
Required:android.location.Location
Found:void
here is my Full code of my GpsTracker Activity(which is my Main Activity)
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
public class GpsTracker extends Activity
{
public static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1;
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 20;
boolean isGPSEnabled = false, isNetworkEnabled = false;
boolean isGPSEnabled2 = false, isNetworkEnabled2 = false;
DatabaseTable cn;
DatabaseManager db = new DatabaseManager(this);
HttpClass JSONSaver = new HttpClass();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
Context context = GpsTracker.this;
LocationManager locationManager, locationManagerCHECK;
TextView ET_Coordinates, ET_NU;
ListView listView;
//for Coordinates details in Location Listener
double latitude;
double longitude;
String Date;
//for Getting Coordinates details
String strLat, strLong, strDate;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Show Last Known Location
ShowLastKnownLocation();
String NetworkProvider = LocationManager.NETWORK_PROVIDER;
String GpsProvider = LocationManager.GPS_PROVIDER;
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled2 = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled2 = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public LocationListener mylocationListener = new LocationListener()
{
#Override
public void onLocationChanged(Location location)
{
Date date = new Date();
Date = dateFormat.format(date);
latitude = location.getLatitude();
longitude = location.getLongitude();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Toast.makeText(GpsTracker.this, "Provide Status Changed" + "\n"
+ "Provider: " + provider + "\n"
+ "Status: " + status + "\n"
+ "Extras: " + extras + ".",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText(GpsTracker.this,
"Provider Turned ON!", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText(GpsTracker.this,
"Provider is OFF!", Toast.LENGTH_SHORT).show();
}
};
protected void showUpdatedLocation(boolean checkGPSEnabled, boolean checkNetworkEnabled, String NetworkProvider, String GpsProvider, LocationManager locationManager)
{
if (checkGPSEnabled)
{
//I have problem in this Line
Location location1 = locationManager.requestLocationUpdates(GpsProvider, 0, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, mylocationListener);
if (location1 != null)
{
Date = dateFormat.format(date);
latitude = location1.getLatitude();
longitude = location1.getLongitude();
db.addContact(new DatabaseTable(Date, latitude, longitude));
JSONSaver.writeJSON(Date, latitude, longitude);
showOnTextView(Date, latitude, longitude);
}
}
else if (isNetworkEnabled2)
{
Location location1 = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location1 != null)
{
//I have problem in this Line
Location location1 = locationManager.requestLocationUpdates(NetworkProvider, 0, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, mylocationListener);
Date = dateFormat.format(date);
latitude = location1.getLatitude();
longitude = location1.getLongitude();
db.addContact(new DatabaseTable(Date, latitude, longitude));
JSONSaver.writeJSON(Date, latitude, longitude);
showOnTextView(Date, latitude, longitude);
}
}
}
}
I want to know where is my problem and how can i solve it and which of them(Context or LocationListener) is better to be used for doing my job.
It's my first time that i ask a question in Stackoverflow so if explanations have some lacks or i was not very clear or any other problems,
feel free to ask for more information in comments I will try to be as much as clear i can.
and beside of that I'm Kind of New to Programming so if you find something Stupid in my codes Don't get Surprised :D.
Thanks for Further Helps!
Error: incompatible types: void cannot be converted to Location. This the actuall error you should get when you run above code.
You are expecting location in the place where void is returning. requestLocationUpdates uses LocationListener object of LocationManager class to receive periodic updates about the geoposition.
//Implement LocationListener to your class and implement callback methods
//use the below code at onCreate
//[Changes starts here]
// 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);
}
//[Changes ends here]
//onLocationChanged method you'll get the updated locatioin
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
}
/* 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);
}
Source: http://www.vogella.com/tutorials/AndroidLocationAPI/article.html
Thanks for all people who helped me! the problem was for the package i used that was:
import android.location.LocationListener;
I used next package instead of first package:
import com.google.android.gms.location.LocationListener;
using this package in #chiru 's script will work fine for me!
Thanks A Lot Again!
You have an error at this line of code :
...requestLocationUpdates(NetworkProvider, 0, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, mylocationListener);
The method requestLocationUpdates has the parameters: String provider, long minTime, float minDistance, LocationListener listener
This is what you put in:
NetworkProvider provider, long minTime, float minDistance, LocationListener listener
The only reason I'd see of the compiler giving an error is because NetworkProvider isn't a String. Otherwise, your locationManager simply doesn't have requestLocationUpdates(..).
I am working on application where I need to collect accelerometer and location data & send them over web-server. I have to collect the data on sensor changed event. Right now I am trying to collect it when I click on start button, but somehow I don't see that data getting stored in my file. Could anyone help me with this ?
I have to send this data to MySQL database for processing (on web-server). How will I send the data over to server?
Here is what I have tried right now :
package myapp;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import app.AccelLocData;
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapViewActivity extends Activity implements LocationListener,
SensorEventListener, OnClickListener {
GoogleMap googleMap;
private boolean started = false;
private ArrayList<AccelLocData> sensorData;
private SensorManager sensorManager;
private Button btnStart, btnStop;
private String provider;
// private Button btnUpload;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorData = new ArrayList<AccelLocData>();
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
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
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : "
+ latLng.longitude);
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory
.newLatLng(latLng));
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
}
});
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
public void onSensorChanged(SensorEvent event) {
if (started) {
double x = event.values[0];
double y = event.values[1];
double z = event.values[2];
long timestamp = System.currentTimeMillis();
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locManager.getBestProvider(criteria, true);
Location location = locManager.getLastKnownLocation(provider);
double latitude = 0;
double longitude = 0;
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
AccelLocData data = new AccelLocData(timestamp, x, y, z, latitude,
longitude);
// System.out.println("Accel Data:" + data.toString());
// System.out.println("Latitude:" + latitude);
// System.out.println("Longitude:" + longitude);
sensorData.add(data);
}
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
System.out.println("Latitude:" + latitude + ", Longitude:" + longitude);
// Setting latitude and longitude in the TextView tv_location
// tvLocation.setText("Latitude:" + latitude + ", Longitude:" +
// longitude);
}
#Override
public void onProviderDisabled(String arg0) {
// 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 onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart:
btnStart.setEnabled(false);
btnStop.setEnabled(true);
// btnUpload.setEnabled(false);
// sensorData = new ArrayList<AccelLocData>();
// save prev data if available
started = true;
try {
File root = android.os.Environment
.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/myapp");
dir.mkdirs();
File sensorFile = new File(dir, "acc.txt");
// sensorFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(sensorFile);
ObjectOutputStream myOutWriter = new ObjectOutputStream(fOut);
System.out.println("Sensor data size:"+sensorData.size());
for(int i=0;i<sensorData.size();i++){
System.out.println("Sensor Data:" + sensorData.get(i).getX());
}
myOutWriter.writeObject(sensorData);
myOutWriter.close();
fOut.close();
} catch (Exception e) {
}
Sensor accel = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accel,
SensorManager.SENSOR_DELAY_FASTEST);
break;
case R.id.btnStop:
btnStart.setEnabled(true);
btnStop.setEnabled(false);
// btnUpload.setEnabled(true);
started = false;
sensorManager.unregisterListener(this);
// don't need chart
// openChart();
// show data in chart
break;
// case R.id.btnUpload:
// break;
default:
break;
}
}
}
In your activity put this into your OnClick of your Startbutton:
startService(new Intent(this, BackgroundService.class));
and this to your Stopbutton:
stopService(new Intent(this, BackgroundService.class));
Create a new Class for example like the following:
public class BackgroundService extends Service implements LocationListener,
SensorEventListener{
//Hint: there are some methods you need to implement which I forgot to mention but eclipse will add them for you
#Override
public void onCreate() {
//enable networking, look into this: http://www.vogella.com/blog/2012/02/22/android-strictmode-networkonmainthreadexception/
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//do your data collecting-methods and connect to your webserver
}
#Override
public void onDestroy() {
//unregister your sensor listener
}
}
In this method I got this:
#Override
public void onSensorChanged(SensorEvent event) {
sendValuesToYourServer(Float.toString(event.values[0]) + "," + Float.toString(event.values[1]) +","+ Float.toString(event.values[2]));
}
I cannot the get the latitude and longitude of my phone when testing it on an actual phone or device, it always return null values, but when I test it on the emulator and send coordinates using DDMS, it succesfully returns the lat and long.
Here is my class:
package locateodroid.james;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.widget.EditText;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver{
public SharedPreferences prefs;
private String Keywords = "prefmode";
private Double lat;
private Double lon;
private static final String FAR_MODE_KEY = "farmode";
private Context con;
#Override
public void onReceive(Context context, Intent intent) {
con = context;
String FarModeKeyword= "";
String message = "";
String number = "";
prefs = context.getSharedPreferences(Keywords, Context.MODE_PRIVATE);
FarModeKeyword = prefs.getString(FAR_MODE_KEY, "");
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++)
{
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
message += msgs[i].getMessageBody().toString();
}
for (int i=0; i<msgs.length; i++)
{
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
number += msgs[i].getOriginatingAddress();
}
}
getLocation();
Toast.makeText(context,
lat + "_" + lon,
Toast.LENGTH_SHORT).show();
sendSMS(number, lat + "_" + lon);
}
private void sendSMS(String phoneNumber, String message)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
private getLocation ()
{
// Get the location manager
LocationManager locationManager = (LocationManager)con.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria ();
Geocoder geoCoder = new Geocoder(con);
LocationListener MyLocListener = new LocListener();
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
locationManager.requestLocationUpdates(provider, 0, 0, MyLocListener);
}
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lat = location.getLatitude();
lon = location.getLongitude();
}
public class LocListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc) {
lat = loc.getLatitude();
lon = loc.getLongitude();
}
#Override
public void onProviderDisabled(String arg0) {
// 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
}
}
}
Thanks in advance!
did you give all permission in manifest to get GPS co ordinate ? have you check whether the option of "USE GPS Settelite" in your phone is already selected or not ? Have You try getting data outside the building because GPS will not get a fix inside building.
If answer of all these questions is no. than please do that first .