I have an application and I want to use the GPS's Location. After implementing what I was taught, I have two files, VirtualAssistantActivity which uses the LocationGPS file. The second file will send the result with an intent received from the first file.
The problem is the TextView that is supposed to be edited after receiving the intent filled with the location.toString() doesn't change. After using the debug feature of Android Studio, I've found that it's like the locationManager's requestLocationUpdate is never called, I can't even get into the new LocationListener's creation.
I am using a Sony XPERIA running Android 5.0, and decided to develop targeting Android 4.0 with API 15.
Here's the VirtualAssistantActivity code :
public class VirtualAssistantActivity extends AppCompatActivity {
private LocationGPS lgps = null;
private BroadcastReceiver mLocationReceiver;
private TextView tvTest = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_virtual_assistant);
tvTest = (TextView) findViewById(R.id.tV_testGeo);
lgps = LocationGPS.get(this.getApplicationContext());
mLocationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent){
Location l = (Location)intent.getParcelableExtra(LocationManager.KEY_LOCATION_CHANGED);
if (l!=null){
tvTest.setText(""+l);
} else {
tvTest.setText("Empty intent");
}
}
};
}#Override
protected void onResume(){
super.onResume();
this.registerReceiver(mLocationReceiver, new IntentFilter(LocationGPS.ACTION_LOCATION));
lgps.startLocationUpdates();
Toast.makeText(getApplicationContext(), "BR Init", Toast.LENGTH_SHORT).show();
}
#Override
public void onPause() {
super.onPause();
//unregisterReceiver(mLocationReceiver);
}
And the LocationGPS's :
public class LocationGPS {
static LocationGPS slocationGPS = null;
Context mAppContext = null;
LocationManager mLocationManager = null;
public static String ACTION_LOCATION = "LOCATION_MSG";
private LocationGPS(Context appContext) {
mAppContext = appContext;
mLocationManager = (LocationManager)appContext.getSystemService(Context.LOCATION_SERVICE);
}
public static LocationGPS get(Context c) {
if (slocationGPS == null) {
slocationGPS = new LocationGPS(c);
}
return slocationGPS;
}
private void broadcastLocation(Location location) {
Intent broadcast = new Intent(this.ACTION_LOCATION);
broadcast.putExtra(LocationManager.KEY_LOCATION_CHANGED, location);
this.mAppContext.sendBroadcast(broadcast);
}
public void startLocationUpdates(){
if (ContextCompat.checkSelfPermission(mAppContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mAppContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationManager.requestLocationUpdates
(LocationManager.GPS_PROVIDER, 1000, 5, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
//Log.d(this.getClass().getName(), location.toString());
Log.d("GPS", "Latitude " + location.getLatitude() + " et longitude " + location.getLongitude());
Toast.makeText(mAppContext, "Location", Toast.LENGTH_SHORT).show();
broadcastLocation(location);
}
Toast.makeText(mAppContext, "Location", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
I've searched for some solutions, and while it seems to work for everyone, or at least they have some error messages, I don't know what I can do except eventually use Google's APIs, but I would prefer to avoid that. I have checked my permission, they're granted and this is a list of my imports:
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
And the permissions :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
This activity has 2 button, Start and Stop. When button start clicked, its save
user location to firebase and button stop to stop it. So, I use LocationManager.requestLocationUpdates to make every 5 second user location inserted to firebase. But this makes my app crash, here is my code
package com.example.julio.firebasemaster;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
TextView condition;
Button start;
Button stop;
DatabaseReference mDatabase;
DatabaseReference mChild;
LocationManager locationManager;
LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference();
mChild = mDatabase.child("user");
start = (Button) findViewById(R.id.btnStart);
stop = (Button) findViewById(R.id.btnStop);
permission();
start.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("MissingPermission")
#Override
public void onClick(View view) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, locationListener);
permission();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = (new LocationListener() {
#Override
public void onLocationChanged(Location location) {
String latitude = location.getLatitude() + " ";
String longitude = location.getLongitude() + " ";
HashMap<String, String> data = new HashMap<>();
data.put("latitude", latitude);
data.put("longitude", longitude);
mChild.setValue(data);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
});
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
locationManager.removeUpdates(locationListener);
}
});
}
private void permission() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
}
}
The Crush occur when I click start button
I'm using firebase assistant, so there is no problem with the initialization
Help me please, my head want to explode thinking this bug :(
Add null check inside onLocationChanged
public void onLocationChanged(Location location) {
if (location != null) {
String latitude = location.getLatitude() + " ";
String longitude = location.getLongitude() + " ";
HashMap<String, String> data = new HashMap<>();
data.put("latitude", latitude);
data.put("longitude", longitude);
mChild.setValue(data);
}
}
I hope this will help you
For some reason it only updates the textviews when the app hits onPause, like when I hit the home button, or multitasking button. Can someone help me figure out why that is?
MainActivity.java:
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private String lat, lon;
private TextView longTextView, latTextView;
LocationService locationService = new LocationService(this);
private Intent intentService;
private PendingIntent pendingIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latTextView = (TextView) findViewById(R.id.latitude_textview);
longTextView = (TextView) findViewById(R.id.longitude_textview);
}
#Override
protected void onStart() {
super.onStart();
locationService.buildGoogleApiClient();
locationService.apiConnect();
if (latTextView != null && longTextView != null) {
latTextView.setText( locationService.getLat());
longTextView.setText( locationService.getLon());
Toast.makeText(getApplicationContext(), " Actually got location", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getApplicationContext(), "The shit was null fam", Toast.LENGTH_LONG)
.show();
}
}
#Override
protected void onStop() {
super.onStop();
locationService.apiDisconnect();
}
}
LocationService.java:
import android.Manifest;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import static com.google.android.gms.wearable.DataMap.TAG;
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
// ============================================================= Variables
Context context;
Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private String lat, lon;
final static String[] LOCATION_PERMISSIONS = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
public static final long UPDATE_FASTEST_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
public static boolean isEnded = false;
public static Boolean requestingLocationUpdates;
protected String lastUpdateTime;
final int GOOGLEAPI_REQUEST_CODE = 24;
private FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
// ============================================================= Constructor
public LocationService(Context context) {
this.context = context;
}
// ============================================================= Getters / Setters
public String getLon() {
return lon;
}
public void setLon(String lon) {
this.lon = lon;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
// ============================================================= Methods
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public void apiConnect() {
mGoogleApiClient.connect();
}
public void apiDisconnect() {
mGoogleApiClient.disconnect();
}
void updateUI() {
}
// ============================================================= Implemented Location Methods
#Override
public void onLocationChanged(Location location) {
setLat(String.valueOf(location.getLatitude()));
setLon(String.valueOf(location.getLongitude()));
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); // Sets Location to update every second
mLocationRequest.setFastestInterval(UPDATE_FASTEST_INTERVAL_IN_MILLISECONDS); // The fastest location can update is every half-second
startLocationUpdates();
// TODO come back to this to see whats up
/* mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);*/
if (mLastLocation != null) {
setLat(String.valueOf(mLastLocation.getLatitude()));
setLon(String.valueOf(mLastLocation.getLongitude()));
}
}
#Override
public void onConnectionSuspended(int i) {
}
protected void startLocationUpdates() {
/*if (!requestingLocationUpdates) {
requestingLocationUpdates = true;*/
if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) context, LOCATION_PERMISSIONS, GOOGLEAPI_REQUEST_CODE);
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
Log.i(TAG, " startLocationUpdates===");
isEnded = true;
//}
}
// ============================================================= Implemented Service Methods
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Within {#code onPause()}, we pause location updates, but leave the
// connection to GoogleApiClient intact. Here, we resume receiving
// location updates if the user has requested them.
Log.d("LOC", "Service init...");
isEnded = false;
requestingLocationUpdates = false;
lastUpdateTime = "";
buildGoogleApiClient();
if (mGoogleApiClient.isConnected() && requestingLocationUpdates) {
startLocationUpdates();
}
return Service.START_REDELIVER_INTENT;
}
}
The reason why you are not getting the location updated in textview is because your code doesn't have a way for the service to communicate back to the activity.
If you want to obtain location only when the activity is in foreground don't use Service and please look into this google's example for obtaining location and updating on a TextView using fused location provider.
I am not sure why you are using a Service.Use Service only when you want to continuously fetch the location even when the app is running background.
For this use any one of the method mentioned here to inform the activity that a new location has been obtained.LocalBroadcast would be your best bet. Anyway explore the best possible solution that suits your usecase in the previous link.
i'm writing a program which i need to get the coordination of my place , latitude and longitude. my problem is i cant get the location and in my Log lat
and lng are 0 and 0 and i'm trying to run it on a nexus 6P device which is running android M 6.0.1.
here is my GPSTracker class
package es.euphrat.clover.compass;
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
private Location mLocation;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager mLocationManager;
public GPSTracker(Context context) {
mContext = context;
getLocation();
}
private Location getLocation() {
try {
mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
}
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
latitude = mLocation.getLatitude();
longitude = mLocation.getLongitude();
}
}
}
if (isGPSEnabled) {
if (mLocation == null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
latitude = mLocation.getLatitude();
longitude = mLocation.getLongitude();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return mLocation;
}
public void stopUsingGPS() {
if (mLocationManager != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mLocationManager.removeUpdates(GPSTracker.this);
}
}
}
public double getLatitude(){
if (mLocation != null){
latitude = mLocation.getLatitude();
}
return latitude;
}
public double getLongitude(){
if (mLocation != null){
longitude = mLocation.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
this is my main method which i'm Logging the result in main activity
package es.euphrat.clover.compass.activity;
import android.Manifest;
import android.content.Context;
import android.database.Cursor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import es.euphrat.clover.compass.GPSTracker;
import es.euphrat.clover.compass.R;
import es.euphrat.clover.compass.adapters.CityAdapter;
import es.euphrat.clover.compass.boxes.CityBox;
import es.euphrat.clover.compass.boxes.CompassAndCityBox;
import es.euphrat.clover.compass.boxes.DateBox;
import es.euphrat.clover.compass.boxes.DayAndNight;
import es.euphrat.clover.compass.database.City;
import es.euphrat.clover.compass.database.DataBaseHelper;
import info.alqiblah.taqwim.MA6;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
public final String TAG = this.getClass().getSimpleName();
protected DataBaseHelper mDataBaseHelper;
protected CompassAndCityBox mCompassAndCityBox;
protected DateBox mDateBox;
protected CityBox mCityBox;
protected DayAndNight mDayAndNight;
protected SensorManager mSensorManager;
protected LinearLayout myRoot;
protected DrawerLayout drawerLayout;
protected RelativeLayout gpsDrawer;
protected RelativeLayout cityListDrawer;
protected ArrayList<String> mCityNames;
protected ListView cityListView;
protected EditText searchCity;
protected City[] mCities;
private CityAdapter mCityListAdapter;
protected City currentCity;
protected GPSTracker mGPSTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath(getTypeface())
.setFontAttrId(R.attr.fontPath)
.build());
myRoot = (LinearLayout) findViewById(R.id.my_root);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
gpsDrawer = (RelativeLayout) findViewById(R.id.gps_drawer);
cityListDrawer = (RelativeLayout) findViewById(R.id.city_list_drawer);
cityListView = (ListView) findViewById(R.id.listView);
searchCity = (EditText) findViewById(R.id.search_city);
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
MA6.InitPlanetsTerms(this);
mGPSTracker = new GPSTracker(this);
mCityNames = new ArrayList<>();
mDataBaseHelper = new DataBaseHelper(this);
mCityBox = new CityBox(this);
mDateBox = new DateBox(this);
mCompassAndCityBox = new CompassAndCityBox(this);
mDayAndNight = new DayAndNight(this);
myRoot.addView(mCityBox);
myRoot.addView(mDateBox);
myRoot.addView(mCompassAndCityBox);
myRoot.addView(mDayAndNight);
searchCityTextView();
createTheDataBase();
double a = mGPSTracker.getLatitude();
if (mGPSTracker.canGetLocation()) {
Log.d(TAG, String.valueOf(mGPSTracker.canGetLocation()));
Log.d(TAG, a + "," + mGPSTracker.getLongitude());
}
}
private void createTheDataBase() {
try {
mDataBaseHelper.createDataBase();
} catch (IOException e) {
Log.e(TAG , "Cannot Create DataBase", e);
}
}
private void searchCityTextView() {
searchCity.clearComposingText();
searchCity.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Cursor cursor = mDataBaseHelper.selectOrSearchAllCities(searchCity.getText().toString());
updateList(cursor);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private void updateList(Cursor cursor) {
mCityNames.clear();
final int cityName = cursor.getColumnIndex(DataBaseHelper.CITY_NAME);
int timeZone = cursor.getColumnIndex(DataBaseHelper.CITY_TIMEZONE);
int countryName = cursor.getColumnIndex(DataBaseHelper.COUNTRY_NAME);
int lat = cursor.getColumnIndex(DataBaseHelper.CITY_LATITUDE);
int lng = cursor.getColumnIndex(DataBaseHelper.CITY_LONGITUDE);
mCities = new City[cursor.getCount()];
int c = 0;
cursor.moveToFirst();
while (!cursor.isAfterLast()){
String city = cursor.getString(cityName);
String tZone = cursor.getString(timeZone);
String country = cursor.getString(countryName);
float latitude = cursor.getFloat(lat);
float longitude = cursor.getFloat(lng);
mCities[c] = new City(city,tZone,country,latitude,longitude);
c++;
cursor.moveToNext();
}
mCityListAdapter = new CityAdapter(this, mCities);
cityListView.setAdapter(mCityListAdapter);
cityListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
currentCity = new City(mCities[position]);
drawerLayout.closeDrawer(cityListDrawer);
mCityBox.setCurrentCityName(currentCity);
hideKeyboard();
}
});
}
private void hideKeyboard() {
InputMethodManager inputManager =
(InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
public void antenaClick(View view) {
drawerLayout.openDrawer(gpsDrawer);
}
public void pinpointClick (View view){
drawerLayout.openDrawer(cityListDrawer);
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_GAME);
mDataBaseHelper.openDataBase();
Cursor cursor = mDataBaseHelper.selectOrSearchAllCities(searchCity.getText().toString());
updateList(cursor);
}
#Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
mDataBaseHelper.close();
}
#Override
public void onSensorChanged(SensorEvent event) {
float degree = Math.round(event.values[0]);
mCompassAndCityBox.setDegreeFromNorth(degree,currentCity);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
private String getTypeface(){
if( Locale.getDefault().getDisplayLanguage().toLowerCase().startsWith("en")) return "fonts/Roboto-Medium.ttf";
else return "fonts/IRAN Sans.ttf";
}
}
and this is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="es.euphrat.clover.compass">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
>
<activity android:name=".activity.MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
can any one please help me to find a solution for my problem.
RESOLVED
Singleton pattern was suggested. Not the most elegant way to solve the problem but it works. Here is the code I used. Just have to get the instance in the main and LocationService class to use. See answer for how you are suppose to do it.
import android.location.Location;
public class LocationSingleton {
private Location location;
private static LocationSingleton singleton = new LocationSingleton();
private LocationSingleton(){
}
public static LocationSingleton getInstance( ) {
return singleton;
}
protected void setLocation(Location newLocation) {
this.location = newLocation;
}
protected Location getLocation(){
return this.location;
}
}
Attempting to use a background service to handle Location updates. I create a service in Main that updates the data (working correctly I believe) but I also have a button in main that whenever pressed does some work with the location data. I can't figure out though how to pass the Location from the service back to main. I've tried passing Main to the service but that didn't work and always created the service using the constructor without main passed. I've also tried creating a method in the service that returns the location but that kept getting a null pointer exception. How does one go about doing this.
Service Class
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationListener;
import java.util.Locale;
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private String TAG = "LocationService";
private GoogleApiClient mGoogleApiClient;
private static final long INTERVAL = 1000 * 15;
private static final long FATEST_INTERVAL = 1000 * 30;
private LocationRequest mLocationRequest;
private Location mCurrentLocation;
private Geocoder geocoder;
AddressStringOperations addressOps;
TimerUpdate timerUpdate;
Context mainContext;
MainActivity act;
public LocationService(MainActivity act) {
this.mainContext = mainContext;
Log.e(TAG, "Correct Constructor");
}
public LocationService(){
Log.e(TAG, "Shouldn't use");
}
#Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate");
this.geocoder = new Geocoder(this, Locale.getDefault());
addressOps = new AddressStringOperations(this.geocoder);
this.timerUpdate = new TimerUpdate(this, addressOps);
timerUpdate.startTimer();
mGoogleApiClient = new GoogleApiClient.Builder(LocationService.this)
.addApi(LocationServices.API).addConnectionCallbacks(LocationService.this)
.addOnConnectionFailedListener(LocationService.this).build();
mGoogleApiClient.connect();
createLocationRequest();
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
Log.e(TAG, "Service Started");
return super.onStartCommand(intent, flags, startId);
}
protected void createLocationRequest(){
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public Location getLocation(){
Log.e(TAG, "Latitude: "+ mCurrentLocation.getLatitude() + "\n" + "Longitude: " + mCurrentLocation.getLatitude());
return this.mCurrentLocation;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onConnected(Bundle bundle) {
Log.e(TAG, "Connection Successful");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.e(TAG, "Connection Lost");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "Connection Failed");
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "Firing onLocationChanged.........");
//Log.e(TAG, "Latitude: "+ location.getLatitude() + "\n" + "Longitude: " + location.getLatitude());
timerUpdate.location = location;
mCurrentLocation = location;
}
}
Main Class
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.location.Geocoder;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import java.util.Locale;
public class MainActivity extends Activity {
private Button bLogout, bWebsite;
private ImageButton bLogData;
private TextView etLabel;
private UserLocalStore userLocalStore;
private static final String TAG = "MainActivity";
TimerUpdate timerUpdate;
Geocoder geocoder;
Location location;
AddressStringOperations addressOps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e(TAG, "On Create . . . . .");
if(!isGooglePlayServicesAvailable()){
startActivity(new Intent(MainActivity.this, login.class));
Log.e(TAG, "No GooglePlayServices");
finish();
Toast.makeText(getApplicationContext(), "Please update GooglePlay Servies to use this Application", Toast.LENGTH_LONG).show();
}else{
userLocalStore = new UserLocalStore(this);
this.geocoder = new Geocoder(this, Locale.getDefault());
addressOps = new AddressStringOperations(this.geocoder);
this.timerUpdate = new TimerUpdate(this, addressOps, false);
if (authenticate() != true) {
startActivity(new Intent(MainActivity.this, login.class));
Log.e(TAG, "Authenticate is not true");
finish();
} else {
etLabel = (TextView) findViewById(R.id.etEmailLabel);
bLogout = (Button) findViewById(R.id.bLogout);
bLogData = (ImageButton) findViewById(R.id.DataLog);
bWebsite = (Button) findViewById(R.id.website);
LocationService service = new LocationService(MainActivity.this);
Intent start = new Intent(MainActivity.this, LocationService.class);
MainActivity.this.startService(start);
bLogData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String pressStatus = "3";
Log.e(TAG, "Latitude: "+ location.getLatitude() + "\n" + "Longitude: " + location.getLatitude());
timerUpdate.update(pressStatus);
}
});
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
userLocalStore.clearuserData();
userLocalStore.setUserLoggedIn(false);
startActivity(new Intent(MainActivity.this, login.class));
finish();
}
});
bWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("temp"));
startActivity(browserIntent);
}
});
}
}
}
public void setLocation(Location newLocation){
this.location = newLocation;
}
}
You can do that in multiple ways. You can create a Receiver and broadcast and intent from there or you can use an EventBus ( https://github.com/greenrobot/EventBus ).
In this case I think it's more appropriate the Service/Receiver model, you can find here an example: http://www.truiton.com/2014/09/android-service-broadcastreceiver-example/
If you need it only in one activity, consider to use an AsyncTask and handle the output in the postExecute method, it would be a lot easier.
My Application crashes when gps is off and the back end code searches for the location of the user. I have tried the following code for finding the location of user when gps is off it searches using the internet.
Please suggest something in the following code or any other way
below is my code for the locationservice:
package com.example.myapp;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
public class LocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public LocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}