I am trying to get current location with LocationClient.getLastLocation(). First, I call connect() for LocationClient in onCreate() but it gave me this error:
11-11 13:20:45.297: E/AndroidRuntime(9188): Caused by: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
Then I call connect() for LocationClient inside onStart(). It gives me NullPointerException.
This code was working fine in an activity when I call connect() of LocationClient in onCreate(). However, it's not working in fragment. Where should I call connect() for LocationClient?
ClosestFragment.java:
public class ClosestFragment extends Fragment implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
private GoogleMap map;
JSONArray jsonArray;
JSONObject jsonObject, jsonObjResult;
String json = "";
ProgressDialog progress;
Location mCurrentLocation;
LocationClient mLocationClient;
SharedPreferences sp;
Double latitude = 0.0;
Double longitude = 0.0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get back arguments
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Defines the xml file for the fragment
View view = inflater.inflate(R.layout.closest_fragment, container, false);
return view;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getActivity()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public static ClosestFragment newInstance() {
ClosestFragment fragment = new ClosestFragment();
return fragment;
}
#Override
public void onStart() {
super.onStart();
// Connect the location client to start receiving updates
mLocationClient = new LocationClient(getActivity(), this, this);
mLocationClient.connect();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getChildFragmentManager();
fm.beginTransaction()
.replace(R.id.map, SupportMapFragment.newInstance()).commit();
new GetClosestKiosks().execute();
}
private class GetClosestKiosks extends AsyncTask<Void, Void, Void> {
String message="";
ArrayList<KioskInfo> kioskList = new ArrayList<KioskInfo>();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
Location mCurrentLocation = mLocationClient.getLastLocation();
if (mCurrentLocation != null) {
latitude = mCurrentLocation.getLatitude();
Log.e("ASD", "" + latitude);
longitude = mCurrentLocation.getLongitude();
Log.e("ASD", "" + longitude);
} else {
sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
String lat = sp.getString("lat", "0");
String lon = sp.getString("lon", "0");
latitude = Double.parseDouble(lat);
longitude = Double.parseDouble(lon);
}
return null;
}
#Override
protected void onPostExecute(Void args) {
}
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
mCurrentLocation = mLocationClient.getLastLocation();
if (mCurrentLocation != null) {
latitude = mCurrentLocation.getLatitude();
longitude = mCurrentLocation.getLongitude();
String msg = "Updated Location: "
+ Double.toString(mCurrentLocation.getLatitude()) + ","
+ Double.toString(mCurrentLocation.getLongitude());
// Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
Log.d("DEBUG", "current location: " + mCurrentLocation.toString());
} else {
String lat = sp.getString("lat", "");
String lon = sp.getString("lon", "");
latitude = Double.parseDouble(lat);
longitude = Double.parseDouble(lon);
}
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
}
closest_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="20" >
<FrameLayout
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="10" >
</FrameLayout>
<ListView
android:id="#+id/kiosklist"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="10" >
</ListView>
</LinearLayout>
It is possible that the doInBackground() method of GetClosestKiosks is called before the LocationClient is actually connected.
So you should call your new GetClosestKiosks().execute() in a appropriate place. So you might call it inside the public void onConnected(Bundle arg0) method.
In addition, you might want to do mLocationClient.requestLocationUpdates() inside the doInBackground() method to get the more recent location.
Related
So, basically i was trying to put a button on top of my map fragment but it doesn't seems to work despite the map working completely fine. Even after extensively searching Google, I couldn't find an executable answer.
Here's my map fragment-
public class Tab1 extends SupportMapFragment implements
GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks,
GoogleMap.OnInfoWindowClickListener, OnMapReadyCallback,
ClusterManager.OnClusterClickListener<MyItem>,
ClusterManager.OnClusterInfoWindowClickListener<MyItem>,
ClusterManager.OnClusterItemClickListener<MyItem> {
InputStream inputstream;
BufferedReader reader;
String title;
GoogleMap map;
AutoCompleteTextView actv;
Map<String, String> moviemap;
List<MyItem> items = new ArrayList<MyItem>();
String subtitle;
String floor;
String type;
Double lat;
Double lng;
int len;
int arraylength;
ClusterManager<MyItem> mClusterManager;
List<Map<String, String>> moviedata;
JSONArray jsonArray;
JSONObject jsonObject;
String m;
private GoogleApiClient mGoogleApiClient;
private Location mCurrentLocation;
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mClusterManager = new ClusterManager<MyItem>(getActivity(), getMap());
getMap().setOnCameraChangeListener(mClusterManager);
getMap().setOnMarkerClickListener(mClusterManager);
mClusterManager
.setOnClusterClickListener(new ClusterManager.OnClusterClickListener<MyItem>() {
#Override
public boolean onClusterClick(final Cluster<MyItem> cluster) {
getMap().animateCamera(CameraUpdateFactory.newLatLngZoom(
cluster.getPosition(), (float) Math.floor(getMap()
.getCameraPosition().zoom + 2)), 300,
null);
return true;
}
});
try {
inputstream = getResources().getAssets().open("map.json");
reader = new BufferedReader(new InputStreamReader(inputstream));
m = reader.toString();
StringBuilder total = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
total.append(line);
}
m = total.toString();
} catch (IOException ex) {
Toast.makeText(getActivity(), "fail", Toast.LENGTH_SHORT).show();
}
moviedata = new ArrayList<Map<String, String>>();
try {
jsonObject = new JSONObject(m);
jsonArray = jsonObject.optJSONArray("map");
arraylength = jsonArray.length();
len = arraylength;
for (int i = 0; i < arraylength; i++) {
moviemap = new HashMap<>();
JSONObject jsonChildNode = jsonArray.getJSONObject(i);
title = jsonChildNode.optString("title");
subtitle = jsonChildNode.optString("subtitle");
floor = jsonChildNode.optString("floor");
type = jsonChildNode.optString("type");
lat = jsonChildNode.optDouble("latitude");
lng = jsonChildNode.optDouble("longitude");
moviemap.put("A", title);
moviemap.put("B", subtitle);
moviemap.put("C", floor);
moviemap.put("D", type);
moviemap.put("E", lat.toString());
moviemap.put("F", lng.toString());
moviedata.add(moviemap);
Double lat1 = Double.parseDouble(moviedata.get(i).get("E"));
Double lng1 = Double.parseDouble(moviedata.get(i).get("F"));
items.add(new MyItem(lat1, lng1, moviedata.get(i).get("A"), moviedata.get(i).get("B")));
}
mClusterManager.addItems(items);
mClusterManager.setRenderer(new MyClusterRenderer(getActivity(), getMap(), mClusterManager));
} catch (JSONException e) {
e.printStackTrace();
}
initListeners();
}
private void initListeners() {
getMap().setOnInfoWindowClickListener(this);
}
private void removeListeners() {
if (getMap() != null) {
getMap().setOnInfoWindowClickListener(null);
}
}
#Override
public void onDestroy() {
super.onDestroy();
removeListeners();
}
private void initCamera(Location location) {
CameraPosition position = CameraPosition.builder()
.target(new LatLng(28.75007207311156, 77.11772996932268))
.zoom(18f)
.bearing(0.0f)
.tilt(40f)
.build();
getMap().animateCamera(CameraUpdateFactory.newCameraPosition(position), null);
getMap().setMapType(GoogleMap.MAP_TYPE_NORMAL);
getMap().setTrafficEnabled(true);
getMap().setMyLocationEnabled(true);
getMap().getUiSettings().setZoomControlsEnabled(true);
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
initCamera(mCurrentLocation);
}
#Override
public void onConnectionSuspended(int i) {
//handle play services disconnecting if location is being constantly used
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
//Create a default location if the Google API Client fails. Placing location at Googleplex
mCurrentLocation = new Location("");
mCurrentLocation.setLatitude(28.7499);
mCurrentLocation.setLongitude(77.1170);
initCamera(mCurrentLocation);
}
#Override
public void onInfoWindowClick(Marker marker) {
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
}
#Override
public boolean onClusterClick(Cluster<MyItem> cluster) {
return false;
}
#Override
public void onClusterInfoWindowClick(Cluster<MyItem> cluster) {
}
#Override
public boolean onClusterItemClick(MyItem myItem) {
return false;
}
}
Here's my xml-
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button2"
android:layout_gravity="center" />
</FrameLayout>
use FrameLayout instead of RelativeLayout just like below.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button2"
android:layout_gravity="left|top" />
</FrameLayout>
I am doing a project where the title and descriptions have to be displayed. But the issue is the text in the description is little lengthy which is not shown when we click on the marker. I want to size of the snippet to show the full description else need some other option?
#SuppressLint("NewApi") public class GoogleActivity extends
FragmentActivity implements LocationListener {
private LocationManager locationManager; private static final long
MIN_TIME = 700; private static final float MIN_DISTANCE = 800;
// Google Map private GoogleMap googleMap; LatLng myPosition;
// All static variables static final String URL =
"http://webersspot.accountsupport.com/gmaptrial/onedb/phpsqlajax_genxml.php";
// XML node keys
static final String KEY_PID = "pro"; // parent node static final
String KEY_NAME = "Name"; static final String KEY_DESCRIPTION =
"Description"; static final String KEY_LAT = "Latitude"; static
final String KEY_LONG = "Longitude";
ArrayList<HashMap<String, String storeMapData = new
ArrayList<HashMap<String, String (); private ShareActionProvider
mShareActionProvider;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = mapFragment.getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); // Hybrid for
satellite with place name
googleMap.setMyLocationEnabled(true); // enable user location
button. googleMap.setInfoWindowAdapter(null) ;
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setAllGesturesEnabled(true);
googleMap.setTrafficEnabled(true); // enable road
/*
// 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();
} */
new LongOperation().execute(""); new
MapOperation().execute(googleMap);
locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME, MIN_DISTANCE, this); //You can also use
LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER
}
public List<HashMap<String, String prepareData(){
ArrayList<HashMap<String, String menuItems = new
ArrayList<HashMap<String, String (); //List<HashMap<String,
String menuItems = new ArrayList<HashMap<String, String ();
XmlParser parser = new XmlParser(); String xml =
parser.getXmlFromUrl(URL); // getting XML Document doc =
parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_PID); // looping
through all item nodes <item for (int i = 0; i < nl.getLength();
i++) { // creating new HashMap HashMap<String, String map = new
HashMap<String, String (); Element e = (Element) nl.item(i);
System.out.println("OOOOOOOOOOOOOOOOOOO :::
"+e.getAttribute(KEY_NAME)); // adding each child node to HashMap
key = value
map.put(KEY_NAME, e.getAttribute(KEY_NAME).toString());
map.put(KEY_DESCRIPTION
,e.getAttribute(KEY_DESCRIPTION).toString()); map.put(KEY_LAT,
e.getAttribute(KEY_LAT).toString()); map.put(KEY_LONG
,e.getAttribute(KEY_LONG).toString());
// adding HashList to ArrayList menuItems.add(map);
storeMapData = menuItems;
} return menuItems;
}
public void onMapReady(final GoogleMap map) {
ArrayList<HashMap<String, String processData = storeMapData;
System.out.println( "kjkasdc "+processData);
for (int i=0; i< processData.size(); i++){
final double lat =
Double.parseDouble(processData.get(i).get(KEY_LAT));
System.out.println("MAP LAT ::::::::::::::::::::::::: "+lat);
final double lon =
Double.parseDouble(processData.get(i).get(KEY_LONG));
System.out.println("MAP LON ::::::::::::::::::::::::: "+lon);
final String address = processData.get(i).get(KEY_DESCRIPTION);
System.out.println("MAP ADDRESS :::::::::::::::::::::::::
"+address); final String name = processData.get(i).get(KEY_NAME);
System.out.println("MAP ADDRESS ::::::::::::::::::::::::: "+name);
runOnUiThread(new Runnable() {
#Override
public void run() {
final LatLng MELBOURNE = new LatLng(lat, lon);
Marker melbourne = map.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title(name)
.snippet(address)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
melbourne.showInfoWindow();
// map.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title(name).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
} });
} }
#SuppressLint("NewApi") #Override public boolean
onCreateOptionsMenu(Menu menu) {
/** Inflating the current activity's menu with res/menu/items.xml */
getMenuInflater().inflate(R.menu.share_menu, menu);
mShareActionProvider = (ShareActionProvider)
menu.findItem(R.id.menu_item_share).getActionProvider();
/** Setting a share intent */
mShareActionProvider.setShareIntent(getDefaultShareIntent());
return super.onCreateOptionsMenu(menu);
}
/** Returns a share intent */ private Intent
getDefaultShareIntent(){ Intent intent = new
Intent(Intent.ACTION_SEND); intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT,"Download");
intent.putExtra(Intent.EXTRA_TEXT,"Download Hill Top Beauty Parlour
App - Maroli from Google Play Store:
https://play.google.com/store/apps/details?id=beauty.parlour.maroli");
return intent; }
private class LongOperation extends AsyncTask<String, Void, String {
#Override protected String doInBackground(String... params) {
prepareData(); return "Executed"; } #Override protected void onPostExecute(String result) {
System.out.println("Executed"); } #Override protected void
onPreExecute() { System.out.println("Execution started");
} #Override protected void onProgressUpdate(Void... values) {
System.out.println(" -- -- -- "+values); } }
private class MapOperation extends AsyncTask<GoogleMap, Void, String
{ #Override protected String doInBackground(GoogleMap... params) {
GoogleMap map = params[0]; onMapReady(map); return
"Executed"; } #Override protected void onPostExecute(String
result) { System.out.println(result); } #Override
protected void onPreExecute() {
System.out.println("Execution started"); } #Override
protected void onProgressUpdate(Void... values) {
System.out.println(" -- -- -- "+values); } }
class MyInfoWindowAdapter implements InfoWindowAdapter{
private final View myContentsView;
MyInfoWindowAdapter(){ myContentsView =
getLayoutInflater().inflate(R.layout.custom_info_contents, null); }
#Override public View getInfoContents(Marker marker) {
TextView tvTitle =
((TextView)myContentsView.findViewById(R.id.title));
tvTitle.setText(marker.getTitle()); TextView tvSnippet =
((TextView)myContentsView.findViewById(R.id.snippet));
tvSnippet.setText(marker.getSnippet());
return myContentsView; }
#Override public View getInfoWindow(Marker marker) { // TODO
Auto-generated method stub return null;
}
}
#Override public void onLocationChanged(Location location) { //
TODO Auto-generated method stub LatLng latLng = new
LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate =
CameraUpdateFactory.newLatLngZoom(latLng, 10);
googleMap.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
#Override public void onStatusChanged(String provider, int status,
Bundle extras) { // TODO Auto-generated method stub
}
#Override public void onProviderEnabled(String provider) { // TODO
Auto-generated method stub
}
#Override public void onProviderDisabled(String provider) { //
TODO Auto-generated method stub
}
}
<?xml version="1.0" encoding="utf-8"?>
<Relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="300dp"
android:layout_gravity="center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textStyle="bold" />
<TextView
android:id="#+id/snippet"
android:marqueeRepeatLimit="5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10sp" />
</Relativelayout>
You can add custom popup instead of snippet, something like this,
private void showPopup(final Activity context, String address) {
LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.pop_up_layout, viewGroup);
TextView textView = (TextView) layout.findViewById(R.id.txt_address);
textView.setText(address);
// Creating the PopupWindow
final PopupWindow popup = new PopupWindow(context);
popup.setContentView(layout);
popup.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
popup.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
popup.setFocusable(true);
// Clear the default translucent background
popup.setBackgroundDrawable(new BitmapDrawable());
// Displaying the popup at the specified location, + offsets.
popup.showAtLocation(layout, Gravity.NO_GRAVITY, mPoint.x, mPoint.y + 50 );
}
for demonstration install and check here
I am trying to get the current location of the user from an asynctask. My application depends on the latitude and longitude values. I am trying to show a ProgressDialog to the user till the location is fetched.
Problem :- The location value is always null. I know that getting gps location takes time. But my location value is null even after waiting for sometimes. Its always null.
Below is my code :-
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//some action …
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (id == R.id.action_settings)
{
return true;
}
if(id == R.id.action_location)
{
LocationTask locGetter = new LocationTask(MainActivity.this);
locGetter.execute();
}
return super.onOptionsItemSelected(item);
}
}
Below is my AsyncTask
public class LocationTask extends AsyncTask<Void,Void,Void> implements LocationListener
{
private ProgressDialog dialog;
private Activity callingActivity;
LocationManager locationManager;
String provider = LocationManager.GPS_PROVIDER;
public LocationTask(Activity activity)
{
callingActivity = activity;
}
#Override
protected void onPreExecute()
{
dialog= ProgressDialog.show(callingActivity,"Getting Co-ordinates","Please Wait....");
}
#Override
protected Void doInBackground(Void... voids)
{
locationManager = (LocationManager) callingActivity.getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(provider);
showLocation(location);
return null;
}
private void showLocation(Location location)
{
if(location == null)
{
Log.d("Location","Failed to get location");
}
else
{
Log.d("Location","Latitude :- "+location.getLatitude()+" Longitude :- "+location.getLongitude());
}
}
#Override
protected void onPostExecute(Void aVoid)
{
dialog.dismiss();
super.onPostExecute(aVoid);
}
#Override
public void onLocationChanged(Location location)
{
showLocation(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
UPDATE :-
As mentioned by Ivan I have modified my AsyncTask to get location as below :-
#Override
protected Void doInBackground(Void... voids) {
locationManager = (LocationManager) callingActivity.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(provider,0,0,this);
if(locationManager != null) {
Location location = locationManager.getLastKnownLocation(provider);
showLocation(location);
}
return null;
}
But this throws "windows leaked" exception in the dialog= ProgressDialog.show(callingActivity,"Getting Co-ordinates","Please Wait...."); inside onPrexecute() method.
Seems to me that you might be missing the requestLocationUpdates(...) call.
Please check this related question for a better understanding on what might be missing, as it sure doesn't look to be a problem with it being inside an AsyncTask, although I don't really see the need for the AsyncTask in your snippet.
Have you tried using String locationProvider = LocationManager.NETWORK_PROVIDER;
to determine if it's the provider that's the issue?
Ivan has mentioned that you won't get updates, but as I understand you're still just looking for the last known location.
I'm creating a MapFragment in android; maps is showing just fine (although it takes 10 seconds to open), but no marker is shown.
This is the code of the fragment:
public class VehiclesMapFragment extends MapFragment implements OnMapReadyCallback {
GoogleMap _map;
private void setUpMapIfNeeded() {
if (_map == null) {
_map = this.getMap();
//_map = this.getMap();
//if (_map != null) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
ReDrawList(_vehicles);
}
}, 2000);
//}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
_map = googleMap;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
ReDrawList(_vehicles);
}
}, 10000);
}
public VehiclesMapFragment() {
}
VehiclesPosition[] _vehicles = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_vehicles = (VehiclesPosition[])getArguments().getSerializable("VEHICLES");
//setUpMapIfNeeded();
}
public void ReDrawList(VehiclesPosition[] vehicles)
{
if (vehicles != null && vehicles.length > 0 && _map != null) {
LatLngBounds bounds = null;
for (VehiclesPosition vp : vehicles) {
LatLng latlngPos = vp.GetMapLatLng();
if (bounds == null)
bounds = new LatLngBounds(latlngPos, latlngPos);
else
bounds = bounds.including(latlngPos);
MarkerOptions mi = vp.GetMapMarker();
Marker mm = _map.addMarker(mi);
mm.showInfoWindow();
}
try{
_map.animateCamera(CameraUpdateFactory.zoomTo(12));
_map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds,100));
}catch (Exception exx) {
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.fragment_vehicles_map, container, false);
setUpMapIfNeeded();
return v;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
//setUpMapIfNeeded();
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onResume() {
super.onResume();
}
private OnFragmentInteractionListener mListener;
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(Uri uri);
}
}
and this is the layout file:
<fragment 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"
android:id="#+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
and the fragment is instantiated by an activity, with:
Bundle args = new Bundle();
args.putSerializable("VEHICLES",_VehiclesList);
fragment_units_map = new VehiclesMapFragment();
_fragment_units_map.setArguments(args);
calling _map.animateCamera produce an exception at every call:
java.lang.IllegalStateException: Error using newLatLngBounds(LatLngBounds, int): Map size can't be 0. Most likely, layout has not yet occured for the map view. Either wait until layout has occurred or use newLatLngBounds(LatLngBounds, int, int, int) which allows you to specify the map's dimensions.
I'm working with Google Maps. I am able to successfully create and can show a Google Map. Now I want to add CameraUpdate(latitude, longitude). I googled and I found some source code but I'm getting a NullPointerException.
The LogCat error message is:
java.lang.NullPointerException: CameraUpdateFactory is not initialized
This is my source. What am I doing wrong?
public class StradaContact extends Fragment {
public final static String TAG = StradaContact.class.getSimpleName();
private MapView mMapView;
private GoogleMap mMap;
private Bundle mBundle;
double longitude = 44.79299800000001, latitude = 41.709981;
public StradaContact() {
}
public static StradaContact newInstance() {
return new StradaContact();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_contact, container,false);
mMapView = (MapView) rootView.findViewById(R.id.pointMap);
mMapView.onCreate(mBundle);
setUpMapIfNeeded(rootView);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.pointMap)).getMap();
if (mMap != null) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(latitude, longitude));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
}
<com.google.android.gms.maps.MapView
android:id="#+id/pointMap"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
Try this in "onCreate":
try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
Try with following method initialize google map api before using
MapsInitializer.initialize(getActivity());