Android: Location updating very slowly - android

I am trying to create an app that sends to my server the location of my android device on button press. Unfortunately the location updates very slowly, sometimes taking minutes and tens of meters to get the new location.
I'm relatively new to Android programming and if anyone could help me with a way to update the location every time when press the send button I would be grateful.
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
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 android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import org.json.*;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
public class DefaultActivity extends AppCompatActivity {
private String serverURL;
private TextView tv_Title, tv_Status;
private Button b_SendLocation, b_SendNow, b_StopLocation;
private User user;
private FusedLocationProviderClient locationClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_default);
Intent intent = getIntent();
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
locationClient = LocationServices.getFusedLocationProviderClient(this);
serverURL = intent.getExtras().getString("serverURL");
JSONParse(intent.getExtras().getString("myResponse"));
tv_Title = findViewById(R.id.TextView_Title);
tv_Status = findViewById(R.id.TextView_Status);
b_SendLocation = findViewById(R.id.Button_SendLocation);
b_SendNow = findViewById(R.id.Button_SendNow);
b_StopLocation = findViewById(R.id.Button_StopLocation);
tv_Title.setText(user.getLastName() + " " + user.getFirstName());
tv_Status.setText(" ");
b_SendLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Feedback("Sending location every 5 sec.");
}
});
b_SendNow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Feedback("Current location sent!");
GetLocation();
}
});
b_StopLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Feedback("Periodic sending halted!");
}
});
}
private void GetLocation() {
if (ActivityCompat.checkSelfPermission(DefaultActivity.this, ACCESS_FINE_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;
}
locationClient.getLastLocation().addOnSuccessListener(DefaultActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null){
double latitude, longitude;
latitude = location.getLatitude();
longitude = location.getLongitude();
tv_Status.setText("Latitude: " + latitude + "\nLongitude: " + longitude);
SendLocation(latitude, longitude);
}
else
tv_Status.setText("Location is null!");
}
});
}
private void SendLocation(double latitude, double longitude){
OkHttpClient client = new OkHttpClient();
String url = serverURL + "/api/user/?id=" + user.getID() + "&latitude=" + latitude + "&longitude=" + longitude;
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e){
e.printStackTrace();
runOnUiThread(new Runnable() {
#Override
public void run() {
tv_Status.append("\n\n Server error!");
}
});
}
#Override
public void onResponse(Call call, Response response) throws IOException{
if (response.isSuccessful()){
runOnUiThread(new Runnable() {
#Override
public void run() {
tv_Status.append("\n\n Server acknowledged!");
}
});
}
}
});
}
private void JSONParse(String JSONString){
User readUser = new User();
try {
JSONObject obj = new JSONObject(JSONString);
readUser.setID(Integer.parseInt(obj.getString("ID")));
readUser.setFirstName(obj.getString("FirstName"));
readUser.setLastName(obj.getString("LastName"));
readUser.setEmail(obj.getString("Email"));
readUser.setPassword(obj.getString("Password"));
readUser.setRole(obj.getString("Role"));
Feedback("Welcome back " + readUser.getFirstName() + "!");
} catch (JSONException e) {
Feedback("JSON Exception!");
e.printStackTrace();
}
user = readUser;
}
private void Feedback(String message){
Toast toast=Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG);
toast.show();
}
}

Related

How to get current location in android with LocationManager

