I am now working on a online rent car finder apk. I want this program TO fetch database from server and sort it based on the location (distance from user current location of rent car garage).
But i am confuse here on how to sort the list view base on the distance ? I mean, i know how to calculate the distance but i am blank about how to get the user's current latitude and longitude inside an Activity without opening mapActivity?
This my condition right now :
1. My result list is inside ResultListFragment.java and my google map activity is on MapActivity.java.
2. I have to try and get the longitude,latitude using getLatitude and getLongitude method which i create on MapActivity.java, but it just returning zero (not null).
3. I tried to separate the gps listener on GPStracker class, but still it doesn't work.
Please help me, how do i get the latitude and longitude of the current user position.
NB. This is my ResultListFragment.java
public class ResultListFragment extends Fragment implements InternetConnectionListener,
LocationChangeListener {
public static String catId;
public static String titleId;
public static String searchTerm;
public static LocationChangeListener locationChangeListener;
private final int RESULT_ACTION = 1;
private final int RESULT_LIMIT = 100;
private ArrayList<Item> searchResultList;
private ResultListCallbacks mCallbacks;
private InternetConnectionListener internetConnectionListener;
private ArrayList<Item> resultList;
private ListView resultListView;
private LatLng itemLocation;
GPSTrackStandAlone gTrack = new GPSTrackStandAlone(getContext());
MapActivity mAct = new MapActivity();
public HomeActivity hAct = new HomeActivity();
public ResultListFragment() {
}
public static ResultListFragment newInstance(String id, String title) {
ResultListFragment fragment = new ResultListFragment();
catId = id;
titleId = title;
searchTerm = "";
locationChangeListener = fragment;
return fragment;
}
public static ResultListFragment newInstance(String id, String title,String term) {
ResultListFragment fragment = new ResultListFragment();
catId = id;
titleId = title;
searchTerm = term;
locationChangeListener = fragment;
return fragment;
}
public void getGPSLoc(){
double latitude = mAct.getLatitudeSend();
double longitude = mAct.getLongitudeSend();
Log.d("LatitudeCurrGPSLoc",String.valueOf(latitude));
Log.d("LongCur",String.valueOf(longitude));
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (ResultListCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement ResultListCallbacks.");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_result_list, container, false);
resultListView = (ListView) rootView.findViewById(R.id.resultListView);
setHasOptionsMenu(true);
return rootView;
}
#Override
public void onResume() {
super.onResume();
isHomeOpened = false;
isResultListFragmentOpened = true;
if (UtilMethods.isConnectedToInternet(getActivity())) {
if (!TextUtils.isEmpty(catId))
initResultList();
else if (!TextUtils.isEmpty(searchTerm))
getSearchResults(searchTerm);
} else {
internetConnectionListener = (InternetConnectionListener) ResultListFragment.this;
showNoInternetDialog(getActivity(), internetConnectionListener, getResources().getString(R.string.no_internet),
getResources().getString(R.string.no_internet_text),
getResources().getString(R.string.retry_string),
getResources().getString(R.string.exit_string), RESULT_ACTION);
}
}
private void initResultList() {
Log.d("Pembuktian", catId);
if(Integer.parseInt(catId)>100 && Integer.parseInt(catId)<200 ){
new getCarRent().execute();
}else if(Integer.parseInt(catId)>199 && Integer.parseInt(catId)<300){
new getCarBrand().execute();
}else if(Integer.parseInt(catId)>299 && Integer.parseInt(catId)<400){
new getCarType().execute();
}
/**
* json is populating from text file. To make api call use ApiHandler class
* pass parameter using ContentValues (values)
*
* <CODE> ApiHandler handler = new ApiHandler(this, URL_GET_RESULT_LIST_WITH_AD, values);</CODE> <BR>
* <CODE> handler.doApiRequest(ApiHandler.REQUEST_POST);</CODE> <BR>
*
* You will get the response in onSuccessResponse(String tag, String jsonString) method
* if successful api call has done.
*/
// String jsonString = loadJSONFromAsset(getActivity(), "get_result_list");
//parseJson(jsonString);
}
private void getSearchResults(String query) {
/**
* json is populating from text file. To make api call use ApiHandler class
* pass parameter using ContentValues (values)
*
* <CODE> ApiHandler handler = new ApiHandler(this, URL_GET_SEARCH_LIST_AD, values);</CODE> <BR>
* <CODE> handler.doApiRequest(ApiHandler.REQUEST_POST);</CODE> <BR>
*
* You will get the response in onSuccessResponse(String tag, String jsonString) method
* if successful api call has done.
*/
String jsonString = loadJSONFromAsset(getActivity(), "get_search_list");
parseJson(jsonString);
}
public class getCarRent extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
URL hp = null;
try {
hp = new URL(getString(R.string.liveurl)
+ "getCarRent.php?value=" + catId);
// hp = new URL(
// "http://192.168.1.106/restourant/foodtype.php?value="
// + id);
Log.d("URL", "" + hp);
URLConnection hpCon = hp.openConnection();
hpCon.connect();
InputStream input = hpCon.getInputStream();
Log.d("input", "" + input);
BufferedReader r = new BufferedReader(new InputStreamReader(
input));
String x = "";
x = r.readLine();
String total = "";
while (x != null) {
total += x;
x = r.readLine();
}
Log.d("URL", "" + total);
JSONArray j = new JSONArray(total);
Log.d("URL1", "" + j.length());
Item[] itemList = new Item[j.length()];
resultList = new ArrayList<Item>();
for (int i = 0; i < j.length(); i++) {
Item item = new Item();// buat variabel category
//JSONObject Obj;
JSONObject Obj = j.getJSONObject(i); //sama sperti yang lama, cman ini lebih mempersingkat karena getJSONObject cm d tulis sekali aja disini
item.setId(Obj.getString(JF_ID));
//item.setTitle(Obj.getString(JF_TITLE));
item.setAddress(Obj.getString(JF_ADDRESS));
item.setTelephoneNumber(Obj.optString(JF_TELEPHONE, NO_DATA_FOUND));
item.setEmailAddress(Obj.optString(JF_EMAIL, NO_DATA_FOUND));
item.setWebUrl(Obj.optString(JF_WEB, NO_DATA_FOUND));
item.setFacebookUrl(Obj.optString(JF_FACEBOOK, NO_DATA_FOUND));
item.setLatitude(Obj.optDouble(JF_LATITUDE, NULL_LOCATION));
item.setLongitude(Obj.optDouble(JF_LONGITUDE, NULL_LOCATION));
try {
item.setRating(Float.parseFloat(Obj.optString(JF_RATING, NO_DATA_FOUND)));
} catch (NumberFormatException e) {
item.setRating(0.0f);
}
try {
item.setRatingCount(Integer.parseInt(Obj.optString(JF_RATING_COUNT, NO_DATA_FOUND)));
} catch (NumberFormatException e) {
item.setRatingCount(0);
}
try {
item.setRatingCount(Integer.parseInt(Obj.optString(JF_RATINGSCORE, NO_DATA_FOUND)));
} catch (NumberFormatException e) {
item.setRatingCount(0);
}
item.setTagLine(Obj.optString(JF_TAG_LINE, NO_DATA_FOUND));
item.setDescription(Obj.optString(JF_DESCRIPTION, NO_DATA_FOUND));
item.setVerification(Obj.optString(JF_VERIFICATION, NO_DATA_FOUND).equals("1") ? true : false);
item.setCarId(Obj.optString(JF_CARID, NO_DATA_FOUND));
item.setTitle(Obj.optString(JF_CARTITLE, NO_DATA_FOUND));
item.setCarRentalId(Obj.optString(JF_CARRENTALID, NO_DATA_FOUND));
item.setCarPrice(Obj.optString(JF_CARPRICE, NO_DATA_FOUND));
item.setCarYear(Obj.optString(JF_CARYEAR, NO_DATA_FOUND));
JSONArray imgArr = Obj.getJSONArray("thumbImage");
String[] imageThumb = new String[imgArr.length()];
// String[] imageLarge = new String[imgArr.length()];
for (int k = 0; k < imgArr.length(); k++) {
imageThumb[k] = imgArr.getString(k);
// imageLarge[k] = imgArr.getJSONObject(k).getString(JF_TITLE);
}
for(int l = 0; l <imgArr.length(); l++) {
item.setImageLargeUrls(imageThumb);
}
item.setImageThumbUrls(imageThumb);
// item.setImageLargeUrls(imageLarge);
// JSONArray imgArr = Obj.getJSONArray("thumbImage");
/*String[] imgCount = new String[imgArr.length()];
for(int k = 0 ; k < imgCount.length; k++) {
imgCount[k] = imgArr.getString(k);
item.setImageThumbUrls(imgCount);
}*/
Location trgtLocation = new Location("trgtLocation");
trgtLocation.setLatitude(item.getLatitude());
trgtLocation.setLongitude(item.getLongitude());
Location crntLocation = new Location("crntlocation");
crntLocation.setLatitude(gTrack.getLatitude());
crntLocation.setLongitude(gTrack.getLongitude());
Log.d("latitudeCurr", String.valueOf(gTrack.getLatitude()));
Log.d("curLocLong", String.valueOf(gTrack.getLongitude()));
//LatLng currentLatLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
item.setDistance(crntLocation.distanceTo(trgtLocation) / 1000);
Log.d("distance", String.valueOf(item.getDistance()));
Log.d("URL1", "" + Obj.getString(JF_TITLE));
resultList.add(item);
itemList[i]=item;
Log.d("itemList",String.valueOf(itemList[i]));
Arrays.sort(itemList, new Comparator<Item>() {
#Override
public int compare(Item lhs, Item rhs) {
return 0;
}
});
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
resultListView.setAdapter(new ResultListAdapterRental(getActivity(), mCallbacks, resultList));
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
// TODO: handle exception
}
return null;
}
}
I try to take the Lng and Lat from a System service like this one, but it's still doesn't work. Is this code right ?
GPSTracker.java
public class GPSTrackStandAlone extends Service implements LocationListener {
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Context mContext;
private boolean isGpsEnabled = false;
private boolean isNetworkEnabled = false;
private boolean canGetLocation = false;
private Location mLocation;
private double mLatitude;
private double mLongitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 60000;
private LocationManager mLocationManager;
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
public GPSTrackStandAlone(Context mContext) {
this.mContext = mContext;
}
/**
* #return location
*/
public Location getLocation() {
try {
mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
/*getting status of the gps*/
isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
/*getting status of network provider*/
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGpsEnabled && !isNetworkEnabled) {
/*no location provider enabled*/
} else {
this.canGetLocation = true;
/*getting location from network provider*/
if (isNetworkEnabled) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_FOR_UPDATE,
MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
Log.d("Perms", "Permission for GPS Granted");
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
}
}
}
/*if gps is enabled then get location using gps*/
if (isGpsEnabled) {
if (mLocation == null) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_FOR_UPDATE,
MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
Log.d("GPS Enabled", "GPS Enabled");
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return mLocation;
}
/**
* call this function to stop using gps in your application
*/
public void stopUsingGps() {
if (mLocationManager != null) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager.removeUpdates(GPSTrackStandAlone.this);
}
}
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
Toast.makeText(GPSTrackStandAlone.this, "isGooglePlayServiceAvailable = False", Toast.LENGTH_SHORT).show();
return false;
}
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
/**
* #return latitude
* <p/>
* function to get latitude
*/
public double getLatitude() {
getLocation();
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
}
return mLatitude;
}
/**
* #return longitude
* function to get longitude
*/
public double getLongitude() {
getLocation();
if (mLocation != null) {
mLongitude = mLocation.getLongitude();
Log.d("MGPS", String.valueOf(mLocation.getLatitude()));
}
return mLongitude;
}
/**
* #return to check gps or wifi is enabled or not
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Have you consider to use the Google Maps API ? With it you can simply do the following to get the user's current location :
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setMyLocationEnabled(true);
Location myLocation = googleMap.getMyLocation();
Do you mean that you can getLng and getLat in activity ?
Try to use a public static to describe your values,and use MyActivity.value in Fragment.
when you want to pass the data from activity to fragment you should use bundle .
I will give you the example.
public class CompleteJobFragment extends Fragment {
private final static String PICKUP_TIME="pickup time";
public static CompleteJobFragment newInstance(String pickUpTime) {
CompleteJobFragment fragment = new CompleteJobFragment();
Bundle bundle = new Bundle();
bundle.putString(PICKUP_TIME, pickUpTime);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
pickUpTime = getArguments().getString(PICKUP_TIME);
}
}
Activity file
public class ActiveJobActivity extends AppCompatActivity {
String x1;
public void loadData()
{
CompleteJobFragment completeJobFragment = CompleteJobFragment.newInstance(x1);
final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.activez, completeJobFragment, COMPLETE_FRAGMENT);
fragmentTransaction.addToBackStack(COMPLETE_FRAGMENT);
completeJobFragment.setCommunicator(this);
fragmentTransaction.commit();
}
Related
i made a googlemap app where my markers are displyed.
the problem is when there no internet, the app is crashing. The code under onResume does not solve the problem.
also i want to refresh the map or markers each second on the map.
if you have any ideas please i am here to learn from all of you.
here is my MapActivity code :
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback
{
private static final String TAG = "MapActivity";
#Bind(R.id.back)
View back;
#Bind(R.id.zoom_in)
View zoom_in;
#Bind(R.id.zoom_out)
View zoom_out;
#Bind(R.id.updatetimer)
TextView updatetimer;
#Bind(R.id.autozoom)
ImageView autozoom;
#Bind(R.id.showtails)
ImageView showtails;
#Bind(R.id.geofences)
ImageView showGeofences;
#Bind(R.id.map_layer)
ImageView map_layer_icon;
private GoogleMap map;
#Bind(R.id.content_layout)
View content_layout;
#Bind(R.id.loading_layout)
View loading_layout;
#Bind(R.id.nodata_layout)
View nodata_layout;
private Timer timer;
private int autoZoomedTimes = 0;// dėl bugo osmdroid library, zoom'inam du kartus ir paskui po refresh'o nebe, nes greičiausiai user'is bus pakeitęs zoom'ą
private HashMap<Integer, Marker> deviceIdMarkers;
private HashMap<String, Device> markerIdDevices;
private HashMap<Integer, Polyline> deviceIdPolyline;
private HashMap<Integer, LatLng> deviceIdLastLatLng;
// private HashMap<Integer, Marker> deviceIdSmallMarkerInfo;
private long lastRefreshTime;
boolean isAutoZoomEnabled = true;
boolean isShowTitlesEnabled;
boolean isShowTailsEnabled = true;
boolean isShowGeofencesEnabled = true;
private String stopTime;
private AsyncTask downloadingAsync;
private boolean isRefreshLoced = false;
ApiInterface.GetGeofencesResult geofencesResult;
ArrayList<PolygonWithName> polygonsWithDetails = new ArrayList<>();
float previousZoomLevel = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
ButterKnife.bind(this);
deviceIdMarkers = new HashMap<>();
markerIdDevices = new HashMap<>();
deviceIdPolyline = new HashMap<>();
deviceIdLastLatLng = new HashMap<>();
// deviceIdSmallMarkerInfo = new HashMap<>();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
protected void onResume()
{
super.onResume();
timer = new Timer();
timer.schedule(new TimerTask()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
float timeleft = 10 - Math.round(System.currentTimeMillis() - lastRefreshTime) / 1000f;
if (timeleft < 0)
timeleft = 0;
updatetimer.setText(String.format("%.0f", timeleft));
if (System.currentTimeMillis() - lastRefreshTime >= 10 * 1000)
if (map != null)
refresh();
}
});
}
}, 0, 1000);
}
#Override
protected void onPause()
{
super.onPause();
try
{
timer.cancel();
timer.purge();
downloadingAsync.cancel(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
private void refresh()
{
if (isRefreshLoced)
return;
isRefreshLoced = true;
lastRefreshTime = System.currentTimeMillis();
final String api_key = (String) DataSaver.getInstance(this).load("api_key");
API.getApiInterface(this).getDevices(api_key, getResources().getString(R.string.lang), new Callback<ArrayList<ApiInterface.GetDevicesItem>>()
{
#Override
public void success(final ArrayList<ApiInterface.GetDevicesItem> getDevicesItems, Response response)
{
Log.d(TAG, "success: loaded devices array");
final ArrayList<Device> allDevices = new ArrayList<>();
if (getDevicesItems != null)
for (ApiInterface.GetDevicesItem item : getDevicesItems)
allDevices.addAll(item.items);
API.getApiInterface(MapActivity.this).getFieldsDataForEditing(api_key, getResources().getString(R.string.lang), 1, new Callback<ApiInterface.GetFieldsDataForEditingResult>()
{
#Override
public void success(final ApiInterface.GetFieldsDataForEditingResult getFieldsDataForEditingResult, Response response)
{
Log.d(TAG, "success: loaded icons");
downloadingAsync = new AsyncTask<Void, Void, Void>()
{
ArrayList<MarkerOptions> markers;
ArrayList<Integer> deviceIds;
#Override
protected Void doInBackground(Void... params)
{
// add markers
int dp100 = Utils.dpToPx(MapActivity.this, 50);
markers = new ArrayList<>();
deviceIds = new ArrayList<>();
if (getFieldsDataForEditingResult == null || getFieldsDataForEditingResult.device_icons == null)
return null;
for (Device item : allDevices)
{
if (isCancelled())
break;
if (item.device_data.active == 1)
{
// ieškom ikonos masyve
DeviceIcon mapIcon = null;
for (DeviceIcon icon : getFieldsDataForEditingResult.device_icons)
if (item.device_data.icon_id == icon.id)
mapIcon = icon;
String server_base = (String) DataSaver.getInstance(MapActivity.this).load("server_base");
try
{
Log.d("MapActivity", "DOWNLOADING BITMAP: " + server_base + mapIcon.path);
Bitmap bmp = BitmapFactory.decodeStream(new URL(server_base + mapIcon.path).openConnection().getInputStream());
int srcWidth = bmp.getWidth();
int srcHeight = bmp.getHeight();
int maxWidth = Utils.dpToPx(MapActivity.this, mapIcon.width);
int maxHeight = Utils.dpToPx(MapActivity.this, mapIcon.height);
float ratio = Math.min((float) maxWidth / (float) srcWidth, (float) maxHeight / (float) srcHeight);
int dstWidth = (int) (srcWidth * ratio);
int dstHeight = (int) (srcHeight * ratio);
bmp = bmp.createScaledBitmap(bmp, dp100, dp100, true);
// marker
MarkerOptions m = new MarkerOptions();
m.position(new LatLng(item.lat, item.lng));
// marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
// marker.setIcon(new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, true)));
m.icon(BitmapDescriptorFactory.fromBitmap(Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, true)));
// info window
// MapMarkerInfoWindow infoWindow = new MapMarkerInfoWindow(MapActivity.this, item, R.layout.layout_map_infowindow, map);
// marker.setInfoWindow(infoWindow);
markers.add(m);
deviceIds.add(item.id);
} catch (OutOfMemoryError outOfMemoryError)
{
Toast.makeText(MapActivity.this, "Out of memory! Too many devices are selected to be displayed", Toast.LENGTH_LONG).show();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid)
{
ArrayList<GeoPoint> points = new ArrayList<>();
if (autoZoomedTimes < 1)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
if (markers.size() > 1)
{
try
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (MarkerOptions item : markers)
builder.include(item.getPosition());
LatLngBounds bounds = builder.build();
// int padding = 0; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, Utils.dpToPx(MapActivity.this, 50));
map.animateCamera(cu);
} catch (Exception e)
{
}
} else if (markers.size() > 0)
{
map.moveCamera(CameraUpdateFactory.newLatLngZoom(markers.get(0).getPosition(), 15));
}
autoZoomedTimes++;
}
});
}
}, 50);
} else if (isAutoZoomEnabled)
{
if (markers.size() > 1)
{
try
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (MarkerOptions item : markers)
builder.include(item.getPosition());
LatLngBounds bounds = builder.build();
// int padding = 0; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, Utils.dpToPx(MapActivity.this, 50));
map.animateCamera(cu);
} catch (Exception e)
{
}
} else if (markers.size() > 0)
{
map.moveCamera(CameraUpdateFactory.newLatLngZoom(markers.get(0).getPosition(), 15));
}
autoZoomedTimes++;
}
Log.d(TAG, "onPostExecute: icons downloaded and added to map, total markers: " + markers.size());
loading_layout.setVisibility(View.GONE);
if (markers.size() != 0)
content_layout.setVisibility(View.VISIBLE);
else
nodata_layout.setVisibility(View.VISIBLE);
for (int i = 0; i < markers.size(); i++)
{
MarkerOptions options = markers.get(i);
int deviceId = deviceIds.get(i);
Marker m;
Polyline polyline;
if (deviceIdMarkers.containsKey(deviceId))
{
Log.d("aa", "moving to" + options.getPosition());
deviceIdMarkers.get(deviceId).setPosition(new LatLng(options.getPosition().latitude, options.getPosition().longitude));
m = deviceIdMarkers.get(deviceId);
polyline = deviceIdPolyline.get(deviceId);
} else
{
Log.d("aa", "putting new");
m = map.addMarker(options);
deviceIdMarkers.put(deviceId, m);
polyline = map.addPolyline(new PolylineOptions());
deviceIdPolyline.put(deviceId, polyline);
}
Device thatonedevice = null;
for (Device device : allDevices)
if (device.id == deviceId)
thatonedevice = device;
markerIdDevices.put(m.getId(), thatonedevice);
// update marker rotation based on driving direction
if (thatonedevice != null && deviceIdLastLatLng.containsKey(deviceId))
{
double dirLat = thatonedevice.lat - deviceIdLastLatLng.get(deviceId).latitude;
double dirLng = thatonedevice.lng - deviceIdLastLatLng.get(deviceId).longitude;
m.setRotation((float) Math.toDegrees(Math.atan2(dirLng, dirLat)));
}
deviceIdLastLatLng.put(deviceId, new LatLng(thatonedevice.lat, thatonedevice.lng));
List<LatLng> polylinePoints = new ArrayList<>();
for (TailItem item : thatonedevice.tail)
polylinePoints.add(new LatLng(Double.valueOf(item.lat), Double.valueOf(item.lng)));
polyline.setPoints(polylinePoints);
polyline.setWidth(Utils.dpToPx(MapActivity.this, 2));
polyline.setColor(Color.parseColor(thatonedevice.device_data.tail_color));
}
// else
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter()
{
#Override
public View getInfoWindow(Marker marker)
{
return null;
}
#Override
public View getInfoContents(final Marker marker)
{
synchronized (this)
{
}
final Device device = markerIdDevices.get(marker.getId());
if (device != null)
{
View view = getLayoutInflater().inflate(R.layout.layout_map_infowindow, null);
view.bringToFront();
view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
marker.hideInfoWindow();
}
});
TextView device_name = (TextView) view.findViewById(R.id.device_name);
device_name.setText(device.name);
TextView altitude = (TextView) view.findViewById(R.id.altitude);
altitude.setText(String.valueOf(device.altitude) + " " + device.unit_of_altitude);
TextView time = (TextView) view.findViewById(R.id.time);
time.setText(device.time);
TextView stopTimeView = (TextView) view.findViewById(R.id.stopTime);
stopTimeView.setText(stopTime);
TextView speed = (TextView) view.findViewById(R.id.speed);
speed.setText(device.speed + " " + device.distance_unit_hour);
TextView address = (TextView) view.findViewById(R.id.address);
address.setText(device.address);
final ArrayList<Sensor> showableSensors = new ArrayList<>();
for (Sensor item : device.sensors)
if (item.show_in_popup > 0)
showableSensors.add(item);
ListView sensors_list = (ListView) view.findViewById(R.id.sensors_list);
sensors_list.setAdapter(new AwesomeAdapter<Sensor>(MapActivity.this)
{
#Override
public int getCount()
{
return showableSensors.size();
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent)
{
if (convertView == null)
convertView = getLayoutInflater().inflate(R.layout.adapter_map_sensorslist, null);
Sensor item = showableSensors.get(position);
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(item.name);
TextView value = (TextView) convertView.findViewById(R.id.value);
value.setText(item.value);
return convertView;
}
});
List<Address> addresses;
try
{
addresses = new Geocoder(MapActivity.this).getFromLocation(device.lat, device.lng, 1);
if (addresses.size() > 0)
address.setText(addresses.get(0).getAddressLine(0));
} catch (IOException e)
{
e.printStackTrace();
}
return view;
}
return null;
}
});
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()
{
#Override
public boolean onMarkerClick(final Marker marker)
{
int px = Utils.dpToPx(MapActivity.this, 300);
map.setPadding(0, px, 0, 0);
stopTime = "...";
final Device device = markerIdDevices.get(marker.getId());
if (device != null)
{
API.getApiInterface(MapActivity.this).deviceStopTime((String) DataSaver.getInstance(MapActivity.this).load("api_key"), "en", device.id, new Callback<ApiInterface.DeviceStopTimeResult>()
{
#Override
public void success(ApiInterface.DeviceStopTimeResult result, Response response)
{
stopTime = result.time;
marker.showInfoWindow();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
return false;
}
});
map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener()
{
#Override
public void onInfoWindowClick(Marker marker)
{
marker.hideInfoWindow();
}
});
map.setOnInfoWindowCloseListener(new GoogleMap.OnInfoWindowCloseListener()
{
#Override
public void onInfoWindowClose(Marker marker)
{
map.setPadding(0, 0, 0, 0);
}
});
// updateSmallMarkerData(allDevices);
isRefreshLoced = false;
}
}.execute();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
isRefreshLoced = false;
}
});
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
isRefreshLoced = false;
}
});
}
#Override
public void onMapReady(GoogleMap googleMap)
{
map = googleMap;
refresh();
}
this MapActivity is slow to load, could you teach me a way to make it goes faster?
Best regard :)
waiting for your propositions.
PS: i have removed some functions to make the code look short but i kept the most important in is case.
For the crashing issue
create a class
public class NetWorkChecker {
static NetworkInfo wifi, mobile;
public static Boolean check(Context c) {
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
} catch (Exception e) {
e.printStackTrace();
}
if (wifi != null && wifi.isConnected() && wifi.isAvailable()) {
return true;
} else if (mobile != null && mobile.isAvailable() && mobile.isConnected()) {
return true;
} else {
//Toast.makeText(c, "No Network Connection", Toast.LENGTH_SHORT).show();
// ((Activity) c).finish();
displayMobileDataSettingsDialog(c,"No Network Connection","No Network Connection");
return false;
}
}
public static AlertDialog displayMobileDataSettingsDialog(final Context context, String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
context.startActivity(intent);
}
});
builder.show();
return builder.create();
}
}
to check if the devise have an active internet connection
call
if (!NetWorkChecker.check(this)){
////do your refres
}
I am using location listener to track the location.I implement the location listener, there are inbuilt methods of location listener such as onLocationChanged,OnstatusChanged,onProviderEnabled etc.Whenerver the location changed it will hit on server but I want to do at every 10 min of interval So I am using timer for that after every 10 mins it will hit the location. I cannot call the method inside the timer. So how to do it.
public class LocationMonitoringService implements LocationListener, GpsStatus.Listener {
private static final String TAG = LocationMonitoringService.class.getSimpleName();
private final Context mContext;
private final LocationRepository mLocationRepository;
private final ShareLocationAdapterClass mAdapter;
private final SyncOfflineRepository syncOfflineRepository;
private long updatedTime = 0;
private final List<UserLocationPojo> mUserLocationPojoList;
private final SyncOfflineAttendanceRepository syncOfflineAttendanceRepository;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000 * 60 * 5;
public LocationMonitoringService(final Context context) {
mContext = context;
mLocationRepository = new LocationRepository(AUtils.mainApplicationConstant.getApplicationContext());
syncOfflineRepository = new SyncOfflineRepository(AUtils.mainApplicationConstant.getApplicationContext());
syncOfflineAttendanceRepository = new SyncOfflineAttendanceRepository(AUtils.mainApplicationConstant.getApplicationContext());
mUserLocationPojoList = new ArrayList<>();
mAdapter = new ShareLocationAdapterClass();
mAdapter.setShareLocationListener(new ShareLocationAdapterClass.ShareLocationListener() {
#Override
public void onSuccessCallBack(boolean isAttendanceOff) {
if (isAttendanceOff && !syncOfflineAttendanceRepository.checkIsAttendanceIn()) {
AUtils.setIsOnduty(false);
((MyApplication) AUtils.mainApplicationConstant).stopLocationTracking();
}
}
#Override
public void onFailureCallBack() {
}
});
}
public void onStartTacking() {
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
//Exception thrown when GPS or Network provider were not available on the user's device.
try {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setAltitudeRequired(false);
criteria.setSpeedRequired(true);
criteria.setCostAllowed(false);
criteria.setBearingRequired(false);
//API level 9 and up
criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
int gpsFreqInDistance =100;
assert locationManager != null;
locationManager.addGpsStatusListener(this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this,null);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this,null);
} catch (IllegalArgumentException | SecurityException e) {
Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
Log.d(TAG, "onStartTacking: " + e.getMessage());
Log.d(TAG, "onStartTacking: " + e.getLocalizedMessage());
e.printStackTrace();
} catch (RuntimeException e) {
Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
Log.d(TAG, "onStartTacking: " + e.getMessage());
e.printStackTrace();
}
}
public void onStopTracking(Context context) {
mAdapter.shareLocation();
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
// cancelAlarm(context, (AlarmManager)context.getSystemService(Context.ALARM_SERVICE));
}
/*
* LOCATION CALLBACKS
*/
//to get the location change
#Override
public void onLocationChanged(Location location) {
Log.d("okh ", "onLocationChanged: "+System.currentTimeMillis());
if (location != null) {
Log.d(TAG, String.valueOf(location.getAccuracy()));
if (!AUtils.isNullString(String.valueOf(location.getLatitude())) && !AUtils.isNullString(String.valueOf(location.getLongitude()))) {
Prefs.putString(AUtils.LAT, String.valueOf(location.getLatitude()));
Prefs.putString(AUtils.LONG, String.valueOf(location.getLongitude()));
if (Prefs.getBoolean(AUtils.PREFS.IS_ON_DUTY, false)) {
if (updatedTime == 0) {
updatedTime = System.currentTimeMillis();
Log.d(TAG, "updated Time ==== " + updatedTime);
}
if ((updatedTime + AUtils.LOCATION_INTERVAL_MINUTES) <= System.currentTimeMillis()) {
updatedTime = System.currentTimeMillis();
Log.d(TAG, "updated Time ==== " + updatedTime);
}
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(), 5,notify_interval);
// sendLocation();
}
}
} else {
Log.d(TAG, "onLocationChanged: no location found !!");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged" + provider + "Status" + status);
}
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, " onProviderEnabled" + provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, " onProviderDisabled" + provider);
}
#Override
public void onGpsStatusChanged(int event) {
}
private void sendLocation() {
// mAdapter.shareLocation(getTempList());
Log.d("okh", "sendLocation: Current Time In Millies "+ System.currentTimeMillis());
try {
Calendar CurrentTime = AUtils.getCurrentTime();
Calendar DutyOffTime = AUtils.getDutyEndTime();
if (CurrentTime.before(DutyOffTime)) {
Log.i(TAG, "Before");
UserLocationPojo userLocationPojo = new UserLocationPojo();
userLocationPojo.setUserId(Prefs.getString(AUtils.PREFS.USER_ID, ""));
userLocationPojo.setLat(Prefs.getString(AUtils.LAT, ""));
userLocationPojo.setLong(Prefs.getString(AUtils.LONG, ""));
double startLat = Double.parseDouble(Prefs.getString(AUtils.LAT, "0"));
double startLng = Double.parseDouble(Prefs.getString(AUtils.LONG, "0"));
userLocationPojo.setDistance(String.valueOf(AUtils.calculateDistance(
AUtils.mainApplicationConstant.getApplicationContext(), startLat, startLng)));
// userLocationPojo.setDatetime(AUtils.getServerDateTime()); //TODO
userLocationPojo.setDatetime(AUtils.getServerDateTimeLocal());
userLocationPojo.setOfflineId("0");
userLocationPojo.setIsOffline(AUtils.isInternetAvailable() && AUtils.isConnectedFast(mContext));
String UserTypeId = Prefs.getString(AUtils.PREFS.USER_TYPE_ID, AUtils.USER_TYPE.USER_TYPE_GHANTA_GADI);
if (AUtils.isInternetAvailable()) {
TableDataCountPojo.LocationCollectionCount count = syncOfflineRepository.getLocationCollectionCount(AUtils.getLocalDate());
if ((UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_GHANTA_GADI) || UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_WASTE_MANAGER))
&& (count.getLocationCount() > 0 || count.getCollectionCount() > 0)) {
syncOfflineRepository.insetUserLocation(userLocationPojo);
} else {
mUserLocationPojoList.add(userLocationPojo);
mAdapter.shareLocation(mUserLocationPojoList);
mUserLocationPojoList.clear();
}
} else {
if (UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_EMP_SCANNIFY)) {
Type type = new TypeToken<UserLocationPojo>() {
}.getType();
mLocationRepository.insertUserLocationEntity(new Gson().toJson(userLocationPojo, type));
} else {
syncOfflineRepository.insetUserLocation(userLocationPojo);
}
mUserLocationPojoList.clear();
}
}
else {
Log.i(TAG, "After");
syncOfflineAttendanceRepository.performCollectionInsert(mContext,
syncOfflineAttendanceRepository.checkAttendance(), AUtils.getCurrentDateDutyOffTime());
AUtils.setIsOnduty(false);
((MyApplication) AUtils.mainApplicationConstant).stopLocationTracking();
Activity activity = ((Activity) AUtils.currentContextConstant);
if (activity instanceof DashboardActivity) {
((Activity) AUtils.currentContextConstant).recreate();
AUtils.DutyOffFromService = true;
}
if (!AUtils.isNull(AUtils.currentContextConstant)) {
((Activity) AUtils.currentContextConstant).recreate();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private class TimerTaskToGetLocation extends TimerTask {
#Override
public void run() {
sendLocation();
}
}
}
Here is the code please try this:
public class LocationMonitoringService implements LocationListener, GpsStatus.Listener {
private static final String TAG = LocationMonitoringService.class.getSimpleName();
private final Context mContext;
private final LocationRepository mLocationRepository;
private final ShareLocationAdapterClass mAdapter;
private final SyncOfflineRepository syncOfflineRepository;
private long updatedTime = 0;
private int gpsFreqInDistance =100;
private LocationManager locationManager;
private final List<UserLocationPojo> mUserLocationPojoList;
private final SyncOfflineAttendanceRepository syncOfflineAttendanceRepository;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000 * 60 * 5;
public LocationMonitoringService(final Context context) {
mContext = context;
// here we declare the variable as a field for this class instance
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
mLocationRepository = new LocationRepository(AUtils.mainApplicationConstant.getApplicationContext());
syncOfflineRepository = new SyncOfflineRepository(AUtils.mainApplicationConstant.getApplicationContext());
syncOfflineAttendanceRepository = new SyncOfflineAttendanceRepository(AUtils.mainApplicationConstant.getApplicationContext());
mUserLocationPojoList = new ArrayList<>();
mAdapter = new ShareLocationAdapterClass();
mAdapter.setShareLocationListener(new ShareLocationAdapterClass.ShareLocationListener() {
#Override
public void onSuccessCallBack(boolean isAttendanceOff) {
if (isAttendanceOff && !syncOfflineAttendanceRepository.checkIsAttendanceIn()) {
AUtils.setIsOnduty(false);
((MyApplication) AUtils.mainApplicationConstant).stopLocationTracking();
}
}
#Override
public void onFailureCallBack() {
}
});
}
public void onStartTacking() {
//Exception thrown when GPS or Network provider were not available on the user's device.
try {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setAltitudeRequired(false);
criteria.setSpeedRequired(true);
criteria.setCostAllowed(false);
criteria.setBearingRequired(false);
//API level 9 and up
criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
assert locationManager != null;
locationManager.addGpsStatusListener(this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this,null);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this,null);
} catch (IllegalArgumentException | SecurityException e) {
Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
Log.d(TAG, "onStartTacking: " + e.getMessage());
Log.d(TAG, "onStartTacking: " + e.getLocalizedMessage());
e.printStackTrace();
} catch (RuntimeException e) {
Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
Log.d(TAG, "onStartTacking: " + e.getMessage());
e.printStackTrace();
}
}
public void onStopTracking(Context context) {
mAdapter.shareLocation();
// removed initialization from here
locationManager.removeUpdates(this);
// cancelAlarm(context, (AlarmManager)context.getSystemService(Context.ALARM_SERVICE));
}
/*
* LOCATION CALLBACKS
*/
//to get the location change
#Override
public void onLocationChanged(Location location) {
Log.d("okh ", "onLocationChanged: "+System.currentTimeMillis());
if (location != null) {
Log.d(TAG, String.valueOf(location.getAccuracy()));
if (!AUtils.isNullString(String.valueOf(location.getLatitude())) && !AUtils.isNullString(String.valueOf(location.getLongitude()))) {
Prefs.putString(AUtils.LAT, String.valueOf(location.getLatitude()));
Prefs.putString(AUtils.LONG, String.valueOf(location.getLongitude()));
if (Prefs.getBoolean(AUtils.PREFS.IS_ON_DUTY, false)) {
if (updatedTime == 0) {
updatedTime = System.currentTimeMillis();
Log.d(TAG, "updated Time ==== " + updatedTime);
}
if ((updatedTime + AUtils.LOCATION_INTERVAL_MINUTES) <= System.currentTimeMillis()) {
updatedTime = System.currentTimeMillis();
Log.d(TAG, "updated Time ==== " + updatedTime);
}
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(), 5,notify_interval);
// sendLocation();
}
}
} else {
Log.d(TAG, "onLocationChanged: no location found !!");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged" + provider + "Status" + status);
}
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, " onProviderEnabled" + provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, " onProviderDisabled" + provider);
}
#Override
public void onGpsStatusChanged(int event) {
}
private void sendLocation() {
// mAdapter.shareLocation(getTempList());
Log.d("okh", "sendLocation: Current Time In Millies "+ System.currentTimeMillis());
try {
Calendar CurrentTime = AUtils.getCurrentTime();
Calendar DutyOffTime = AUtils.getDutyEndTime();
if (CurrentTime.before(DutyOffTime)) {
Log.i(TAG, "Before");
UserLocationPojo userLocationPojo = new UserLocationPojo();
userLocationPojo.setUserId(Prefs.getString(AUtils.PREFS.USER_ID, ""));
userLocationPojo.setLat(Prefs.getString(AUtils.LAT, ""));
userLocationPojo.setLong(Prefs.getString(AUtils.LONG, ""));
double startLat = Double.parseDouble(Prefs.getString(AUtils.LAT, "0"));
double startLng = Double.parseDouble(Prefs.getString(AUtils.LONG, "0"));
userLocationPojo.setDistance(String.valueOf(AUtils.calculateDistance(
AUtils.mainApplicationConstant.getApplicationContext(), startLat, startLng)));
// userLocationPojo.setDatetime(AUtils.getServerDateTime()); //TODO
userLocationPojo.setDatetime(AUtils.getServerDateTimeLocal());
userLocationPojo.setOfflineId("0");
userLocationPojo.setIsOffline(AUtils.isInternetAvailable() && AUtils.isConnectedFast(mContext));
String UserTypeId = Prefs.getString(AUtils.PREFS.USER_TYPE_ID, AUtils.USER_TYPE.USER_TYPE_GHANTA_GADI);
if (AUtils.isInternetAvailable()) {
TableDataCountPojo.LocationCollectionCount count = syncOfflineRepository.getLocationCollectionCount(AUtils.getLocalDate());
if ((UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_GHANTA_GADI) || UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_WASTE_MANAGER))
&& (count.getLocationCount() > 0 || count.getCollectionCount() > 0)) {
syncOfflineRepository.insetUserLocation(userLocationPojo);
} else {
mUserLocationPojoList.add(userLocationPojo);
mAdapter.shareLocation(mUserLocationPojoList);
mUserLocationPojoList.clear();
}
} else {
if (UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_EMP_SCANNIFY)) {
Type type = new TypeToken<UserLocationPojo>() {
}.getType();
mLocationRepository.insertUserLocationEntity(new Gson().toJson(userLocationPojo, type));
} else {
syncOfflineRepository.insetUserLocation(userLocationPojo);
}
mUserLocationPojoList.clear();
}
}
else {
Log.i(TAG, "After");
syncOfflineAttendanceRepository.performCollectionInsert(mContext,
syncOfflineAttendanceRepository.checkAttendance(), AUtils.getCurrentDateDutyOffTime());
AUtils.setIsOnduty(false);
((MyApplication) AUtils.mainApplicationConstant).stopLocationTracking();
Activity activity = ((Activity) AUtils.currentContextConstant);
if (activity instanceof DashboardActivity) {
((Activity) AUtils.currentContextConstant).recreate();
AUtils.DutyOffFromService = true;
}
if (!AUtils.isNull(AUtils.currentContextConstant)) {
((Activity) AUtils.currentContextConstant).recreate();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private class TimerTaskToGetLocation extends TimerTask {
#Override
public void run() {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this,null);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this,null);
}
}
}
Ill try my best to explain.
I have a page on my android app that is a google map that has stores locations on it.
Depending on the type of store, it has a custom icon. The link for the custom icon I retrieved trough MySQL.
The problem I am having is when I open the page instead of showing me the custom icons for the stores it shows me the default icon. But when I go to another page on the app and go back to the maps page it loads all the custom icons. It seems to me that on the first page launch it does not replace the default icon.
Since im new to programming ive added the whole page because I might be missing something. I think that the reason this is happening is due to the method "parseData()"
Thank you,
public class MapFragment extends Fragment implements
OnInfoWindowClickListener, OnMapClickListener,
OnClickListener, OnDrawingViewListener, GoogleMap.OnMapLoadedCallback{
private View viewInflate;
private GoogleMap googleMap;
private Location myLocation;
private HashMap<String, Store> markers;
private ArrayList<Marker> markerList;
private DisplayImageOptions options;
private MGSliding frameSliding;
private DrawingView drawingView;
private GMapV2Direction gMapV2;
private ArrayList<Store> storeList;
private ArrayList<Store> selectedStoreList;
private Store selectedStore;
Queries q;
MGAsyncTask task;
public MapFragment() { }
#Override
public void onDestroyView() {
super.onDestroyView();
try {
if (googleMap != null) {
FragmentManager fManager = this.getActivity().getSupportFragmentManager();
fManager.beginTransaction()
.remove(fManager.findFragmentById(R.id.googleMap)).commit();
googleMap = null;
}
if (viewInflate != null) {
ViewGroup parentViewGroup = (ViewGroup) viewInflate.getParent();
if (parentViewGroup != null) {
parentViewGroup.removeAllViews();
}
}
}
catch(Exception e) { }
if(task != null)
task.cancel(true);
}
#SuppressLint("InflateParams")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
viewInflate = inflater.inflate(R.layout.fragment_map2, null);
return viewInflate;
}
#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);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(UIConfig.SLIDER_PLACEHOLDER)
.showImageForEmptyUri(UIConfig.SLIDER_PLACEHOLDER)
.showImageOnFail(UIConfig.SLIDER_PLACEHOLDER)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
final MainActivity main = (MainActivity) getActivity();
q = main.getQueries();
frameSliding = (MGSliding) viewInflate.findViewById(R.id.frameSliding);
Animation animationIn = AnimationUtils.loadAnimation(this.getActivity(),
R.anim.slide_up2);
// int i = android.R.anim.slide_out_right;
Animation animationOut = AnimationUtils.loadAnimation(this.getActivity(),
R.anim.slide_down2);
frameSliding.setInAnimation(animationIn);
frameSliding.setOutAnimation(animationOut);
frameSliding.setVisibility(View.GONE);
ImageView imgViewDraw = (ImageView)viewInflate.findViewById(R.id.imgViewDraw);
imgViewDraw.setOnClickListener(this);
ImageView imgViewRefresh = (ImageView)viewInflate.findViewById(R.id.imgViewRefresh);
imgViewRefresh.setOnClickListener(this);
ImageView imgViewRoute = (ImageView)viewInflate.findViewById(R.id.imgViewRoute);
imgViewRoute.setOnClickListener(this);
ImageView imgViewLocation = (ImageView)viewInflate.findViewById(R.id.imgViewLocation);
imgViewLocation.setOnClickListener(this);
ImageView imgViewNearby = (ImageView)viewInflate.findViewById(R.id.imgViewNearby);
imgViewNearby.setOnClickListener(this);
main.showSwipeProgress();
FragmentManager fManager = getChildFragmentManager();
SupportMapFragment supportMapFragment =
((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
if(supportMapFragment == null) {
fManager = getActivity().getSupportFragmentManager();
supportMapFragment = ((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
}
googleMap = supportMapFragment.getMap();
googleMap.setOnMapLoadedCallback(this);
markers = new HashMap<String, Store>();
markerList = new ArrayList<Marker>();
}
#Override
public void onMapLoaded() {
FragmentManager fManager = getChildFragmentManager();
SupportMapFragment supportMapFragment =
((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
if(supportMapFragment == null) {
fManager = getActivity().getSupportFragmentManager();
supportMapFragment = ((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
}
googleMap = supportMapFragment.getMap();
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.setMyLocationEnabled(true);
googleMap.setOnMapClickListener(this);
googleMap.setOnInfoWindowClickListener(this);
googleMap.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
// TODO Auto-generated method stub
myLocation = location;
}
});
googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
if(frameSliding.getVisibility() == View.VISIBLE)
frameSliding.setVisibility(View.INVISIBLE);
}
});
gMapV2 = new GMapV2Direction();
drawingView = (DrawingView) viewInflate.findViewById(R.id.drawingView);
drawingView.setBrushSize(5);
drawingView.setPolygonFillColor(getResources().getColor(R.color.theme_black_color_opacity));
drawingView.setColor(getResources().getColor(R.color.theme_black_color));
drawingView.setPolylineColor(getResources().getColor(R.color.theme_black_color));
drawingView.setGoogleMap(googleMap);
drawingView.setOnDrawingViewListener(this);
if(MGUtilities.isLocationEnabled(getActivity())) {
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
getData();
}
}, Config.DELAY_SHOW_ANIMATION + 500);
}
else {
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
getData();
}
}, Config.DELAY_SHOW_ANIMATION + 500);
}
}
#SuppressLint("DefaultLocale")
#Override
public void onInfoWindowClick(Marker marker) {
// TODO Auto-generated method stub
final Store store = markers.get(marker.getId());
selectedStore = store;
if(myLocation != null) {
Location loc = new Location("marker");
loc.setLatitude(marker.getPosition().latitude);
loc.setLongitude(marker.getPosition().longitude);
double meters = myLocation.distanceTo(loc);
double miles = meters * 0.000621371f;
String str = String.format("%.1f %s",
miles,
MGUtilities.getStringFromResource(getActivity(), R.string.mi));
TextView tvDistance = (TextView) viewInflate.findViewById(R.id.tvDistance);
tvDistance.setText(str);
}
final MainActivity main = (MainActivity) getActivity();
q = main.getQueries();
frameSliding.setVisibility(View.VISIBLE);
ImageView imgViewThumb = (ImageView) viewInflate.findViewById(R.id.imageViewThumb);
Photo p = q.getPhotoByStoreId(store.getStore_id());
if(p != null) {
MainActivity.getImageLoader().displayImage(p.getPhoto_url(), imgViewThumb, options);
}
else {
imgViewThumb.setImageResource(UIConfig.SLIDER_PLACEHOLDER);
}
imgViewThumb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), DetailActivity.class);
i.putExtra("store", store);
getActivity().startActivity(i);
}
});
TextView tvTitle = (TextView) viewInflate.findViewById(R.id.tvTitle);
TextView tvSubtitle = (TextView) viewInflate.findViewById(R.id.tvSubtitle);
tvTitle.setText(Html.fromHtml(store.getStore_name()));
tvSubtitle.setText(Html.fromHtml(store.getIdade()));
ToggleButton toggleButtonFave = (ToggleButton) viewInflate.findViewById(R.id.toggleButtonFave);
toggleButtonFave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
checkFave(v, store);
}
});
Favorite fave = q.getFavoriteByStoreId(store.getStore_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, Store store) {
MainActivity mainActivity = (MainActivity)this.getActivity();
Queries q = mainActivity.getQueries();
Favorite fave = q.getFavoriteByStoreId(store.getStore_id());
if(fave != null) {
q.deleteFavorite(store.getStore_id());
((ToggleButton) view).setChecked(false);
}
else {
fave = new Favorite();
fave.setStore_id(store.getStore_id());
q.insertFavorite(fave);
((ToggleButton) view).setChecked(true);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case R.id.imgViewDraw:
drawingView.enableDrawing(true);
drawingView.startDrawingPolygon(true);
break;
case R.id.imgViewRefresh:
addStoreMarkers();
break;
case R.id.imgViewRoute:
getDirections();
break;
case R.id.imgViewLocation:
getMyLocation();
break;
case R.id.imgViewNearby:
getNearby();
break;
}
}
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);
markers = new HashMap<String, Store>();
markerList = new ArrayList<Marker>();
selectedStoreList = new ArrayList<Store>();
markerList.clear();
markers.clear();
for(Marker mark1 : markers1) {
for(Store entry : storeList) {
if(mark1.getTitle().toLowerCase().compareTo(entry.getStore_name().toLowerCase()) == 0) {
Marker mark = createMarker(entry);
markerList.add(mark);
markers.put(mark.getId(), entry);
selectedStoreList.add(entry);
break;
}
}
}
drawingView.enableDrawing(false);
drawingView.resetPolygon();
drawingView.startNew();
}
#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;
}
public void addStoreMarkers() {
if(googleMap != null)
googleMap.clear();
try {
MainActivity main = (MainActivity) this.getActivity();
Queries q = main.getQueries();
storeList = q.getStores();
markerList.clear();
markers.clear();
for(Store entry: storeList) {
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();
}
}
public void getDirections() {
if(selectedStore == null) {
Toast.makeText(getActivity(), R.string.select_one_store, Toast.LENGTH_SHORT).show();
return;
}
MGAsyncTask asyncTask = new MGAsyncTask(getActivity());
asyncTask.setMGAsyncTaskListener(new OnMGAsyncTaskListener() {
private ArrayList<ArrayList<LatLng>> allDirections;
#Override
public void onAsyncTaskProgressUpdate(MGAsyncTask asyncTask) { }
#Override
public void onAsyncTaskPreExecute(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
allDirections = new ArrayList<ArrayList<LatLng>>();
}
#Override
public void onAsyncTaskPostExecute(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
for(ArrayList<LatLng> directions : allDirections) {
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
for(LatLng latLng : directions) {
rectLine.add(latLng);
}
googleMap.addPolyline(rectLine);
}
if(allDirections.size() <= 0) {
Toast.makeText(getActivity(), R.string.cannot_determine_direction, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onAsyncTaskDoInBackground(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
parseData();
if(myLocation != null && selectedStore != null) {
LatLng marker1 = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
LatLng marker2 = new LatLng(selectedStore.getLat(), selectedStore.getLon());
Document doc = gMapV2.getDocument1(
marker1, marker2, GMapV2Direction.MODE_DRIVING);
ArrayList<LatLng> directionPoint = gMapV2.getDirection(doc);
allDirections.add(directionPoint);
}
}
});
asyncTask.startAsyncTask();
}
private void getMyLocation() {
if(myLocation == null) {
MGUtilities.showAlertView(
getActivity(),
R.string.location_error,
R.string.cannot_determine_location);
return;
}
addStoreMarkers();
CameraUpdate zoom = CameraUpdateFactory.zoomTo(Config.MAP_ZOOM_LEVEL);
googleMap.moveCamera(zoom);
CameraUpdate center = CameraUpdateFactory.newLatLng(
new LatLng(myLocation.getLatitude(), myLocation.getLongitude()));
googleMap.animateCamera(center);
}
private void getNearby() {
if(googleMap != null)
googleMap.clear();
if(myLocation == null) {
MGUtilities.showAlertView(
getActivity(),
R.string.route_error,
R.string.route_error_details);
return;
}
try {
MainActivity main = (MainActivity) this.getActivity();
Queries q = main.getQueries();
storeList = q.getStores();
markerList.clear();
markers.clear();
for(Store entry: storeList) {
Location destination = new Location("Origin");
destination.setLatitude(entry.getLat());
destination.setLongitude(entry.getLon());
double distance = myLocation.distanceTo(destination);
if(distance <= Config.MAX_RADIUS_NEARBY_IN_METERS) {
Marker mark = createMarker(entry);
markerList.add(mark);
markers.put(mark.getId(), entry);
}
}
CameraUpdate zoom = CameraUpdateFactory.zoomTo(Config.MAP_ZOOM_LEVEL);
googleMap.moveCamera(zoom);
CameraUpdate center = CameraUpdateFactory.newLatLng(
new LatLng(myLocation.getLatitude(), myLocation.getLongitude()));
googleMap.animateCamera(center);
}
catch(Exception e) {
e.printStackTrace();
}
}
private void showBoundedMap() {
if(markerList == null && markerList.size() == 0 ) {
MGUtilities.showNotifier(this.getActivity(), MainActivity.offsetY, R.string.failed_data);
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 {
MGUtilities.showNotifier(this.getActivity(), MainActivity.offsetY, R.string.no_results_found);
Location loc = MainActivity.location;
if(loc != null) {
googleMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(new LatLng(loc.getLatitude(), loc.getLongitude()), 70));
}
}
}
private Marker createMarker(Store store) {
final MarkerOptions markerOptions = new MarkerOptions();
Spanned name = Html.fromHtml(store.getStore_name());
name = Html.fromHtml(name.toString());
Spanned storeAddress = Html.fromHtml("R$ " + store.getHora() + " /hr");
storeAddress = Html.fromHtml(storeAddress.toString());
markerOptions.title( name.toString() );
String address = storeAddress.toString();
if(address.length() > 50)
address = storeAddress.toString().substring(0, 50) + "...";
markerOptions.snippet(address);
markerOptions.position(new LatLng(store.getLat(), store.getLon()));
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_pin_orange));
Marker mark = googleMap.addMarker(markerOptions);
mark.setInfoWindowAnchor(Config.MAP_INFO_WINDOW_X_OFFSET, 0);
Category cat = q.getCategoryByCategoryId(store.getCategory_id());
if(cat != null && cat.getCategory_icon() != null) {
MGHSquareImageView imgView = new MGHSquareImageView(getActivity());
imgView.setMarker(mark);
imgView.setMarkerOptions(markerOptions);
imgView.setTag(store);
MainActivity.getImageLoader().displayImage(
cat.getCategory_icon(), imgView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) { }
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) { }
#Override
public void onLoadingComplete(String imageUri, final View view, final Bitmap loadedImage) {
// TODO Auto-generated method stub
if(loadedImage != null) {
MGHSquareImageView v = (MGHSquareImageView)view;
Marker m = (Marker)v.getMarker();
m.remove();
MarkerOptions opt = (MarkerOptions)v.getMarkerOptions();
opt.icon(BitmapDescriptorFactory.fromBitmap(loadedImage));
Marker mark = googleMap.addMarker(opt);
Store s = (Store) v.getTag();
if(markers.containsKey(m.getId())) {
markerList.remove(m);
markerList.add(mark);
markers.remove(m);
markers.put(mark.getId(), s);
}
else {
markers.put(mark.getId(), s);
}
}
else {
Log.e("LOADED IMAGE", "IS NULL");
}
}
#Override
public void onLoadingCancelled(String imageUri, View view) { }
});
}
return mark;
}
public void getData() {
final MainActivity main = (MainActivity) getActivity();
main.showSwipeProgress();
task = new MGAsyncTask(getActivity());
task.setMGAsyncTaskListener(new OnMGAsyncTaskListener() {
#Override
public void onAsyncTaskProgressUpdate(MGAsyncTask asyncTask) { }
#Override
public void onAsyncTaskPreExecute(MGAsyncTask asyncTask) {
asyncTask.dialog.hide();
}
#Override
public void onAsyncTaskPostExecute(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
main.hideSwipeProgress();
new Handler().postDelayed(new Runnable() {
public void run() {
viewInflate.findViewById(R.id.imgViewRefresh4).setVisibility(View.GONE);
}
}, 0);
addStoreMarkers();
CameraUpdate zoom = CameraUpdateFactory.zoomTo(Config.MAP_ZOOM_LEVEL);
googleMap.moveCamera(zoom);
CameraUpdate center = CameraUpdateFactory.newLatLng(
new LatLng(myLocation.getLatitude(), myLocation.getLongitude()));
googleMap.animateCamera(center);
}
#Override
public void onAsyncTaskDoInBackground(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
parseData();
}
});
task.execute();
}
public void parseData() {
MainActivity main = (MainActivity) this.getActivity();
Queries q = main.getQueries();
DataParser parser = new DataParser();
Data data = parser.getData(Config.GET_STORES_JSON_URL);
if(data != null) {
if(data.getStores() != null && data.getStores().size() > 0) {
q.deleteTable("stores");
for(Store store : data.getStores()) {
q.insertStore(store);
}
}
if(data.getCategories() != null && data.getCategories().size() > 0) {
q.deleteTable("categories");
for(Category cat : data.getCategories()) {
q.insertCategory(cat);
}
}
if(data.getPhotos() != null && data.getPhotos().size() > 0) {
q.deleteTable("photos");
for(Photo photo : data.getPhotos()) {
q.insertPhoto(photo);
}
}
}
}
}
Check this documentation on how to customize the marker image.
You can replace the default marker image with a custom marker image, often called an icon. Custom icons are always set as a BitmapDescriptor, and defined using one of the methods in the BitmapDescriptorFactory class.
Here is a sample code on how to create a marker with a custom icon.
private static final LatLng MELBOURNE = new LatLng(-37.813, 144.962);
private Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne")
.snippet("Population: 4,137,400")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
NOTE:
getMap() is already deprecated, so use getMapAsync() in your code.
For more information, check these related SO question.
How to create a custom-shaped bitmap marker with Android map API v2
create custom marker icons on runtime using android xml
I'm creating an Android map app by getting venue from Foursquare and using Google Map.
I have set my MainActivity to get the venue results, a MapFragmentClass and a VenueModel.
I keep all the JSON result from Foursquare into a List venueModelList in the MainActivity.
What I want to do is to add markers in the MapFragmentClass based on the coordinates received from Foursquare.
However, I am stuck trying to pass the venueModelList to the MapFragmentClass.
Any help is appreciated. Thanks.
MainActivity.java
public class MainActivity extends AppCompatActivity implements LocationListener{
private final String VENUE_URL = "https://api.foursquare.com/v2/venues/search?ll=";
private final int LIMIT = 40;
private final double RADIUS = 50000;
private String MOSQUE_URL;
private String RES_URL;
public static final String CLIENT_ID = "";
public static final String CLIENT_SECRET = "";
private static final long MIN_TIME_BW_UPDATES = 20000;
private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 1;
private LocationManager locationManager;
private Location lastLocation;
private Location location;
private boolean receivedLocation = false;
private double lt;
private double lg;
private boolean canGetLocation;
private boolean isGPSEnabled;
private boolean isNetworkEnabled;
private boolean updateSettings = false;
private String TAG = "TAG";
private ListView lvVenues;
private Bundle bundle;
private ArrayList<VenueModel> venueModelList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvVenues = (ListView) findViewById(R.id.lvVenues);
String t = timeMilisToString(System.currentTimeMillis());
Bundle extras = getIntent().getExtras();
if (extras != null)
{
lt = extras.getDouble("LATITUDE");
lg = extras.getDouble("LONGITUDE");
receivedLocation = true;
}
else
{
receivedLocation = false;
}
location = getLocation();
if (location != null)
{
if(receivedLocation)
{
location.setLatitude(lt);
location.setLongitude(lg);
}
else
{
lt = location.getLatitude();
lg = location.getLongitude();
Log.d("LAT", "Latitude: " + lt);
Log.d("LONG", "Longitude: " + lg);
}
}
double lt = 3.142182;
double lg = 101.710602;
MOSQUE_URL = VENUE_URL + lt + "," + lg
+ "&client_id=" + CLIENT_ID
+ "&client_secret=" + CLIENT_SECRET
+ "&v=" + t
+ "&categoryId=4bf58dd8d48988d138941735"
+ "&radius=" + RADIUS
+ "&limit=" + LIMIT;
RES_URL = VENUE_URL + lt + "," + lg
+ "&client_id=" + CLIENT_ID
+ "&client_secret=" + CLIENT_SECRET
+ "&v=" + t
+ "&categoryId=52e81612bcbc57f1066b79ff"
+ "&radius=" + RADIUS
+ "&limit=" + LIMIT;
}
public class JSONTask extends AsyncTask<String, String, List<VenueModel>>
{
#Override
public List<VenueModel> doInBackground(String... params)
{
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONObject secondObject = parentObject.getJSONObject("response");
JSONArray parentArray = secondObject.getJSONArray("venues");
venueModelList = new ArrayList<>();
for (int i = 0; i < parentArray.length(); i++)
{
JSONObject finalObject = parentArray.getJSONObject(i);
JSONObject thirdObject = finalObject.getJSONObject("location");
try {
VenueModel venueModel = new VenueModel();
venueModel.setId(finalObject.getString("id"));
venueModel.setName(finalObject.getString("name"));
venueModel.setAddress(thirdObject.optString("address"));
venueModel.setPostalCode(thirdObject.optString("postalCode"));
venueModel.setCity(thirdObject.optString("city"));
venueModel.setState(thirdObject.optString("state"));
venueModel.setDistance(thirdObject.getInt("distance"));
venueModel.setLat(thirdObject.getDouble("lat"));
venueModel.setLng(thirdObject.getDouble("lng"));
LatLng coordinate = new LatLng(thirdObject.getDouble("lat"), thirdObject.getDouble("lng"));
venueModel.setCoordinate(coordinate);
venueModelList.add(venueModel);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Collections.sort(venueModelList);
return venueModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<VenueModel> result)
{
super.onPostExecute(result);
VenueAdapter adapter = new VenueAdapter(getApplicationContext(), R.layout.row, result);
lvVenues.setAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_mosque)
{
new JSONTask().execute(MOSQUE_URL);
FragmentManager fmanager = getSupportFragmentManager();
FragmentTransaction FT = fmanager.beginTransaction();
MapFragmentClass mfc = new MapFragmentClass();
FT.add(R.id.mapLayout, mfc);
FT.commit();
return true;
}
if (id == R.id.action_restaurant)
{
new JSONTask().execute(RES_URL);
FragmentManager fmanager = getSupportFragmentManager();
FragmentTransaction FT = fmanager.beginTransaction();
MapFragmentClass mfc = new MapFragmentClass();
FT.add(R.id.mapLayout, mfc);
FT.commit();
return true;
}
return super.onOptionsItemSelected(item);
}
private String timeMilisToString(long milis)
{
SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milis);
return sd.format(calendar.getTime());
}
public Location getLocation()
{
try
{
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
Log.v(TAG, "No network provider enabled");
}
else
{
this.canGetLocation = true;
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d(TAG, "Network Enabled");
if(locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d(TAG, "GPS Enabled");
if(locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return location;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onLocationChanged(Location location)
{
lastLocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider)
{
Log.v(TAG, "onProviderEnabled");
}
#Override
public void onProviderDisabled(String provider)
{
Log.v(TAG, "onProviderDisabled");
}
public LatLng setCoordinate()
{
LatLng coordinate = new LatLng(getLocation().getLatitude(), getLocation().getLongitude());
LatLng coordinate = new LatLng(lt, lg);
return coordinate;
}
}
VenueModel.java
public class VenueModel implements Comparable<VenueModel>, Parcelable
{
private String id;
private String name;
private String address;
private String postalCode;
private String city;
private String state;
private Integer distance;
private double lat;
private double lng;
private LatLng coordinate;
private List<VenueModel> venueModelList;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public void setVenueModelList(List<VenueModel> venueModelList)
{
this.venueModelList = venueModelList;
}
public List<VenueModel> getVenueModelList()
{
return venueModelList;
}
public LatLng getCoordinate() {
return coordinate;
}
public void setCoordinate(LatLng coordinate)
{
this.coordinate = coordinate;
}
#Override
public int compareTo(VenueModel venueModel) {
return this.distance.compareTo(venueModel.distance);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.id);
dest.writeString(this.name);
dest.writeString(this.address);
dest.writeString(this.postalCode);
dest.writeString(this.city);
dest.writeString(this.state);
dest.writeValue(this.distance);
dest.writeDouble(this.lat);
dest.writeDouble(this.lng);
dest.writeParcelable(this.coordinate, flags);
dest.writeList(this.venueModelList);
}
public VenueModel() {
}
protected VenueModel(Parcel in) {
this.id = in.readString();
this.name = in.readString();
this.address = in.readString();
this.postalCode = in.readString();
this.city = in.readString();
this.state = in.readString();
this.distance = (Integer) in.readValue(Integer.class.getClassLoader());
this.lat = in.readDouble();
this.lng = in.readDouble();
this.coordinate = in.readParcelable(LatLng.class.getClassLoader());
this.venueModelList = new ArrayList<VenueModel>();
in.readList(this.venueModelList, VenueModel.class.getClassLoader());
}
public static final Parcelable.Creator<VenueModel> CREATOR = new Parcelable.Creator<VenueModel>() {
#Override
public VenueModel createFromParcel(Parcel source) {
return new VenueModel(source);
}
#Override
public VenueModel[] newArray(int size) {
return new VenueModel[size];
}
};
}
MapFragmentClass.java
public class MapFragmentClass extends Fragment implements OnMapReadyCallback
{
private MainActivity mA;
private GoogleMap gmap;
private static final LatLng coordinate = new LatLng(3.152182, 101.710602);
private LatLng coordinate2;
private ArrayList<VenueModel> venueModelList;
#Override
public void onAttach(Context context)
{
super.onAttach(context);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.activity_maps, container, false);
SupportMapFragment supportMapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
return v;
}
#Override
public void onMapReady(GoogleMap googleMap)
{
gmap = googleMap;
gmap.addMarker(new MarkerOptions().position(coordinate).title("Your location").draggable(true));
gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 14));
}
}
Convert that Object to JSON string using GSON and then reconvert that string again to Object of list again.
MapFragment.getInstance(new Gson().toJson(venuList));
public static final getInstance(String venusStringListObj) {}
Bundle argument = new Bundle();
argument.putString("VENUES", venusStringListObj);
MapFragment fragment = new MapFragment();
fragment.setArgument(argument);
return fragment;
}
onCreate(...) {
private List<VenueModel> venueList;
Type listType = new TypeToken<ArrayList<VenueModel>>() {}.getType();
String venueStringRecvFromFragArg = getArguments().getString("VENUES");
venueList = new Gson().fromJson(venueStringRecvFromFragArg, listType);
}
MapFragmentClass mfc = new MapFragmentClass();
Bundle b = new Bundle();
b.putParcelableArrayList("Parcel", list);
mfc.setArguments(b);
FT.add(R.id.mapLayout, mfc);
FT.commit();
To access arrayList in MapFragment use this
ArrayList<VenueModel> myList = getArguments().getParcelableArrayList("Parcel");
I have literally been searching for this for weeks. I am a novice java programmer but I have been able to piece together an app that can use a double latitude and longitude hard coded in the same class. It will show a list of current places surrounding those points. I have another separate class with a method that is able to get the current location based on the gps/network but I can't pass the variables created from this second class to the PlaceRequest class. I have looked through all of the tutorials on the above subjects but there isn't anything combining current location and place search results. I have two getters declared but can't call the variables in these. Again sort of a rookie so may be an easy fix. Any ideas?
Update - Here is my code so far:
GooglePlaceActivity.java
public class GooglePlaceActivity extends Activity {
/** Called when the activity is first created. */
Button btn1;
TextView txt1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.main);
btn1 = (Button)findViewById(R.id.button1);
txt1 = (TextView)findViewById(R.id.textView1);
btn1.setOnClickListener(l);
}
private class SearchSrv extends AsyncTask<Void, Void, PlacesList>{
#Override
protected PlacesList doInBackground(Void... params) {
PlacesList pl = null;
try {
pl = new PlaceRequest().performSearch();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pl;
}
#Override
protected void onPostExecute(PlacesList result) {
String text = "Result \n";
if (result!=null){
for(Place place: result.results){
text = text + place.name +"\n";
}
txt1.setText(text);
}
setProgressBarIndeterminateVisibility(false);
}
}
View.OnClickListener l = new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SearchSrv srv = new SearchSrv();
setProgressBarIndeterminateVisibility(true);
srv.execute();
}
};
}
//////////////////////
PlaceRequest.java
public class PlaceRequest {
private static final HttpTransport transport = new ApacheHttpTransport();
private static final String API_KEY = "keyhere";
private static final String LOG_KEY = "GGPlace";
// The different Places API endpoints.
private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
private static final String PLACES_AUTOCOMPLETE_URL = "https://maps.googleapis.com/maps/api/place/autocomplete/json?";
private static final String PLACES_DETAILS_URL = "https://maps.googleapis.com/maps/api/place/details/json?";
private static final boolean PRINT_AS_STRING = true;
//double latitude;
//double longitude;
CurrentLocation clo = new CurrentLocation(null);
//clo.onLocationChanged(latitude);
//double longitude = CurrentLocation.getLongitude();
//double latitude = CurrentLocation.getLatitude();
double longi = clo.getLongitude();
double lat = clo.getLatitude();
public PlacesList performSearch() throws Exception {
try {
//CurrentLocation currlo = new CurrentLocation();
//double lat = currlo.getLatitude();
//double longi = currlo.getLongitude();
Log.v(LOG_KEY, "Start Search");
GenericUrl reqUrl = new GenericUrl(PLACES_SEARCH_URL);
reqUrl.put("key", API_KEY);
//reqUrl.put("location", latitude + "," + longitude);
//reqUrl.put("location", getLatitude(latitude) + "," + getLongitude());
reqUrl.put("location", lat + "," + longi);
reqUrl.put("radius", 1600);
reqUrl.put("types", "food");
reqUrl.put("sensor", "false");
Log.v(LOG_KEY, "url= " + reqUrl);
HttpRequestFactory httpRequestFactory = createRequestFactory(transport);
HttpRequest request = httpRequestFactory.buildGetRequest(reqUrl);
Log.v(LOG_KEY, request.execute().parseAsString());
PlacesList places = request.execute().parseAs(PlacesList.class);
Log.v(LOG_KEY, "STATUS = " + places.status);
for (Place place : places.results) {
Log.v(LOG_KEY, place.name);
}
return places;
} catch (HttpResponseException e) {
Log.v(LOG_KEY, e.getResponse().parseAsString());
throw e;
}
catch (IOException e) {
// TODO: handle exception
throw e;
}
}
public static HttpRequestFactory createRequestFactory(final HttpTransport transport) {
return transport.createRequestFactory(new HttpRequestInitializer() {
public void initialize(HttpRequest request) {
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("Google-Places-DemoApp");
request.setHeaders(headers);
JsonHttpParser parser = new JsonHttpParser(new JacksonFactory()) ;
//JsonHttpParser.builder(new JacksonFactory());
//parser.jsonFactory = new JacksonFactory();
request.addParser(parser);
}
});
}
}
/////////////
CurrentLocation.java
public class CurrentLocation {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
LocationManager locationManager ;
double latitude=0;
double longitude=0;
public CurrentLocation(Context ctxt) {
super();
locationManager = (LocationManager) ctxt.getSystemService(Context.LOCATION_SERVICE);
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
});
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
}
Edit: After looking your complete code, I see a few fundamental design flaws so I'm going to show you how I did it and you can adapt it to your program flow. Please keep in mind that this example is vastly simplified from my original, but it should be enough to get you going.
First, the CurrentLocation.java file. My design decision for wrapping this in a Future was so that I can re-use it in multiple activities with the added bonus of killing it when necessary.
public class CurrentLocation implements Callable<Location> {
private static final String TAG = "CurrentLocation";
private Context context;
private LocationManager lm;
private Criteria criteria;
private Location bestResult;
private boolean locationListenerWorking;
public CurrentLocation(Context context) {
lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
this.context = context;
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
bestResult = null;
locationListenerWorking = false;
}
public Location call() {
return getLoc();
}
private Location getLoc() {
String provider = lm.getBestProvider(criteria, true);
if (provider != null) {
Log.d(TAG, "Using provider: " +provider);
locationListenerWorking = true;
lm.requestLocationUpdates(provider,
0,
0,
singeUpdateListener,
context.getMainLooper());
} else {
Log.w(TAG, "Couldn't find a location provider");
return null;
}
while (locationListenerWorking) {
// Check for the interrupt signal - terminate if necessary
if (Thread.currentThread().isInterrupted()) {
Log.i(TAG, "User initiated interrupt (cancel signal)");
cleanup();
break;
}
try {
// ghetto implementation of a busy wait...
Thread.sleep(500); // Sleep for half a second
} catch (Exception e) {
Log.d(TAG, "Thread interrupted..");
cleanup();
break;
}
}
return bestResult;
}
private void cleanup() {
if (lm != null) {
Log.d(TAG, "Location manager not null - cleaning up");
lm.removeUpdates(singeUpdateListener);
} else {
Log.d(TAG, "Location manager was NULL - no cleanup necessary");
}
}
/**
* This one-off {#link LocationListener} simply listens for a single location
* update before unregistering itself. The one-off location update is
* returned via the {#link LocationListener} specified in {#link
* setChangedLocationListener}.
*/
private LocationListener singeUpdateListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.d(TAG, "Got a location update");
if (location == null) {
Log.d(TAG, "Seems as if we got a null location");
} else {
bestResult = location;
}
cleanup();
locationListenerWorking = false;
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
}
Then in your calling class (i.e. where you need the lat/lon coordinates - you want to do this from an Activity):
private class GetLocationTask extends AsyncTask <Void, Void, Location> {
private Future<Location> future;
private ExecutorService executor = new ScheduledThreadPoolExecutor(5);
private boolean cancelTriggered = false;
protected void onPreExecute() {
Log.d(TAG, "Starting location get...");
}
public Location doInBackground(Void... arg) {
CurrentLocation currLoc = new CurrentLocation(getApplicationContext());
future = executor.submit(currLoc);
long LOCATION_TIMEOUT = 20000; // ms = 20 sec
try {
// return future.get(Constants.LOCATION_TIMEOUT, TimeUnit.MILLISECONDS);
return future.get(LOCATION_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (Exception e) {
Log.w(TAG, "Location get timed out");
future.cancel(true);
return null;
}
}
public boolean killTask() {
cancelTriggered = true;
boolean futureCancelRes = future.cancel(true);
this.cancel(true);
Log.d(TAG, "Result of cancelling task: " +futureCancelRes);
return futureCancelRes;
}
protected void onPostExecute(Location res) {
if (cancelTriggered) {
Log.d(TAG, "User initiated cancel - this is okay");
cancelTriggered = false;
} else if (res == null) {
Log.d(TAG, "Could not get a location result");
} else {
double lat = res.getLatitude();
double lon = res.getLongitude();
Log.d(TAG, "Latitude: " +lat);
Log.d(TAG, "Longitude: " +lon);
}
}
}
Finally to wrap things up, here's how you call it:
GetLocationTask t = new GetLocationTask();
t.execute();
And if you need to kill the location update for whatever reason (if your user switches out of your activity, etc), this will kill the AsyncTask as well as the associated Future task.
t.killTask();
P.S. You may want to get your API keys changed and edit it out of your post.