This question is asked here many times,I tried all the answers but none of them worked.
I'm getting this error: Error inflating class fragment.
Mapsactivity:
package com.example.gio.autostop;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Geocoder;
import android.location.Location;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
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.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.NetworkInterface;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class MapsActivity extends FragmentActivity implements LocationListener,
GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback, GoogleMap.OnMyLocationButtonClickListener,
GoogleApiClient.ConnectionCallbacks {
public int permissionRequestCounter;
public GoogleApiClient mGoogleApiClient;
public Boolean startedLocationUpdate;
public LocationRequest locationRequest;
public Location mCurrentLocation;
public LocationManager mLocationManager;
public final static int MILISECONDS_PER_SECOND = 1000;
public final static int REQUEST_FINE_LOCATION = 0;
public final static int MINUTE = 60 * MILISECONDS_PER_SECOND;
protected String mLastUpdateTime;
protected final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
protected final static String LOCATION_KEY = "location-key";
protected static final String ADDRESS_REQUESTED_KEY = "address-request-pending";
protected static final String LOCATION_ADDRESS_KEY = "location-address";
protected static final String TAG = "main-activity";
public address_fragment address_fragment;
private GoogleMap mMap;// Might be null if Google Play services APK is not available.
private Button checkInButton,checkOutButton;
private ArrayList<Marker> markerCollection = new ArrayList<>();
private Marker markerForDeletion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
checkInButton = (Button) findViewById(R.id.button2);
checkOutButton=(Button)findViewById(R.id.button3);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
address_fragment address_fragment=(address_fragment)getSupportFragmentManager().findFragmentById(R.id.address_fragment);
address_fragment.setMapsActivity(this);
startedLocationUpdate = false;
permissionRequestCounter = 0;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
locationRequest = new LocationRequest();
locationRequest.setInterval(MINUTE);
locationRequest.setFastestInterval(15 * MILISECONDS_PER_SECOND);
locationRequest.setPriority(com.google.android.gms.location.LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
checkGps();
}
deviceUniqueNumber();
updateValuesFromBundle(savedInstanceState);
checkInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkInCurrentPosition();
checkInButton.setClickable(false);
checkOutButton.setClickable(true);
}
});
checkOutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePosition();
markerForDeletion.remove();
checkOutButton.setClickable(false);
checkInButton.setClickable(true);
}
});
checkOutButton.setClickable(false);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
if (mGoogleApiClient.isConnected() && !startedLocationUpdate)
startLocationUpdates();
}
#Override
public void onConnected(Bundle bundle) {
if (!startedLocationUpdate)
startLocationUpdates();
if (mCurrentLocation != null) {
if (!Geocoder.isPresent()) {
Toast.makeText(this, R.string.no_geocoder_available, Toast.LENGTH_SHORT).show();
return;
}
address_fragment gettingAddressFragment=(address_fragment)getSupportFragmentManager().findFragmentById(R.id.map);
if (gettingAddressFragment.mAddressRequested) {
gettingAddressFragment.startIntentService();
}
}
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
startedLocationUpdate = false;
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected() && startedLocationUpdate)
stopLocationUpdates();
}
private void startLocationUpdates() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, MapsActivity.this);
startedLocationUpdate = true;
} else {
if (permissionRequestCounter == 0) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
permissionRequestCounter++;
}
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMyLocationButtonClickListener(this);
enableMyLocation();
}
public void enableMyLocation() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
if (permissionRequestCounter == 0) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
permissionRequestCounter++;
}
} else if (mMap != null) {
// Access to the location has been granted to the app.
mMap.setMyLocationEnabled(true);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_FINE_LOCATION: {
if (grantResults.length == 1
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
enableMyLocation();
checkGps();
} else {
Toast.makeText(MapsActivity.this, "Permission was blocked", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public boolean onMyLocationButtonClick() {
checkGps();
return false;
}
public void checkGps() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
}
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
address_fragment.fetchAddressHandler();
}
private void setUpMap() {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonResponse = new JSONObject(s);
boolean success = jsonResponse.getBoolean("success");
if (success) {
JSONArray jsonArray = jsonResponse.getJSONArray("data");
JSONObject jsonObject;
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String mac = jsonObject.getString("mac");
String android_id = jsonObject.getString("android_id");
Double latitude = jsonObject.getDouble("latitude");
Double longitude = jsonObject.getDouble("longitude");
if (!isMarkerOnArray(markerCollection, latitude, longitude))
markerCollection.add(mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude))));
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(MapsActivity.this);
builder.setMessage("Downloading position failed")
.setNegativeButton("retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
DownloadPosition downloadPosition = new DownloadPosition(responseListener);
RequestQueue queue = Volley.newRequestQueue(MapsActivity.this);
queue.add(downloadPosition);
}
private boolean isMarkerOnArray(ArrayList<Marker> array, Double Latitude, Double Longitude) {
Marker current;
for (int c = 0; c < array.size(); c++) {
current = array.get(c);
if ((current.getPosition().latitude == Latitude) && (current.getPosition().longitude == Longitude))
return true;
}
return false;
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, startedLocationUpdate);
savedInstanceState.putParcelable(LOCATION_KEY, mCurrentLocation);
savedInstanceState.putBoolean(ADDRESS_REQUESTED_KEY, address_fragment.mAddressRequested);
savedInstanceState.putString(LOCATION_ADDRESS_KEY, address_fragment.mAddressOutput);
super.onSaveInstanceState(savedInstanceState);
}
private void updateValuesFromBundle(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY))
startedLocationUpdate = savedInstanceState.getBoolean(REQUESTING_LOCATION_UPDATES_KEY);
if (savedInstanceState.keySet().contains(LOCATION_KEY))
mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
if (savedInstanceState.keySet().contains(ADDRESS_REQUESTED_KEY)) {
address_fragment.mAddressRequested = savedInstanceState.getBoolean(ADDRESS_REQUESTED_KEY);
}
if (savedInstanceState.keySet().contains(LOCATION_ADDRESS_KEY)) {
address_fragment.mAddressOutput = savedInstanceState.getString(LOCATION_ADDRESS_KEY);
address_fragment.displayAddressOutput();
}
}
}
public void checkInCurrentPosition() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location locationGPS = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location locationNet = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location location;
long GPSLocationTime = 0;
if (null != locationGPS) { GPSLocationTime = locationGPS.getTime(); }
long NetLocationTime = 0;
if (null != locationNet) {
NetLocationTime = locationNet.getTime();
}
if ( 0 < GPSLocationTime - NetLocationTime ) {
location=locationGPS;
}
else {
location=locationNet;
}
LatLng newLatLng = new LatLng(location.getLatitude(), location.getLongitude());
markerForDeletion=mMap.addMarker(new MarkerOptions().position(newLatLng).title(newLatLng.toString()));
String deviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
Positions position=new Positions(newLatLng.latitude,newLatLng.longitude,getWifiMacAddress(),deviceId);
Response.Listener<String> responseListener= new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonResponse= new JSONObject(s);
boolean success=jsonResponse.getBoolean("success");
if(!success){
AlertDialog.Builder builder=new AlertDialog.Builder(MapsActivity.this);
builder.setMessage("uploading position failed")
.setNegativeButton("retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
UploadPosition upload=new UploadPosition(position,responseListener);
RequestQueue queue= Volley.newRequestQueue(MapsActivity.this);
queue.add(upload);
}
public void deletePosition(){
String deviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
String mac=getWifiMacAddress();
Response.Listener<String> responseListener = new Response.Listener<String>(){
#Override
public void onResponse(String s) {
try {
JSONObject jsonResponse= new JSONObject(s);
boolean success=jsonResponse.getBoolean("success");
if(!success){
AlertDialog.Builder builder=new AlertDialog.Builder(MapsActivity.this);
builder.setMessage("uploading position failed")
.setNegativeButton("retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
DeletePosition delete=new DeletePosition(mac,deviceId,responseListener);
RequestQueue queue=Volley.newRequestQueue(MapsActivity.this);
queue.add(delete);
}
public void deviceUniqueNumber(){
String deviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
Toast.makeText(this,deviceId+" "+getWifiMacAddress(),Toast.LENGTH_SHORT).show();
}
public static String getWifiMacAddress() {
try {
String interfaceName = "wlan0";
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
if (!intf.getName().equalsIgnoreCase(interfaceName)){
continue;
}
byte[] mac = intf.getHardwareAddress();
if (mac==null){
return "";
}
StringBuilder buf = new StringBuilder();
for (byte aMac : mac) {
buf.append(String.format("%02X:", aMac));
}
if (buf.length()>0) {
buf.deleteCharAt(buf.length() - 1);
}
return buf.toString();
}
} catch (Exception ex) {
Log.i("getWifiMacAddress","exception in getWifiMacAddress");
}
return "";
}
}
activity_maps.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal">
<fragment class="com.example.gio.autostop.address_fragment"
android:id="#+id/address_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/map"
tools:context="com.example.gio.autostop.MapsActivity"
class="com.google.android.gms.maps.SupportMapFragment"
>
<include layout="#layout/map_interface"/>
</fragment>
</LinearLayout>
address_fragment.java:
package com.example.gio.autostop;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
public class address_fragment extends Fragment {
protected TextView mLocationAddressTextView;
protected String mAddressOutput;
private AddressResultReceiver mResultReceiver;
private ProgressBar mProgressBar;
protected boolean mAddressRequested;
private MapsActivity mapsActivity;
public address_fragment() {
// Required empty public constructor
}
class AddressResultReceiver extends ResultReceiver{
private int CREATOR;
public AddressResultReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY);
mAddressRequested = false;
updateUIWidgets();
super.onReceiveResult(resultCode, resultData);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_address_fragment, container, false);
}
public void setMapsActivity(MapsActivity mapsActivity){
this.mapsActivity=mapsActivity;
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("mAddressOutput",mAddressOutput);
outState.putBoolean("mAddressRequested",mAddressRequested);
}
#Override
public void onStart() {
super.onStart();
View view = getView();
if(view!=null){
mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
mLocationAddressTextView=(TextView) view.findViewById(R.id.address);
displayAddressOutput();
}
}
public void displayAddressOutput(){
mLocationAddressTextView.setText(mAddressOutput);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mResultReceiver = new AddressResultReceiver(new Handler());
mAddressRequested = false;
mAddressOutput = " ";
updateUIWidgets();
}
public void startIntentService() {
Intent intent = new Intent(getContext(), FetchAddressIntentService.class);
intent.putExtra(Constants.RECEIVER, mResultReceiver);
intent.putExtra(Constants.LOCATION_DATA_EXTRA, mapsActivity.mCurrentLocation);
mapsActivity.startService(intent);
}
public void fetchAddressHandler() {
if (mapsActivity.mGoogleApiClient.isConnected() && mapsActivity.mCurrentLocation != null) {
startIntentService();
}
mAddressRequested = true;
updateUIWidgets();
}
private void updateUIWidgets() {
if (mAddressRequested) {
mProgressBar.setVisibility(ProgressBar.VISIBLE);
} else {
mProgressBar.setVisibility(ProgressBar.GONE);
}
}
}
fragment_address_fragment:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.gio.autostop.address_fragment"
android:background="#android:color/transparent">
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text=""
android:layout_centerHorizontal="true"
android:textSize="22sp"/>
</FrameLayout>
map_interface.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/check_in"
android:layout_marginTop="#dimen/layout_marginTop_button"
android:layout_gravity="end"
android:layout_alignParentBottom="true"
android:layout_weight="1"
/>
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/check_out"
android:layout_marginTop="#dimen/layout_marginTop_button"
android:layout_gravity="end"
android:layout_weight="1"
/>
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</LinearLayout>
what is causing error?
update:
full project: https://github.com/giusha/Autostop
Perhaps the "Error inflating fragment" message is misleading somewhat - but a closer examination of your error stacktrace shows that it is caused by NullPointerException (because you are calling mProgressBar.setVisibility) whereas mProgressBar is actually NULL - because you assigned it to view.findViewById(R.id.progress_bar); which returns null because the view R.id.progress_bar does not exist in the layout file (fragment_address_fragment). So my suggestion would be to move :
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
into the fragment_address_fragment layout file - and then run your code again and see if it works.
Related
This is my first time working with google maps in android.I was able to create a map showing my current user location.
However, I would like to display multiple markers whose data I'm fetching using volley. To do this I'm using a backgroundTask class with a singleton class. The backgroundTask class is the one returning the arrayList of the location data.
For this reason I need to populate my BackgroungTask class with the arrayList before my MapActivity become active and access the arraylist of objects in onCreate but it seems the MapActivity loads very fast and a reference to the arrayList of objects from the BackgroungTask class is always null.
This is the BackgroundTask class which is fetching the data
package com.example.carwashplaces;
import android.content.Context;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class BackgroundTask {
private Context context;
private ArrayList<ModelLocation> locationArrayList = new ArrayList<>();
String json_url = "http://histogenetic-exhaus.000webhostapp.com/location.php";
public BackgroundTask(Context context) {
this.context = context;
}
public ArrayList<ModelLocation> getLocationArrayList(){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest (
Request.Method.POST,
json_url,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count = 0;
while (count<response.length()){
try {
JSONObject jsonObject = response.getJSONObject(count);
ModelLocation modelLocation = new ModelLocation(
jsonObject.getString("id"),
jsonObject.getString("name"),
jsonObject.getString("latitude"),
jsonObject.getString("longitude"),
jsonObject.getString("staff"),
jsonObject.getString("comment"),
jsonObject.getString("phone"));
locationArrayList.add(modelLocation);
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Error fetching car wash places... ", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
MySingleton.getInstance(context).addToRequestque(jsonArrayRequest);
return locationArrayList;
}
}
This is the MapActivity where I want to display the locations.
package com.example.carwashplaces;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.AutocompletePrediction;
import com.google.android.libraries.places.api.model.AutocompleteSessionToken;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.TypeFilter;
import com.google.android.libraries.places.api.net.FetchPlaceRequest;
import com.google.android.libraries.places.api.net.FetchPlaceResponse;
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest;
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsResponse;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.mancj.materialsearchbar.MaterialSearchBar;
import com.mancj.materialsearchbar.adapter.SuggestionsAdapter;
import com.skyfishjy.library.RippleBackground;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private PlacesClient placesClient;
private List<AutocompletePrediction> predictionList;
private ArrayList<ModelLocation> locations;
private BackgroundTask backgroundTask;
private Location mLastKnownLocation;
private LocationCallback locationCallback;
private MaterialSearchBar materialSearchBar;
private View mapView;
private Button btnFind;
private RippleBackground rippleBg;
private final float DEFAULT_ZOOM = 18;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
//init views
materialSearchBar = findViewById(R.id.searchBar);
btnFind = findViewById(R.id.btnFind);
rippleBg = findViewById(R.id.ripple_bg);
//an object of backgroung task
backgroundTask = new BackgroundTask(MapActivity.this);
locations = new ArrayList<>();
//getting location data from background task
locations = backgroundTask.getLocationArrayList();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mapView = mapFragment.getView();
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MapActivity.this);
Places.initialize(MapActivity.this, "MY_KEY");
placesClient = Places.createClient(this);
final AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString(), true, null, true);
}
#Override
public void onButtonClicked(int buttonCode) {
if (buttonCode == MaterialSearchBar.BUTTON_NAVIGATION){
//opening or closing a navigation drawer
}else if (buttonCode == MaterialSearchBar.BUTTON_BACK){
materialSearchBar.disableSearch();
}
}
});
materialSearchBar.addTextChangeListener(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) {
FindAutocompletePredictionsRequest predictionsRequest = FindAutocompletePredictionsRequest.builder()
.setCountry("ke")
.setTypeFilter(TypeFilter.ADDRESS)
.setSessionToken(token)
.setQuery(s.toString())
.build();
placesClient.findAutocompletePredictions(predictionsRequest).addOnCompleteListener(new OnCompleteListener<FindAutocompletePredictionsResponse>() {
#Override
public void onComplete(#NonNull Task<FindAutocompletePredictionsResponse> task) {
if (task.isSuccessful()){
//predictions found, find out what suggestions we have from google
FindAutocompletePredictionsResponse predictionsResponse = task.getResult();
if (predictionsResponse != null){
predictionList = predictionsResponse.getAutocompletePredictions();
//converting predictionList into a list of string
List<String> suggestionsList = new ArrayList<>();
for (int i = 0; i < predictionList.size(); i++){
AutocompletePrediction prediction = predictionList.get(i);
suggestionsList.add(prediction.getFullText(null).toString());
}
//pass suggestion list to our MaterialSearchBar
materialSearchBar.updateLastSuggestions(suggestionsList);
if (!materialSearchBar.isSuggestionsVisible()){
materialSearchBar.showSuggestionsList();
}
}
}
else {
//some error
Log.i("mytag", "prediction fetching task failed");
}
}
});
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setSuggstionsClickListener(new SuggestionsAdapter.OnItemViewClickListener() {
#Override
public void OnItemClickListener(int position, View v) {
// seek the longitude and latitude of that suggestion
if (position >= predictionList.size()){
return;
}
AutocompletePrediction selectedPrediction = predictionList.get(position);
String suggestion = materialSearchBar.getLastSuggestions().get(position).toString();
materialSearchBar.setText(suggestion);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
materialSearchBar.clearSuggestions();
}
},1000);
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
if (imm != null){
imm.hideSoftInputFromWindow(materialSearchBar.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
}
String placeId = selectedPrediction.getPlaceId();
List<Place.Field> placeFields = Arrays.asList(Place.Field.LAT_LNG);// get latitude and longitude of a place
FetchPlaceRequest fetchPlaceRequest = FetchPlaceRequest.builder(placeId, placeFields).build();
placesClient.fetchPlace(fetchPlaceRequest).addOnSuccessListener(new OnSuccessListener<FetchPlaceResponse>() {
#Override
public void onSuccess(FetchPlaceResponse fetchPlaceResponse) {
// place found, update camera Factory
Place place = fetchPlaceResponse.getPlace();
Log.i("mytag", "place found: "+place.getName());
LatLng latLngOfPlace = place.getLatLng();
if (latLngOfPlace != null){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngOfPlace, DEFAULT_ZOOM));
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ApiException){
ApiException apiException = (ApiException) e;
apiException.printStackTrace();
int statusCode = apiException.getStatusCode();
Log.i("mytag", "place not found: " +e.getMessage());
Log.i("mytag", "status code: "+statusCode);
}
}
});
}
#Override
public void OnItemDeleteListener(int position, View v) {
}
});
btnFind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get the current location of the marker
LatLng currentMarkerLocation = mMap.getCameraPosition().target;
rippleBg.startRippleAnimation();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
rippleBg.stopRippleAnimation();
Toast.makeText(MapActivity.this, "Nearest Car Wash", Toast.LENGTH_SHORT).show();
}
},3000);
}
});
}
//Called when the map is loaded
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
if (mapView != null && mapView.findViewById(Integer.parseInt("1")) != null){
View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 40, 180);
}
//check if gps is enabled or not and then request user to enable it
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
SettingsClient settingsClient = LocationServices.getSettingsClient(MapActivity.this);
Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build());
task.addOnSuccessListener(MapActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
getDeviceLocation();
setMarkersToCarWashes();
}
});
task.addOnFailureListener(MapActivity.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ResolvableApiException){
ResolvableApiException resolvable = (ResolvableApiException) e;
try {
resolvable.startResolutionForResult(MapActivity.this, 51);
} catch (IntentSender.SendIntentException ex) {
ex.printStackTrace();
}
}
}
});
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
if (materialSearchBar.isSuggestionsVisible())
materialSearchBar.clearSuggestions();
if (materialSearchBar.isSearchEnabled())
materialSearchBar.disableSearch();
return false;
}
});
setMarkersToCarWashes();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 51) {
if (resultCode == RESULT_OK) {
getDeviceLocation();
setMarkersToCarWashes();
}
}
}
private void setMarkersToCarWashes() {
if (locations != null){
for(int i = 0; i < locations.size(); i++){
double lati = Double.parseDouble(locations.get(i).getLatitude());
double longLat = Double.parseDouble(locations.get(i).getLongitude());
//set markers to car wash places
mMap.addMarker(new MarkerOptions().position(
new LatLng(lati, longLat))
.title(locations.get(i).getName())
.snippet(locations.get(i).getComment()));
}
}
}
private void getDeviceLocation() {
mFusedLocationProviderClient.getLastLocation()
.addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful()){
mLastKnownLocation = task.getResult();
if (mLastKnownLocation != null){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
}else {
final LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationCallback = new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult == null){
return;
}
mLastKnownLocation = locationResult.getLastLocation();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
mFusedLocationProviderClient.removeLocationUpdates(locationCallback);
}
};
mFusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
}else {
Toast.makeText(MapActivity.this, "Unable to get last Location", Toast.LENGTH_SHORT).show();
}
}
});
}
}
And This is the part of the code in MapActivity where I'm trying to get the arraylist from the BackgroundTask class
//an object of backgroung task
backgroundTask = new BackgroundTask(MapActivity.this);
locations = new ArrayList<>();
//getting location data from background task
locations = backgroundTask.getLocationArrayList();
How do I display the markers in onMapReady method i.e populate the BackgroundTask before the onMapReady method executes?
This is my approach, based off of this solution from related thread. First let's create an interface to handle the volley's response.
public interface LocationsCallback {
void onSuccess(ArrayList<ModelLocation> fetchedLocations);
}
Then modify your getLocationArrayList method as follows:
public ArrayList<ModelLocation> getLocationArrayList(final LocationsCallback locationsCallback)
Inside the onResponse method of getLocationArrayList, right at the end, add the callback:
public ArrayList<ModelLocation> getLocationArrayList(final LocationsCallback locationsCallback) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.POST,
json_url,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// your code here...
// Add this at the end here
ArrayList<ModelLocation> locations = locationArrayList;
locationsCallback.onSuccess(locations);
}
//...
Now assign your MapActivity's locations to the fetched array:
locations = new ArrayList<>();
backgroundTask = new BackgroundTask(MapActivity.this);
backgroundTask.getLocationArrayList(new LocationsCallback() {
#Override
public void onSuccess(ArrayList<ModelLocation> fetchedLocations) {
locations = fetchedLocations;
// Your other code goes here...
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapActivity.this);
mapView = mapFragment.getView();
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MapActivity.this);
Places.initialize(MapActivity.this, "KEY");
placesClient = Places.createClient(MapActivity.this);
//...
}
});
And the markers will now be displayed on the map. See screenshot below. :)
I am getting error at:
com.projects.fragments.MapFragment.onMapReady(MapFragment.java:200) at
com.projects.fragments.MapFragment.onMapReady(MapFragment.java:200)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown
Source)
at com.google.android.gms.maps.internal.zzo$zza.onTransact(Unknown
Source)
Occurs in run time this the Mapfragment class
package com.projects.fragments;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.application.RealEstateApplication;
import com.config.Config;
import com.config.UIConfig;
import com.db.Queries;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.libraries.asynctask.MGAsyncTask;
import com.libraries.asynctask.MGAsyncTaskNoDialog;
import com.libraries.dataparser.DataParser;
import com.libraries.drawingview.DrawingView;
import com.libraries.location.MGLocationManagerUtils;
import com.libraries.sliding.MGSliding;
import com.libraries.usersession.UserAccessSession;
import com.libraries.utilities.MGUtilities;
import com.models.DataResponse;
import com.models.Favorite;
import com.models.Photo;
import com.models.PropertyType;
import com.models.RealEstate;
import com.projects.activities.DetailActivity;
import com.projects.realestatefinder.R;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
/**
* Created by mg on 27/07/16.
*/
public class MapFragment extends Fragment implements OnMapReadyCallback,
RealEstateApplication.OnLocationListener,
GoogleMap.OnInfoWindowClickListener, GoogleMap.OnMapClickListener,
DrawingView.OnDrawingViewListener {
private View viewInflate;
private GoogleMap googleMap;
private MGSliding frameSliding;
SwipeRefreshLayout swipeRefresh;
MGAsyncTaskNoDialog task;
ArrayList<RealEstate> realEstates;
private HashMap<String, RealEstate> markers;
private ArrayList<Marker> markerList;
private RealEstate selectedRealEstate;
private DrawingView drawingView;
private Unbinder unbinder;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
viewInflate = inflater.inflate(R.layout.fragment_map, null);
unbinder = ButterKnife.bind(this, viewInflate);
return viewInflate;
}
#Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
if(task != null)
task.cancel(true);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
realEstates = new ArrayList<RealEstate>();
swipeRefresh = (SwipeRefreshLayout) viewInflate.findViewById(R.id.swipe_refresh);
swipeRefresh.setClickable(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
swipeRefresh.setProgressViewOffset(false, 0,100);
}
swipeRefresh.setColorSchemeResources(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
showRefresh(false);
FragmentManager fManager = getActivity().getSupportFragmentManager();
SupportMapFragment supportMapFragment = ((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
if(supportMapFragment == null) {
fManager = getChildFragmentManager();
supportMapFragment = ((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
}
supportMapFragment.getMapAsync(this);
frameSliding = (MGSliding) viewInflate.findViewById(R.id.frameSliding);
Animation animationIn = AnimationUtils.loadAnimation(this.getActivity(), R.anim.slide_up2);
Animation animationOut = AnimationUtils.loadAnimation(this.getActivity(), R.anim.slide_down2);
frameSliding.setInAnimation(animationIn);
frameSliding.setOutAnimation(animationOut);
frameSliding.setVisibility(View.GONE);
markers = new HashMap<String, RealEstate>();
markerList = new ArrayList<Marker>();
}
#Override
public void onMapReady(GoogleMap _googleMap) {
googleMap = _googleMap;
googleMap.setOnInfoWindowClickListener(this);
googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
if(frameSliding.getVisibility() == View.VISIBLE)
frameSliding.setVisibility(View.INVISIBLE);
}
});
drawingView = (DrawingView) viewInflate.findViewById(R.id.drawingView);
drawingView.setBrushSize(5);
drawingView.setPolygonFillColor(getResources().getColor(R.color.colorPrimaryAlpha));
drawingView.setColor(getResources().getColor(R.color.colorAccent));
drawingView.setPolylineColor(getResources().getColor(R.color.colorAccent));
drawingView.setGoogleMap(googleMap);
drawingView.setOnDrawingViewListener(this);
if(!MGUtilities.isLocationEnabled(getActivity()) && RealEstateApplication.currentLocation == null) {
MGLocationManagerUtils utils = new MGLocationManagerUtils();
utils.setOnAlertListener(new MGLocationManagerUtils.OnAlertListener() {
#Override
public void onPositiveTapped() {
startActivityForResult(
new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS),
Config.PERMISSION_REQUEST_LOCATION_SETTINGS);
}
#Override
public void onNegativeTapped() {
showRefresh(false);
}
});
utils.showAlertView(
getActivity(),
R.string.location_error,
R.string.gps_not_on,
R.string.go_to_settings,
R.string.cancel);
}
else {
showRefresh(true);
if(RealEstateApplication.currentLocation != null) {
getData();
}
else {
refetch();
}
}
}
public void refetch() {
showRefresh(true);
RealEstateApplication app = (RealEstateApplication) getActivity().getApplication();
app.setOnLocationListener(this, getActivity());
}
private void getData() {
showRefresh(true);
task = new MGAsyncTaskNoDialog(getActivity());
task.setMGAsyncTaskListener(new MGAsyncTaskNoDialog.OnMGAsyncTaskListenerNoDialog() {
#Override
public void onAsyncTaskProgressUpdate(MGAsyncTaskNoDialog asyncTask) { }
#Override
public void onAsyncTaskPreExecute(MGAsyncTaskNoDialog asyncTask) {
}
#Override
public void onAsyncTaskPostExecute(MGAsyncTaskNoDialog asyncTask) {
// TODO Auto-generated method stub
showRefresh(false);
addMarkers(realEstates);
// showBoundedMap();
}
#Override
public void onAsyncTaskDoInBackground(MGAsyncTaskNoDialog asyncTask) {
// TODO Auto-generated method stub
if(RealEstateApplication.currentLocation != null && MGUtilities.hasConnection(getContext())) {
try {
UserAccessSession accessSession = UserAccessSession.getInstance(getActivity());
float radius = accessSession.getFilterDistance();
if(radius == 0)
radius = Config.DEFAULT_FILTER_DISTANCE_IN_KM;
String strUrl = String.format("%s?api_key=%s&lat=%f&lon=%f&radius=%f&get_propertytypes=1&default_count_to_find_distance=%d",
Config.GET_DATA_JSON_URL,
Config.API_KEY,
RealEstateApplication.currentLocation.getLatitude(),
RealEstateApplication.currentLocation.getLongitude(),
radius,
Config.DEFAULT_COUNT_TO_FIND);
Log.e("URL", strUrl);
DataParser parser = new DataParser();
DataResponse data = parser.getData(strUrl);
if (data == null)
return;
if(data.getMax_distance() > 0) {
UserAccessSession.getInstance(getActivity()).setFilterDistanceMax(data.getMax_distance());
}
if(Config.AUTO_ADJUST_DISTANCE) {
if(UserAccessSession.getInstance(getActivity()).getFilterDistance() == 0) {
UserAccessSession.getInstance(getActivity()).setFilterDistance(data.getDefault_distance());
}
}
Queries q = RealEstateApplication.getQueriesInstance(getContext());
if (data.getProperty_types() != null && data.getProperty_types().size() > 0) {
for (PropertyType obj : data.getProperty_types()) {
q.deletePropertyType(obj.getPropertytype_id());
q.insertPropertyType(obj);
}
}
if (data.getReal_estates() != null && data.getReal_estates().size() > 0) {
for (RealEstate obj : data.getReal_estates()) {
double distance = obj.getDistance() * Config.CONVERSION_SERVER_DATA_DISTANCE_TO_KM;
obj.setDistance(distance);
q.deleteRealEstate(obj.getRealestate_id());
q.insertRealEstate(obj);
if (obj.getPhotos() != null && obj.getPhotos().size() > 0) {
for (Photo photo : obj.getPhotos()) {
q.deletePhoto(photo.getPhoto_id());
q.insertPhoto(photo);
}
}
if(obj.getAgent() != null) {
q.deleteAgent(obj.getAgent().getAgent_id());
q.insertAgent(obj.getAgent());
}
realEstates.add(obj);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
else {
realEstates = RealEstateApplication.getQueriesInstance(getContext()).getRealEstates();
if(RealEstateApplication.currentLocation != null) {
for(RealEstate realEstate : realEstates) {
Location locStore = new Location("Store");
locStore.setLatitude(realEstate.getLat());
locStore.setLongitude(realEstate.getLon());
double userDistanceFromStore =
RealEstateApplication.currentLocation.distanceTo(locStore) *
Config.CONVERSION_OFFLINE_DATA_DISTANCE_TO_KM;
realEstate.setDistance(userDistanceFromStore);
}
Collections.sort(realEstates, new Comparator<RealEstate>() {
#Override
public int compare(RealEstate obj1, RealEstate obj2) {
if (obj1.getDistance() < obj2.getDistance())
return -1;
if (obj1.getDistance() > obj2.getDistance())
return 1;
return 0;
}
});
}
}
}
});
task.execute();
}
private void addMarkers(ArrayList<RealEstate> arrayList) {
if(googleMap != null)
googleMap.clear();
try {
markerList.clear();
markers.clear();
for(RealEstate entry: arrayList) {
if(entry.getLat() == 0 || entry.getLon() == 0)
continue;
Marker mark = createMarker(entry);
markerList.add(mark);
markers.put(mark.getId(), entry);
}
showBoundedMap();
}
catch(Exception e) {
e.printStackTrace();
}
}
private Marker createMarker(RealEstate realEstate) {
final MarkerOptions markerOptions = new MarkerOptions();
String strPrice = String.format("%s %s", realEstate.getCurrency(), realEstate.getPrice());
Spanned price = Html.fromHtml(strPrice);
price = Html.fromHtml(price.toString());
Spanned storeAddress = Html.fromHtml(realEstate.getAddress());
storeAddress = Html.fromHtml(storeAddress.toString());
markerOptions.title( price.toString() );
String address = storeAddress.toString();
if(address.length() > Config.ELLIPSE_HOME_COUNT)
address = storeAddress.toString().substring(0, Config.ELLIPSE_HOME_COUNT) + "...";
markerOptions.snippet(address);
markerOptions.position(new LatLng(realEstate.getLat(), realEstate.getLon()));
markerOptions.icon(BitmapDescriptorFactory.fromResource(UIConfig.MAP_PIN_REAL_ESTATE));
Marker mark = googleMap.addMarker(markerOptions);
mark.setInfoWindowAnchor(Config.MAP_INFO_WINDOW_X_OFFSET, 0);
return mark;
}
private void showBoundedMap() {
if(markerList == null && markerList.size() == 0 ) {
Toast.makeText(getContext(), R.string.no_results_found, Toast.LENGTH_SHORT).show();
return;
}
if(markerList.size() > 0) {
LatLngBounds.Builder bld = new LatLngBounds.Builder();
for (int i = 0; i < markerList.size(); i++) {
Marker marker = markerList.get(i);
bld.include(marker.getPosition());
}
LatLngBounds bounds = bld.build();
googleMap.moveCamera(
CameraUpdateFactory.newLatLngBounds(bounds,
this.getResources().getDisplayMetrics().widthPixels,
this.getResources().getDisplayMetrics().heightPixels,
70));
}
else {
Toast.makeText(getContext(), R.string.no_results_found, Toast.LENGTH_SHORT).show();
Location loc = RealEstateApplication.currentLocation;
if(loc != null) {
googleMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(
new LatLng(loc.getLatitude(), loc.getLongitude()),
70) );
}
}
}
#Override
public void onInfoWindowClick(Marker marker) {
// TODO Auto-generated method stub
final RealEstate obj = markers.get(marker.getId());
selectedRealEstate = obj;
if(RealEstateApplication.currentLocation != null) {
Location loc = new Location("marker");
loc.setLatitude(marker.getPosition().latitude);
loc.setLongitude(marker.getPosition().longitude);
double meters = RealEstateApplication.currentLocation.distanceTo(loc);
double miles = meters * Config.METERS_TO_KM;
String str = String.format("%.1f %s",
miles,
MGUtilities.getStringFromResource(getActivity(), R.string.km));
TextView tvDistance = (TextView) viewInflate.findViewById(R.id.tvDistance);
tvDistance.setText(str);
}
frameSliding.setVisibility(View.VISIBLE);
Queries q = RealEstateApplication.getQueriesInstance(getContext());
ImageView imgViewThumb = (ImageView) viewInflate.findViewById(R.id.imgViewThumb);
Photo p = q.getPhotoByRealEstateId(obj.getRealestate_id());
if(p != null) {
RealEstateApplication.getImageLoaderInstance(
getActivity()).displayImage(p.getPhoto_url(),
imgViewThumb,
RealEstateApplication.getDisplayImageOptionsInstance());
}
else {
imgViewThumb.setImageResource(UIConfig.IMAGE_PLACEHOLDER);
}
imgViewThumb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), DetailActivity.class);
i.putExtra("realestate", obj);
getActivity().startActivity(i);
}
});
String strPrice = String.format("%s %s", obj.getCurrency(), obj.getPrice());
Spanned spannedPrice = Html.fromHtml(strPrice);
spannedPrice = Html.fromHtml(spannedPrice.toString());
Spanned spannedAddress = Html.fromHtml(obj.getAddress());
spannedAddress = Html.fromHtml(spannedAddress.toString());
String address = spannedAddress.toString();
if(address.length() > Config.ELLIPSE_HOME_COUNT)
address = spannedAddress.toString().substring(0, Config.ELLIPSE_HOME_COUNT) + "...";
TextView tvTitle = (TextView) viewInflate.findViewById(R.id.tvTitle);
TextView tvSubtitle = (TextView) viewInflate.findViewById(R.id.tvSubtitle);
tvTitle.setText(spannedPrice);
tvSubtitle.setText(address);
ToggleButton toggleButtonFave = (ToggleButton) viewInflate.findViewById(R.id.toggleButtonFave);
toggleButtonFave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
checkFave(v, obj);
}
});
Favorite fave = q.getFavoriteByRealEstateId(obj.getRealestate_id());
toggleButtonFave.setChecked(true);
if(fave == null)
toggleButtonFave.setChecked(false);
}
#Override
public void onMapClick(LatLng point) {
// TODO Auto-generated method stub
frameSliding.setVisibility(View.INVISIBLE);
}
private void checkFave(View view, RealEstate realEstate) {
Queries q = RealEstateApplication.getQueriesInstance(getContext());
Favorite fave = q.getFavoriteByRealEstateId(realEstate.getRealestate_id());
if(fave != null) {
q.deleteFavorite(realEstate.getRealestate_id());
((ToggleButton) view).setChecked(false);
}
else {
fave = new Favorite();
fave.setRealestate_id(realEstate.getRealestate_id());
q.insertFavorite(fave);
((ToggleButton) view).setChecked(true);
}
}
public void showRefresh(boolean show) {
swipeRefresh.setRefreshing(show);
swipeRefresh.setEnabled(show);
}
ArrayList<Marker> markers1;
#SuppressLint("DefaultLocale")
#Override
public void onUserDidFinishDrawPolygon(PolygonOptions polygonOptions) {
// TODO Auto-generated method stub
googleMap.clear();
googleMap.addPolygon( polygonOptions );
markers1 = getMarkersInsidePoly(polygonOptions, null, markerList);
markerList.clear();
markers.clear();
for(Marker mark1 : markers1) {
for(RealEstate realEstate : realEstates) {
String strPrice = String.format("%s %s", realEstate.getCurrency(), realEstate.getPrice());
if(mark1.getPosition().latitude == realEstate.getLat() &&
mark1.getPosition().longitude == realEstate.getLon() &&
mark1.getTitle().compareTo(strPrice) == 0) {
Marker mark = createMarker(realEstate);
markerList.add(mark);
markers.put(mark.getId(), realEstate);
break;
}
}
}
drawingView.enableDrawing(false);
drawingView.resetPolygon();
drawingView.startNew();
if(markers1.size() == 0)
Toast.makeText(getContext(), R.string.no_results_found, Toast.LENGTH_SHORT).show();
}
#Override
public void onUserDidFinishDrawPolyline(PolylineOptions polylineOptions) { }
public ArrayList<Marker> getMarkersInsidePoly(PolygonOptions polygonOptions,
PolylineOptions polylineOptions, ArrayList<Marker> markers) {
ArrayList<Marker> markersFound = new ArrayList<Marker>();
for(Marker mark : markers) {
Boolean isFound = polygonOptions != null ?
drawingView.latLongContainsInPolygon(mark.getPosition(), polygonOptions) :
drawingView.latLongContainsInPolyline(mark.getPosition(), polylineOptions);
if(isFound) {
markersFound.add(mark);
}
}
return markersFound;
}
#OnClick(R.id.btnDraw)
public void drawMap() {
drawingView.enableDrawing(true);
drawingView.startDrawingPolygon(true);
}
#OnClick(R.id.btnRefresh)
public void refresh() {
showRefresh(true);
addMarkers(realEstates);
showRefresh(false);
}
#OnClick(R.id.btnRoute)
public void route() {
if(selectedRealEstate == null) {
MGUtilities.showAlertView(
getActivity(),
R.string.action_error,
R.string.cannot_proceed_route);
return;
}
String geo = String.format("http://maps.google.com/maps?f=d&daddr=%s&dirflg=d", selectedRealEstate.getAddress()) ;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(geo));
intent.setComponent(new ComponentName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity"));
startActivity(intent);
}
#OnClick(R.id.btnCurrentLocation)
public void currentLocation() {
Location loc = RealEstateApplication.currentLocation;
if(loc != null) {
googleMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(
new LatLng(loc.getLatitude(), loc.getLongitude()),
70) );
}
}
#Override
public void onLocationChanged(Location prevLoc, Location currentLoc) {
RealEstateApplication app = (RealEstateApplication) getActivity().getApplication();
app.setOnLocationListener(null, getActivity());
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
getData();
}
}, Config.DELAY_SHOW_ANIMATION + 500);
googleMap.setMyLocationEnabled(true);
}
#Override
public void onLocationRequestDenied() {
showRefresh(false);
MGUtilities.showAlertView(getActivity(), R.string.permission_error, R.string.permission_error_details_location);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Config.PERMISSION_REQUEST_LOCATION_SETTINGS) {
if(MGUtilities.isLocationEnabled(getActivity()))
refetch();
else {
showRefresh(false);
Toast.makeText(getActivity(),
R.string.location_error_not_turned_on, Toast.LENGTH_LONG).show();
}
}
}
}
This is getting my current location and displaying the details of that location but what I'm wanting to do is be able to have a google map display as well with my current location, I need to do this in a fragment.
The Source Is Code Below
package location.com.prjlocationdemo;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
public class GetMyAddress extends AppCompatActivity
{
TextView AddressText;
Geocoder objCoder;
String provider;
Criteria objCriteria;
LocationManager objLocationManager;
Location objLocation;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_my_address);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
AddressText = (TextView) findViewById(R.id.tvMyAddress);
objCriteria = new Criteria();
objLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
objCriteria.setAccuracy(Criteria.NO_REQUIREMENT);
objCriteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
// provider = objLocationManager.getBestProvider(objCriteria,true);
provider = objLocationManager.NETWORK_PROVIDER;
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;
}
objLocationManager.requestLocationUpdates(provider, 1000, 0, new LocationListener()
{
#Override
public void onLocationChanged(Location location)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText(GetMyAddress.this, "Location On", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText(GetMyAddress.this, "Location Off", Toast.LENGTH_SHORT).show();
}
});
}
//*********************************************************************************************************
public void btnClick(View v)
{
RetrieveLocation objAddress = new RetrieveLocation();
objAddress.execute(objLocation);
}
//*********************************************************************************************************
public class RetrieveLocation extends AsyncTask<Location, Void, String>
{
#Override
protected void onPreExecute()
{
Toast.makeText(getApplication(), "Finding Your Location....", Toast.LENGTH_SHORT).show();
}
//***************************************************************************
#Override
protected String doInBackground(Location... params)
{
String myAddress = null;
if (Geocoder.isPresent())
{
objCoder = new Geocoder(getApplicationContext());
if (ActivityCompat.checkSelfPermission(GetMyAddress.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(GetMyAddress.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 "";
}
params[0] = objLocationManager.getLastKnownLocation(provider);
if (params[0] != null)
{
List<Address> objAddressList = null;
try
{
objAddressList = objCoder.getFromLocation(params[0].getLatitude(), params[0].getLongitude(), 1);
if (objAddressList != null)
{
for (Address addressLoc : objAddressList)
{
String city = addressLoc.getLocality();
String country = addressLoc.getCountryName();
String place = addressLoc.getFeatureName();
String road = addressLoc.getSubThoroughfare();
String postal = addressLoc.getPostalCode();
myAddress = "Address\n City : " + city +
"\nCountry : " + country +
"\nName Of Place : " + place +
"\nRoad : " + road +
"\nPostal Code : " + postal + "\n";
int addressIndex = addressLoc.getMaxAddressLineIndex();
for (int count = 0; count <= addressIndex; count++)
{
String line = addressLoc.getAddressLine(count);
myAddress += line + "\n";
}
}
}
else
{
return "No Location Found";
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
return "Nothing Found";
}
}
return myAddress;
}
//****************************************************************************************
#Override
protected void onPostExecute(String s)
{
AddressText.setText(s);
Log.d("Prov",provider);
}
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="location.com.prjlocationdemo.GetMyAddress"
tools:showIn="#layout/activity_get_my_address">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="My Address"
android:id="#+id/tvMyAddress"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="86dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get My Address"
android:id="#+id/btnAddress"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="125dp"
android:onClick="btnClick"/>
</RelativeLayout>
I'm trying to add this to it
but the get map = mapView.getMap(); map.setMyLocationEnabled(true); catch (GooglePlayServicesNotAvailableException e) {e.printStackTrace();} are giving me errors.
public class FragmentTwo extends Fragment
{
MapView mapView;
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_fragment_two, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
// Updates the location and zoom of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);
return v;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
<LinearLayout
android:orientation="vertical"
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="280dp"
android:id="#+id/mapLay"
android:background="#color/blue25">
<fragment xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
tools:context="com.example.k.guides4art20.MapsActivity"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
You can use this part of layout
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.
I'm working on a location based tracking app. Does anyone know how to use only gps location and not network provider location. Since i'm using acess_fine_location in my manifest it uses both.
This is my tracking code:
package com.persasrl.paul.quickfit;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
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 com.google.android.gms.common.SupportErrorDialogFragment;
import java.text.DateFormat;
import java.util.Date;
public class StepCounter extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
// Request code to use when launching the resolution activity
private static final int REQUEST_RESOLVE_ERROR = 1001;
// Unique tag for the error dialog fragment
private static final String DIALOG_ERROR = "dialog_error";
// Bool to track whether the app is already resolving an error
private boolean mResolvingError = false;
//keys
GoogleApiClient mGoogleApiClient;
TextView mDistanceText;
TextView mTimeText;
Location mLastLocation;
Location mCurrentLocation;
UserLocalStore userLocalStore;
float[] d = new float[1];
float totald=0;
int type;
private MCountDownTimer countDownTimer;
private long timeElapsed;
private final long startTime = 9223372036854775807L;
private final long interval = 1;
LocationRequest mLocationRequest;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step_counter);
userLocalStore = new UserLocalStore(this);
mDistanceText = (TextView) findViewById(R.id.dist);
mTimeText = (TextView) findViewById(R.id.time);
mResolvingError = savedInstanceState != null
&& savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false);
Intent startIntent = getIntent();
Bundle bundle = startIntent.getExtras();
if(bundle!=null)
type= bundle.getInt("sport");
isGpsConnected();
createLocationRequest();
buildGoogleApiClient();
}
public void isGpsConnected()
{
// Get Location Manager and check for GPS & Network location services
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
// Build the alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Location Services Not Active");
builder.setMessage("Please enable Location Services and GPS");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
// Show location settings when the user acknowledges the alert dialog
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
Dialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
if(!mResolvingError)
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
public void stopApp(View view)
{
User user = userLocalStore.getLoggedInUser();
Workout workout = new Workout (totald,type,user.username,timeElapsed);
registerWorkout(workout);
}
private void registerWorkout(Workout workout) {
ServerRequests serverRequest = new ServerRequests(this);
serverRequest.storeWorkoutDataInBackground(workout, new GetWorkoutCallback() {
#Override
public void done(Workout returnedWorkout) {
Intent Intent = new Intent(StepCounter.this, MainActivity.class);
startActivity(Intent);
}
});
}
public void onConnected(Bundle connectionHint) {
countDownTimer = new MCountDownTimer(startTime, interval);
countDownTimer.start();
startLocationUpdates();
}
//pana aici merge de aici vine partea cu update
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(500);
mLocationRequest.setFastestInterval(500);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onLocationChanged(Location location) {
if(mCurrentLocation!=null)
mLastLocation = mCurrentLocation;
mCurrentLocation = location;
if(mLastLocation!=null && mCurrentLocation!=null)
updateDistance();
}
public void updateDistance()
{
Location.distanceBetween(mLastLocation.getLatitude(), mLastLocation.getLongitude(), mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude(), d);
if(!(d[0]<0.001))
totald+=d[0];
mDistanceText.setText(String.valueOf(String.format("%.3f", totald)));
}
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
// De aici partea cu rezolvatu problemei
#Override
public void onConnectionSuspended(int i) {
//todo nust...
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
// Show dialog using GoogleApiAvailability.getErrorDialog()
showErrorDialog(result.getErrorCode());
mResolvingError = true;
}
}
// The rest of this code is all about building the error dialog
/* Creates a dialog for an error message */
private void showErrorDialog(int errorCode) {
// Create a fragment for the error dialog
ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
// Pass the error that should be displayed
Bundle args = new Bundle();
args.putInt(DIALOG_ERROR, errorCode);
dialogFragment.setArguments(args);
dialogFragment.show(getFragmentManager(), "errordialog");
}
/* Called from ErrorDialogFragment when the dialog is dismissed. */
public void onDialogDismissed() {
mResolvingError = false;
}
/* A fragment to display an error dialog */
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() { }
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the error code and retrieve the appropriate dialog
int errorCode = this.getArguments().getInt(DIALOG_ERROR);
return GoogleApiAvailability.getInstance().getErrorDialog(
this.getActivity(), errorCode, REQUEST_RESOLVE_ERROR);
}
#Override
public void onDismiss(DialogInterface dialog) {
((StepCounter) getActivity()).onDialogDismissed();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false;
if (resultCode == RESULT_OK) {
// Make sure the app is not already connected or attempting to connect
if (!mGoogleApiClient.isConnecting() &&
!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
}
}
private static final String STATE_RESOLVING_ERROR = "resolving_error";
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError);
}
//timer
public class MCountDownTimer extends CountDownTimer
{
public MCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
#Override
public void onFinish()
{
mTimeText.setText("Time Elapsed: " + String.valueOf(startTime));
}
#Override
public void onTick(long millisUntilFinished)
{
long hours=0;
long minutes=0;
long seconds=0;
timeElapsed = (startTime - millisUntilFinished)/1000;
seconds= timeElapsed%60;
minutes= timeElapsed/60%60;
hours = timeElapsed/3600;
mTimeText.setText(String.valueOf(hours) + ":" + String.valueOf(minutes)+ ":" + String.valueOf(seconds));
}
}
}
And my manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
//android:theme="#android:style/Theme.Holo"
<activity
android:name=".LoginScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
</activity>
<activity
android:name=".StepCounter"
android:label="#string/title_activity_step_counter" >
</activity>
</application>