Whenever I use LocationManager and LocationListener,
while using the AndroidEmulator, I get the location,
using the extra tools when I set the latitude and longitude
I checked out other question-answers but i am new to Android Development so i really could not understand the answer. so i raised a new question, i would appreciate the review of my code. Thanks.
but when I run on a physical device my code does not give me my current location on start. How do I get the current location? I also tried getLastKnownLocation but even that does not work.
package com.londonappbrewery.climapm;
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.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONObject;
import cz.msebera.android.httpclient.Header;
public class WeatherController extends AppCompatActivity {
// Constants:
final String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather";
// App ID to use OpenWeather data
final String APP_ID = "5563c6a4ddd7d7181b257988cc2b1ad1";
// Time between location updates (5000 milliseconds or 5 seconds)
final long MIN_TIME = 5000;
// Distance between location updates (1000m or 1km)
final float MIN_DISTANCE = 1000;
//Request Code
final int REQUEST_CODE = 123;
// TODO: Set LOCATION_PROVIDER here:
String LOCATION_PROVIDER = LocationManager.GPS_PROVIDER;
// Member Variables:
TextView mCityLabel;
ImageView mWeatherImage;
TextView mTemperatureLabel;
// TODO: Declare a LocationManager and a LocationListener here:
LocationManager mLocationManager;
LocationListener mLocationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather_controller_layout);
// Linking the elements in the layout to Java code
mCityLabel = (TextView) findViewById(R.id.locationTV);
mWeatherImage = (ImageView) findViewById(R.id.weatherSymbolIV);
mTemperatureLabel = (TextView) findViewById(R.id.tempTV);
ImageButton changeCityButton = (ImageButton) findViewById(R.id.changeCityButton);
// TODO: Add an OnClickListener to the changeCityButton here:
changeCityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(WeatherController.this, ChangeCityController.class);
startActivity(intent);
}
});
}
// TODO: Add onResume() here:
#Override
protected void onResume() {
super.onResume();
Log.d("Clima", "onResume() called");
Intent intent = getIntent();
String cityName = intent.getStringExtra("cityName");
if (cityName != null) {
//Log.d("Clima", cityName);
getWeatherForNewCity(cityName);
} else {
Log.d("Clima", "Getting weather for current location");
getWeatherForCurrentLocation();
}
}
// TODO: Add getWeatherForNewCity(String city) here:
private void getWeatherForNewCity(String city) {
RequestParams params = new RequestParams();
params.put("q", city);
params.put("appid", APP_ID);
letsDoSomeNetworking(params);
}
// TODO: Add getWeatherForCurrentLocation() here:
private void getWeatherForCurrentLocation() {
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//Log.d("Clima", "");
String latitude = String.valueOf(location.getLatitude());
String longitude = String.valueOf(location.getLongitude());
Log.d("Clima", "onLocationChanged() callback received");
Log.d("Clima", "Latitude is " + latitude);
Log.d("Clima", "Longitude is " + longitude);
RequestParams params = new RequestParams();
params.put("lat", latitude);
params.put("lon", longitude);
params.put("appid", APP_ID);
letsDoSomeNetworking(params);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Clima", "onProviderDisabled() callback received");
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
return;
}
mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, MIN_TIME, MIN_DISTANCE, mLocationListener);
Location location = mLocationManager.getLastKnownLocation(LOCATION_PROVIDER);
if(location != null) {
RequestParams params = new RequestParams();
params.put("lat", location.getLatitude());
params.put("lon", location.getLongitude());
params.put("appid", APP_ID);
letsDoSomeNetworking(params);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("Clima", "onRequestPermissionResult(): Permission Granted!");
//mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, MIN_TIME, MIN_DISTANCE, mLocationListener);
getWeatherForCurrentLocation();
}
}
}
// TODO: Add letsDoSomeNetworking(RequestParams params) here:
private void letsDoSomeNetworking(RequestParams params) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(WEATHER_URL, params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] header, JSONObject response) {
Log.d("Clima", "Success! JSON : " + response.toString());
WeatherDataModel weatherData = WeatherDataModel.fromJSON(response);
// Log.d("Clima", weatherData.getTemperature()); << WORKING
updateUI(weatherData);
}
#Override
public void onFailure(int statusCode, Header[] header, Throwable e, JSONObject response) {
Log.e("Clima", e.toString());
Log.d("Clima", String.valueOf(statusCode));
Toast.makeText(WeatherController.this, "Request Failed!", Toast.LENGTH_SHORT).show();
}
});
}
// TODO: Add updateUI() here:
private void updateUI(WeatherDataModel weatherData){
mTemperatureLabel.setText(weatherData.getTemperature());
mCityLabel.setText(weatherData.getCity());
int resourceID = getResources().getIdentifier(weatherData.getIconName(), "drawable", getPackageName());
mWeatherImage.setImageResource(resourceID);
}
// TODO: Add onPause() here:
}
What should I do to get the location as soon as the app starts?
P.S. permissions are in place so it isn't an issue of permissions.
LocationManager locationManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
boolean networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location location;
if(networkEnabled){
longitude=location.getLongitude();
latitude=location.getLatitude();
}
}
Add these permissions in your manifest file:-
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Unable to instantiate a service which sends data to firebase.

My service stops running after i ran the app.
The Log shows a runtime error which says the following lines
java.lang.RuntimeException: Unable to instantiate service com.example.hp.newtrial.Service_Location: java.lang.NullPointerException
The code for the activity and the service is shared. The manifest is also given for reference.
I am basically trying to upload data to firestore at particular intervals but this error keeps showing up.
My Main Activity code which call for the service
package com.example.hp.newtrial;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.FirebaseApp;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity_Log";
private LocalBroadcastManager manager;
private BroadcastReceiver receiver;
double latitude, longitude;
//Location location;
//private Service_Location service_location;
//creating class
//public MyBroadcastReceiver myBroadcastReceiver;
EditText nameUser;
Button click;
String userName;
// Access a Cloud Firestore instance from your Activity
String reference_id;
Intent intents;
FirebaseFirestore db;
ServiceConnection mServiceConn;
#Override
protected void onStart() {
super.onStart();
FirebaseApp.initializeApp(this);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseApp.initializeApp(this);
// service_location = new Service_Location();
db = FirebaseFirestore.getInstance();
nameUser = findViewById(R.id.usrName);
click = findViewById(R.id.button_3);
Log.d(TAG, "Main Activity");
try {
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}, 1);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}
} catch (Exception e) {
Log.d(TAG, "Error: ", e);
}
//to start the service . . . .
try {
intents = new Intent(MainActivity.this, Service_Location.class);
//bindService(intents, mServiceConn, BIND_AUTO_CREATE);
startService(intents);
} catch (Exception e) {
Log.d(TAG, String.valueOf(e));
}
/*try {
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("Location"));
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle b = intent.getExtras();
if (b != null) {
latitude = b.getDouble("latitude");
longitude = b.getDouble("longitude");
}
Log.d("MainActivity", "Latitude: " + latitude + " Longitude:" + longitude);
Toast.makeText(MainActivity.this, "Location: Latitude: " + latitude + " Longitude: " + latitude, Toast.LENGTH_LONG).show();
}
};
} catch (Exception e) {
Log.d("MainActivity", String.valueOf(e));
}*/
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//to Firebase . . . .
try {
userName = String.valueOf(nameUser.getText());
Map<String, Object> data = new HashMap<>();
data.put("UserName", userName);
Map<String, Object> data2 = new HashMap<>();
data.put("UserName", "Akshansh");
db.collection("Users").add(data).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
//Getting the reference id . . . .
reference_id = documentReference.getId();
intents.putExtra("Reference_id", reference_id);
startService(intents);
Log.d(TAG, documentReference.getId());
Log.d(TAG, "On Success Listener :: document Added . .. . ");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "On Failure Listener some trouble");
}
});
} catch (Exception e) {
Log.d(TAG, "Error " + String.valueOf(e));
}
}
});
}
}
And here is the code of my service
package com.example.hp.newtrial;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.FirebaseApp;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.WriteBatch;
import java.io.FileDescriptor;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class Service_Location extends Service implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
public static Location mCurrentLocation;
long BACKGROUND_INTERVAL = 5000;
Context context;
String TAG = "Service_Location";
Intent send = new Intent("Location");
Handler handler;
String reference_id;
IBinder binder;
//Firebase Reference . . . .
private FirebaseFirestore db;
private DocumentReference documentReference;
//We'll try to use batch to perform what we need . . . .
WriteBatch batch = Objects.requireNonNull(db).batch();
public Service_Location() {
super();
}
//Google Api Connection . . .
#SuppressLint("RestrictedApi")
#Override
public void onCreate() {
super.onCreate();
//initializing app
FirebaseApp.initializeApp(this);
db = FirebaseFirestore.getInstance();
try {
Log.d(TAG, "onCreate()");
LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
assert locationManager != null;
boolean isGPSenabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSenabled) {
showSettingDialog();
}
} catch (Exception e) {
Log.d(TAG, String.valueOf(e));
}
//show error dialog if GoolglePlayServices not available
try {
if (isGooglePlayServicesAvailable()) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(BACKGROUND_INTERVAL);
mLocationRequest.setFastestInterval(BACKGROUND_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//mLocationRequest.setSmallestDisplacement(10.0f); /* min dist for location change, here it is 10 meter */
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
} catch (Exception e) {
Log.d(TAG, String.valueOf(e));
}
handler = new Handler(getMainLooper());
}
private void showSettingDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("GPS is setting");
alertDialog.setMessage("GPS not enabled!!!");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
alertDialog.show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Data received from intent Reference_id:" + intent.getStringExtra("Reference_id"));
reference_id = intent.getStringExtra("Reference_id");
return START_STICKY;
}
private boolean isGooglePlayServicesAvailable() {
Log.d(TAG, "isGooglePlayServicesAvailable()");
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
return ConnectionResult.SUCCESS == status;
}
//Service
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
//Location Listener. . .
#Override
public void onLocationChanged(final Location location) {
try {
if (reference_id != null) {
documentReference = db.collection("Users").document(reference_id);
//update(location);
//now trying with batch. . .
updateBatch(location);
}
Log.d(TAG, "OnLocationChanged()");
Log.d(TAG, "Latitude: " + location.getLatitude() + " Longitude: " + location.getLongitude());
} catch (Exception e) {
Log.d(TAG, String.valueOf(e));
}
handler.post(new Runnable() {
#Override
public void run() {
//Toast.makeText(getApplicationContext(), "this helps", Toast.LENGTH_LONG).show();
}
});
}
private void updateBatch(Location location) {
Log.d(TAG, "inside updateBatch");
try {
LatLng lng = new LatLng(location.getLatitude(), location.getLongitude());
Map<String, LatLng> map = new HashMap<>();
map.put("Location", lng);
batch.update(documentReference, "Location", map);
} catch (Exception e) {
Log.d(TAG, String.valueOf(e));
}
}
private void update(Location location) {
Log.d(TAG, "Updating Location");
LatLng lng = new LatLng(location.getLatitude(), location.getLongitude());
Map<String, LatLng> map = new HashMap<>();
map.put("Location", lng);
documentReference.set(map).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("Location", "Added Successfully. . ");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("Location", "Failed ");
}
});
}
/
//Google API Client
public void onConnected(Bundle bundle) {
Log.d(TAG, "On_Connected()");
startLocationUpdates();
}
protected void startLocationUpdates() {
try {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
} catch (Exception e) {
Log.d("Service", String.valueOf(e));
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
The Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hp.newtrial">
<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" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<service android:name=".Service_Location" />
</application>
</manifest>
I don't understand what to do next . . .
Any working suggestion is acceptable
Try to ask runtime permissions like this. First add run time permission in onCreate()
private static final int LOCATION_PERMISSI0N = 2002;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSI0N);
}
else
{
startService();
}
now outside onCreate() method add this startService() method
public void startService()
{
try {
Intent intents = new Intent(MainActivity.this, Service_Location.class);
//bindService(intents, mServiceConn, BIND_AUTO_CREATE);
startService(intents);
} catch (Exception e) {
Log.d(TAG, String.valueOf(e));
}
}
handle granted permission by overriding this method outside onCreate()
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case LOCATION_PERMISSI0N:
{
if (grantResults.length > 0)
{
boolean course_location = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (course_location)
{
startService();
}
else
{
Log.d("locationpermissions","Location Permission Denied");
}
}
break;
}
}
}
this must start your service..

How to update weather with onCreate()?

I've been working on a weather app, and I know it's not perfect (I'm just starting out with android development), but I'm not sure how to update the weather info on every startup. I tried to keep everything in the onCreate() method, but it just "sticks" on the location and conditions that I used when I first started.
I have been able to work around this with a button that gets the new location and weather conditions when it is pressed, but that's not very intuitive. I'm wondering how I can get new conditions on app startup. Might it involve calling onRestart()?
Here's my only activity in the app:
package com.photonfighterlabs.dropweather;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.ftoslab.openweatherretrieverz.CurrentWeatherInfo;
import com.ftoslab.openweatherretrieverz.OpenWeatherRetrieverZ;
import com.ftoslab.openweatherretrieverz.WeatherCallback;
import com.ftoslab.openweatherretrieverz.WeatherUnitConverter;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WeatherActivity extends Activity {
private double lat;
private double lng;
private String temp;
private String icon;
private TextView tempTextView;
private TextView cityTextView;
private TextView conditionsTextView;
private int LOCATION_PERMISSION_ID = 1001;
CurrentWeatherInfo currentWeatherInfoF;
private String city;
private List<Address> addresses;
private FusedLocationProviderClient mFusedLocationClient;
OpenWeatherRetrieverZ retriever;
ImageView image;
Geocoder geocoder;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_weather);
retriever = new OpenWeatherRetrieverZ(API_KEY); // hidden for obvious reasons, but working
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
geocoder = new Geocoder(this, Locale.getDefault());
tempTextView = (TextView) findViewById(R.id.temp_text_view);
cityTextView = (TextView) findViewById(R.id.city_text_view);
conditionsTextView = (TextView) findViewById(R.id.conditions_text_view);
image = (ImageView) findViewById(R.id.conditions_image);
if (ContextCompat.checkSelfPermission(WeatherActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(WeatherActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_ID);
return;
}
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null)
lat = location.getLatitude();
lng = location.getLongitude();
try {
addresses = geocoder.getFromLocation(lat, lng, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (!addresses.isEmpty()) {
city = addresses.get(0).getLocality();
cityTextView.setText("Current Weather - " + city);
Log.d("City", city);
}
Log.d("LAT", String.valueOf(lat));
Log.d("LNG", String.valueOf(lng));
}
});
retriever.updateCurrentWeatherInfo(lat, lng, new WeatherCallback() {
#Override
public void onReceiveWeatherInfo(CurrentWeatherInfo currentWeatherInfo) {
currentWeatherInfoF = WeatherUnitConverter.convertToImperial(currentWeatherInfo);
}
#Override
public void onFailure(String error) {
Toast.makeText(WeatherActivity.this, error, Toast.LENGTH_SHORT).show();
}
});
}
public void onRetrieveButtonClick(View view) {
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null)
lat = location.getLatitude();
lng = location.getLongitude();
try {
addresses = geocoder.getFromLocation(lat, lng, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (!addresses.isEmpty()) {
city = addresses.get(0).getLocality();
cityTextView.setText("Current Weather - " + city);
Log.d("City", city);
}
Log.d("LAT", String.valueOf(lat));
Log.d("LNG", String.valueOf(lng));
}
});
retriever.updateCurrentWeatherInfo(lat, lng, new WeatherCallback() {
#Override
public void onReceiveWeatherInfo(CurrentWeatherInfo currentWeatherInfo) {
currentWeatherInfoF = WeatherUnitConverter.convertToImperial(currentWeatherInfo);
}
#Override
public void onFailure(String error) {
Toast.makeText(WeatherActivity.this, error, Toast.LENGTH_SHORT).show();
}
});
temp = currentWeatherInfoF.getCurrentTemperature();
Log.d("TMP : ", String.valueOf(temp));
tempTextView.setText( String.valueOf((int) Double.parseDouble(temp)) + (char) 0x00B0);
conditionsTextView.setText(currentWeatherInfoF.getWeatherDescriptionLong());
String iconURL = currentWeatherInfoF.getWeatherIconLink().toString();
Pattern p = Pattern.compile("\\d\\w(n|d)");
Matcher m = p.matcher(iconURL);
if (m.find()) {
icon = m.group();
Log.d("ICON", icon);
String iconName = "r" + icon;
image.setImageResource(getResources().getIdentifier(iconName, "drawable", getPackageName()));
Log.d("NAME", iconName);
}
}
}
getLastLocation() and updateCurrentWeatherInfo(...) are both asynchronous operations. You start them both at the same time which means that updateCurrentWeatherInfo will most likely run before the position is available.
You must start it only after you have got the position, for example from the onSuccess listener.
You have tried with onResume() method?
You can use it and when the view is visible wi
Awareness offers a snapshot-API for obtaining the weather via getWeather() API method at the device location without managing location access or integrating with APIs that query weather from server on-demand.
Illustrative code-snippet:
Awareness.SnapshotApi.getWeather(mGoogleApiClient)
.setResultCallback(new ResultCallback<WeatherResult>() {
#Override
public void onResult(#NonNull WeatherResult weatherResult) {
if (!weatherResult.getStatus().isSuccess()) {
Log.e(TAG, "Could not get weather.");
return;
}
Weather weather = weatherResult.getWeather();
Log.i(TAG, "Weather: " + weather);
}
});
Please refer here for description of the Weather class whose instance is returned by the API.
The advantage of using this is that you can massively simplify your code, avoid having to manage location requests and call the API as often as needed (I believe it has a cache to avoid too many network requests that are battery draining).

how to get real time geolocation with movings(like google maps) on android with movings

I'm new to android and I'm creating an application based on GPS . So i have implement Google maps and location point identifier on my application but it takes only my first attempt geo location , when I'm moving it is not get updated . please help me to solve this . Thank you.
package com.android.locationtracker;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.android.app.AppConst;
import com.android.app.AppController;
import com.android.common.GPSTracker;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
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 com.google.android.gms.maps.model.PolylineOptions;
public class NearByActivity extends Activity {
private static final String TAG = "error";
private GoogleMap googleMap;
private static String URL = AppConst.GEOMETRY;
private static String URL_UPDATE = AppConst.GEOMETRY_UPDATE;
private String jsonResponse;
private ProgressDialog pDialog;
GPSTracker gps;
double latitude;
double longtitude;
String id;
String type;
List<Marker> markerList = new ArrayList<Marker>();
Marker marker;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nearby_activity);
try {
// Loading map
initilizeMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
gps = new GPSTracker(this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longtitude = gps.getLongtitude();
} else {
gps.showSettingAllerts();
}
new LoadGeo().execute();
}
private void initilizeMap() {
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onResume() {
super.onResume();
initilizeMap();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
private class LoadGeo extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NearByActivity.this);
pDialog.setMessage("Loading...");
pDialog.show();
//
}
#Override
protected Void doInBackground(Void... arg0) {
SharedPreferences prefs = getSharedPreferences("conetext",
Context.MODE_PRIVATE);
id = prefs.getString("userid", null);
type = prefs.getString("persontype", null);
Map<String, String> params = new HashMap<String, String>();
params.put("userid", id);
params.put("usertype", type);
params.put("lat", String.valueOf(latitude));
params.put("lng", String.valueOf(longtitude));
JsonObjectRequest req = new JsonObjectRequest(URL_UPDATE,
new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("map", "msg");
VolleyLog.v("Response:%n %s",
response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
AppController.getInstance().addToRequestQueue(req);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Thread thread = new Thread() {
#Override
public void run() {
try {
while (true) {
sleep(1000);
JsonArrayRequest req = new JsonArrayRequest(URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(
JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
markerList.clear();
googleMap.clear();
for (int i = 0; i < response
.length(); i++) {
JSONObject geo = (JSONObject) response
.get(i);
String usertype = geo
.getString("UserType");
MarkerOptions markerblue = new MarkerOptions();
markerblue.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
markerblue.position(new LatLng(latitude, longtitude));
googleMap.addMarker(markerblue);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
latitude, longtitude), 17));
if (usertype
.equals("driver")) {
double lat = geo
.getDouble("Lat");
double lng = geo
.getDouble("Lng");
MarkerOptions markerop = new MarkerOptions();
markerop.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
markerop.position(
new LatLng(lat,
lng))
.draggable(true)
.visible(true);
marker= googleMap
.addMarker(markerop);
markerList.add(marker);
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(
getApplicationContext(),
"Error: "
+ e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(
VolleyError error) {
VolleyLog.d(
TAG,
"Error: "
+ error.getMessage());
Toast.makeText(
getApplicationContext(),
error.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
}
}
You need to register LocationListener and implement method
#Override
public void onLocationChanged(Location location) {
//smth like this
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongtitude()), 17));
}
detailed info is here https://developer.android.com/training/location/receive-location-updates.html
You need to execute this code in specific interval
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longtitude = gps.getLongtitude();
} else {
gps.showSettingAllerts();
}
new LoadGeo().execute();
i would suggest use Handler.postDelayed(Runnable,Interval) method to work this out.
You can use Location service. Here is the code for that:
Call this function by giving a desired frequency (in mins):
private void requestLocation(Context context, int frequency) //frequency in mins
{
LocationMgr loc_mgr = new LocationMgr(context);
loc_mgr.requestLocationUpdates(frequency);
}
Here is the LocationMgr class:
public class LocationMgr implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
{
private final Context context;
private GoogleApiClient googleApiClient;
private boolean inProgress;
public enum REQUEST_TYPE {START, STOP, LAST_KNOWN}
private REQUEST_TYPE requestType;
private Intent intent;
LocationRequest mLocationRequest;
LocationListener ll;
public LocationMgr(Context context)
{
this.context = context;
this.googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
intent = new Intent(context, LocationService.class);
inProgress = false;
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
inProgress = false;
}
#Override
public void onConnectionSuspended(int arg0) {
googleApiClient.connect();
}
#Override
public void onConnected(Bundle connectionHint) {
PendingIntent pendingIntent = PendingIntent.getService(context, 123, intent, PendingIntent.FLAG_UPDATE_CURRENT);
switch (requestType)
{
case START :
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, pendingIntent);
break;
case STOP :
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, pendingIntent);
break;
case LAST_KNOWN :
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
ll.onNewLocationUpdate(location);
break;
default :
log.e("Unknown request type in onConnected().");
break;
}
inProgress = false;
googleApiClient.disconnect();
}
/**
*
* #param frequency (minutes) minimum time interval between location updates
*/
public void requestLocationUpdates(int frequency)
{
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(frequency * 60 * 1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(1000);
if (inProgress)
{
log.e("A request is already underway");
return;
}
inProgress = true;
requestType = REQUEST_TYPE.START;
googleApiClient.connect();
}
public void removeContinuousUpdates()
{
if (inProgress)
{
log.e("A request is already underway");
return;
}
inProgress = true;
requestType = REQUEST_TYPE.STOP;
googleApiClient.connect();
}
public void getLastKnownLocation(LocationListener ll)
{
this.ll = ll;
if (inProgress)
{
log.e("A request is already underway");
return;
}
inProgress = true;
requestType = REQUEST_TYPE.LAST_KNOWN;
googleApiClient.connect();
}
}
Here is the LocationService class:
public class LocationService extends IntentService
{
public LocationService()
{
super("NOTIFICATION_SERVICE");
}
/**
* Called when a new location update is available.
*/
#Override
protected void onHandleIntent(Intent intent)
{
LocationListener ll = new LocationListener()
{
#Override
public void onNewLocationUpdate(Location location)
{
// here you will get the latest location
}
};
LocationMgr lm = new LocationMgr(getApplicationContext());
lm.getLastKnownLocation(ll);
}
}

App works in emulator but crashes in real device

I have an app that shows user's current location on google map, the app runs in emulator (though it doesn't show location) however it crashes in real device.
Here is the error I'm getting
01-04 15:00:59.509 26494-26494/io.xgear.geotag E/AndroidRuntime: FATAL
EXCEPTION: main java.lang.RuntimeException: Unable to start activity
ComponentInfo{io.xgear.geotag/io.xgear.geotag.MainActivity}:
java.lang.NullPointerException
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1659)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
at android.app.ActivityThread.access$1500(ActivityThread.java:121)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at io.xgear.geotag.MainActivity.onCreate(MainActivity.java:72)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675) 
at android.app.ActivityThread.access$1500(ActivityThread.java:121) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:943) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:130) 
at android.app.ActivityThread.main(ActivityThread.java:3701) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:507) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624) 
at dalvik.system.NativeStart.main(Native Method)
 
and here's my code for main activity
package io.xgear.geotag;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import android.support.v4.app.Fragment;
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.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import io.xgear.geotag.helper.Post;
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
private GeoTagTask mAuthTask = null;
//GPSTracker gps;
private JSONObject jsonObj;
// UI references.
private EditText txtShopCode;
private EditText lblAddress;
private View mProgressView;
private View mGeoTagForm;
private Button btnGeoTag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
txtShopCode = (EditText) findViewById(R.id.txtShopCode);
btnGeoTag = (Button) findViewById(R.id.btnGeoTag);
mGeoTagForm = (View) findViewById(R.id.geoTagForm);
mProgressView = findViewById(R.id.geoTagProgress);
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
// gps = new GPSTracker(MainActivity.this);
btnGeoTag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String shopid = txtShopCode.getText().toString();
boolean cancel = false;
View focusView = null;
//txtShopCode.setInputType(InputType.TYPE_CLASS_NUMBER);
if (TextUtils.isEmpty(shopid)) {
txtShopCode.setError(getString(R.string.error_field_required));
focusView = txtShopCode;
cancel = true;
}
else {
showProgress(true);
mAuthTask = new GeoTagTask(shopid);
mAuthTask.execute((Void) null);
}
}
});
}
//
// public void btnGeoTag_Click(View v){
//
// }
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
mGeoTagForm.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private final String shopCode;
// private String lat= Double.toString( gps.getLatitude());
// private String lng = Double.toString( gps.getLongitude());
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
// double longitude = location.getLongitude();
private boolean isConnect;
GeoTagTask(String shopId) {
shopCode = shopId;
isConnect = false;
}
#Override
protected Boolean doInBackground(Void... params) {
boolean res = false;
try {
ContentValues nameValuePairs = new ContentValues();
nameValuePairs.put("Id", shopCode);
nameValuePairs.put("lat", lat);
nameValuePairs.put("lng", lng);
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
Log.i("Latitude", lat+"");
Post post = new Post(getApplicationContext());
String result = "";
// isConnect = post.isConnected();
// if(isConnect) {
result = post.doPost(nameValuePairs);
jsonObj = new JSONObject(result);
Log.i("Result", result+"");
if(jsonObj.getInt("success") == 1)
res = true;
// }
} catch (JSONException e) {
e.printStackTrace();
}
return res;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
// Intent intent = new Intent(LoginActivity.this, MainActivity.class);
// intent.putExtra("jsonObj", jsonObj.toString());
// startActivity(intent);
txtShopCode.getText().clear();
txtShopCode.requestFocus();
Toast.makeText(getBaseContext(), "Your shop is geo tagged ", Toast.LENGTH_LONG).show();
} else {
// if(isConnect){
// mPasswordView.setError(getString(R.string.error_incorrect_password));
// mPasswordView.requestFocus();
// }
// else
Toast.makeText(getBaseContext(), R.string.geoTagError, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
}
why is google map null? I'm using API in my meta deta
Change you or on create to start with
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Remove additional setContentView calls.
Use getMapAsyc to handle asynchronous map initialization:
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
supportMapFragment.getMapAsync(new OnMapReadyCallback(){
#Override
public void onMapReady(final GoogleMap map) {
map.setMyLocationEnabled(true);
}
});

Categories

Resources