Loading Map crashes on few devices - android

I have a listview and onItemSelected, will call an Activity to get user location (his current lat and lng), this activity has no layout, then this activity automatically calls another activity which gets lat and lng of the item selected from the listview and marks both the user location and item location on the map.
This worked fine when I was testing on Emulator and Samsung Galaxy Ace, But it crashes when I'm testing on Micromax A50 and Sony Xperia.
Sad thing is that I can't install drivers of the later 2 devices, so I cant get logcat.
Can any 1 guess what might have gone wrong??
My code for finding user location is:
public class MyLocationActivity extends Activity implements LocationListener {
private LocationManager mgr;
private String best;
public static double myLocationLatitude;
public static double myLocationLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
dumpProviders();
Criteria criteria = new Criteria();
best = mgr.getBestProvider(criteria, true);
Log.d("best provider", best);
Location location = mgr.getLastKnownLocation(best);
dumpLocation(location);
/*Intent intent = new Intent(MyLocationActivity.this, ShowMapActivity.class);
startActivity(intent);*/
Intent intent = new Intent(MyLocationActivity.this, MapMarkerActivity.class);
startActivity(intent);
finish();
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
dumpLocation(location);
}
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
}
#Override
protected void onPause() {
super.onPause();
mgr.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
mgr.requestLocationUpdates(best, 15000, 1, this);
}
private void dumpLocation(Location l) {
if (l == null) {
myLocationLatitude = 0.0;
myLocationLongitude = 0.0;
} else {
myLocationLatitude = l.getLatitude();
myLocationLongitude = l.getLongitude();
}
}
private void dumpProviders() {
List<String> providers = mgr.getAllProviders();
for (String p : providers) {
dumpProviders(p);
}
}
private void dumpProviders(String s) {
LocationProvider info = mgr.getProvider(s);
StringBuilder builder = new StringBuilder();
builder.append("name: ").append(info.getName());
}
}
and item location is:
public class MapMarkerActivity extends MapActivity {
private MapView map = null;
private MyLocationOverlay me = null;
private Drawable marker1;
private Drawable marker2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.particular_entry);
Button feedButton = (Button) findViewById(R.id.feedButton_particularEntry);
feedButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(MapMarkerActivity.this,
FeedListViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
});
Button iWantButton = (Button) findViewById(R.id.iWantButton_particularEntry);
iWantButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MapMarkerActivity.this,
IWantActivity.class);
startActivity(intent);
}
});
Button shareButton = (Button) findViewById(R.id.shareButton_particularEntry);
shareButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MapMarkerActivity.this,
ShareActivity.class);
startActivity(intent);
}
});
Button profileButton = (Button) findViewById(R.id.profileButton_particularEntry);
profileButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MapMarkerActivity.this,
ProfileActivity.class);
startActivity(intent);
}
});
map = (MapView) findViewById(R.id.map);
map.getController().setCenter(
getPoint(FeedListViewActivity.lat, FeedListViewActivity.lng));
map.getController().setZoom(13);
map.setBuiltInZoomControls(true);
marker1 = getResources().getDrawable(R.drawable.marker2);
marker2 = getResources().getDrawable(R.drawable.marker1);
marker1.setBounds(0, 0, marker1.getIntrinsicWidth(),
marker1.getIntrinsicHeight());
marker2.setBounds(0, 0, marker1.getIntrinsicWidth(),
marker1.getIntrinsicHeight());
map.getOverlays().add(new SitesOverlay(marker1));
me = new MyLocationOverlay(this, map);
map.getOverlays().add(me);
}
#Override
public void onResume() {
super.onResume();
me.enableCompass();
}
#Override
public void onPause() {
super.onPause();
me.disableCompass();
}
#Override
protected boolean isRouteDisplayed() {
return (false);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_S) {
map.setSatellite(!map.isSatellite());
return (true);
} else if (keyCode == KeyEvent.KEYCODE_Z) {
map.displayZoomControls(true);
return (true);
}
return (super.onKeyDown(keyCode, event));
}
private GeoPoint getPoint(double lat, double lon) {
return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
}
public class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items = new ArrayList<OverlayItem>();
public SitesOverlay(Drawable marker) {
super(marker);
boundCenterBottom(marker);
OverlayItem oli1 = new OverlayItem(getPoint(
MyLocationActivity.myLocationLatitude,
MyLocationActivity.myLocationLongitude), "YL",
"Your Location");
oli1.setMarker(marker2);
items.add(oli1);
OverlayItem oli2 = new OverlayItem(getPoint(
FeedListViewActivity.lat, FeedListViewActivity.lng), "SL",
"Store Location");
oli2.setMarker(marker1);
items.add(oli2);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return (items.get(i));
}
#Override
protected boolean onTap(int i) {
Toast.makeText(MapMarkerActivity.this, items.get(i).getSnippet(),
Toast.LENGTH_SHORT).show();
return (true);
}
#Override
public int size() {
return (items.size());
}
}
}

Maybe this can help you:
Location Method Calls Crashes On Some Devices

Related

How to use a constructer of java class into fragment?

[![enter image description here][1]][1]HI all I am having a problem can anyone tell me how do I resolve this , I want to use a constructer in fragment class:
here is my both classes
AppLocationService:
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
here is fragment:
public class AddressFragment extends Fragment {
Button ShowAddress;
TextView tvAddress;
AppLocationService appLocationService;
public AddressFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_address, container, false);
tvAddress = (TextView) rootView.findViewById(R.id.input_location);
appLocationService = new AppLocationService(
AddressFragment.this);
ShowAddress = (Button) rootView.findViewById(R.id.btn_location);
ShowAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Location location = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
//you can hard-code the lat & long if you have issues with getting it
//remove the below if-condition and use the following couple of lines
//double latitude = 37.422005;
//double longitude = -122.084095
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LocationAddress locationAddress = new LocationAddress();
locationAddress.getAddressFromLocation(latitude, longitude,
getApplicationContext(), new GeocoderHandler());
} else {
showSettingsAlert();
}
}
});
return rootView;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
AddressFragment.this);
alertDialog.setTitle("SETTINGS");
alertDialog.setMessage("Enable Location Provider! Go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
AddressFragment.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
String locationAddress;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationAddress = bundle.getString("address");
break;
default:
locationAddress = null;
}
tvAddress.setText(locationAddress);
}
}
// Inflate the layout for this fragment
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
To answer your question; A Fragment does not derive from Context. To let your code compile, you should change this
appLocationService = new AppLocationService(
AddressFragment.this);
To this
appLocationService = new AppLocationService(getActivity());
However, you should never call a constructor of a Service yourself. You should start it with Context#startService(Intent) (in your case getActivity().startService(new Intent(getActivity(), AppLocationService.class)). To supply any parameters for your service, take a look at Intent#putExtra(String, String)

Not working plot multiple marker getOverlay().add(classobject) not accept

This is my code i want to plot multiple marker in google map
when i write mapview.getoverlay().add(overlaymarker) it is not working
i am not use MapActivity i use fragment so this is not supported getoverlays() please help me.......
fragmnt1.java
public class one extends Fragment implements LocationListener {
MapView mapView;
GoogleMap googleMap;
private boolean mapsSupported = true;
Location location;
double latitude; // latitude
double longitude;
LatLng latlang;
LocationManager manager;
Overlay_Marker overmarker;
frag provider;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final RelativeLayout parent = (RelativeLayout) inflater.inflate(R.layout.one, container, false);
mapView = (MapView) parent.findViewById(R.id.map);
provider=new frag(getActivity());
Log.d("spn", "oncreate view");
return parent;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
MapsInitializer.initialize(getActivity());
} catch (Exception ex) {
mapsSupported = false;
}
if (mapView != null) {
mapView.onCreate(savedInstanceState);
}
initializeMap();
Log.d("spn", "onactivity created");
}
private void initializeMap() {
if (googleMap == null && mapsSupported) {
mapView = (MapView) getActivity().findViewById(R.id.map);
googleMap = mapView.getMap();
Drawable dmarker=getResources().getDrawable(R.drawable.ic_launcher);
dmarker.setBounds(0, 0, dmarker.getIntrinsicWidth(), dmarker.getIntrinsicHeight());
overmarker=new Overlay_Marker(dmarker,getActivity());
Drawable windmill = getResources().getDrawable(R.drawable.ic_launcher);
Drawable bigBen = getResources().getDrawable(R.drawable.ic_launcher);
Drawable eiffelTower = getResources().getDrawable(R.drawable.ic_launcher);
overmarker.addOverlayItem(52372991, 4892655, "Amsterdam", windmill);
overmarker.addOverlayItem(51501851, -140623, "London", bigBen);
overmarker.addOverlayItem(48857522, 2294496, "Paris", eiffelTower);
//List<Overlay_Marker> temp = (List<Overlay_Marker>) mapView.getOverlay();
// temp.add(overmarker);
mapView.getOverlay().add(overmarker); /// Not working
GetLongitude_Latitude();
}
}
public void GetLongitude_Latitude()
{
manager=(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
location=provider.getLocation(LocationManager.NETWORK_PROVIDER);
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
String provider = manager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = manager.getLastKnownLocation(provider);
manager.requestLocationUpdates(provider, 20000, 1, this);
if(location!=null)
onLocationChanged(location);
// Toast.makeText(getActivity(), "Location retrieved"+location.getLatitude()+" and "+location.getLongitude(), Toast.LENGTH_SHORT).show();
//else
// Toast.makeText(getActivity(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "No Provider Found", Toast.LENGTH_SHORT).show();
}
Log.d("spn", "location"+location);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
initializeMap();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onLocationChanged(Location location) {
latitude=location.getLatitude();
longitude=location.getLongitude();
latlang=new LatLng(latitude, longitude);
MarkerOptions marker=new MarkerOptions().position(latlang);
googleMap.addMarker(marker);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder().target(
latlang).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}

animateCamera android not working when returning back to activity

I am struggling with animateCamera method of the Android Google Maps API, what is happening is that it only runs once. When I come back to activity after some time its not working at all. I don't know why its not working as its working very first time when i open the activity but after that its not working at all, i debug the code and also check that if any error is thrown or not but no errors are catched. Even animateCamera method call is smoothly running but map is not getting animated to position after returning to activity again.
public class MapsActivity extends Activity {
private static GoogleMap mGoogleMap = null;
private static final String TAG = "MapsActivity";
private Button mBtnStartRide, mBtnPauseRide, mBtnStopRide = null;
private static TextView mTxtLatLong, mTxtTimer, mTxtTotalSize,
mTxtSpeed = null;
private static PolylineOptions mRectLine = null;
// Storing the directions returned by the direcction api
private static ArrayList<LatLng> mDirectionsPoints = new ArrayList<LatLng>();
private SharedPreferences mPreferences = null;
private MyBroadcastReceiver receiver = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
receiver = new MyBroadcastReceiver();
mPreferences = getSharedPreferences(Preferences.PREFERENCES,
Context.MODE_PRIVATE);
mTxtLatLong = (TextView) findViewById(R.id.txtLatLong);
mTxtTimer = (TextView) findViewById(R.id.txtTimer);
mTxtTotalSize = (TextView) findViewById(R.id.txtDirectionsSize);
mTxtSpeed = (TextView) findViewById(R.id.txtSpeed);
mBtnStartRide = (Button) findViewById(R.id.btn_start_ride);
mBtnPauseRide = (Button) findViewById(R.id.btn_pause_ride);
mBtnStopRide = (Button) findViewById(R.id.btn_stop_ride);
mBtnStartRide.setOnClickListener(btnStartRideClickListener);
mBtnPauseRide.setOnClickListener(btnPauseRideClickListener);
mBtnStopRide.setOnClickListener(btnStopRideClickListener);
initilizeMap();
}
/**
* Start Ride Button Click Listener
*/
private OnClickListener btnStartRideClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (mPreferences.getBoolean(Preferences.IS_RIDE_PAUSE, false)) {
if (RidingTimerService.getInstance() != null) {
RidingTimerService.getInstance().reStartRide();
}
} else {
startService(new Intent(MapsActivity.this,
RidingTimerService.class));
}
mPreferences.edit()
.putBoolean(Preferences.IS_RIDE_STOPPED, false)
.commit();
mBtnStartRide.setVisibility(View.GONE);
mBtnPauseRide.setVisibility(View.VISIBLE);
mBtnStopRide.setVisibility(View.VISIBLE);
}
};
/**
* Start Ride Button Click Listener
*/
private OnClickListener btnPauseRideClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
RidingTimerService.getInstance().pauseRide();
mPreferences.edit().putBoolean(Preferences.IS_RIDE_PAUSE, true)
.commit();
mBtnStartRide.setVisibility(View.VISIBLE);
mBtnPauseRide.setVisibility(View.GONE);
mBtnStopRide.setVisibility(View.VISIBLE);
}
};
/**
* Stop Ride Button Click Listener
*/
private OnClickListener btnStopRideClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(MapsActivity.this,
RidingTimerService.class));
mPreferences.edit().remove(Preferences.IS_RIDE_PAUSE).commit();
mPreferences.edit()
.putBoolean(Preferences.IS_RIDE_STOPPED, true).commit();
mDirectionsPoints.clear();
mBtnStartRide.setVisibility(View.VISIBLE);
mBtnPauseRide.setVisibility(View.GONE);
mBtnStopRide.setVisibility(View.GONE);
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter(
Constants.BROADCAST_INTENT));
initilizeMap();
if (mPreferences.getBoolean(Preferences.IS_RIDE_STOPPED, false)) {
// Show start button and gone Pause & Stop both
mBtnStartRide.setVisibility(View.VISIBLE);
mBtnPauseRide.setVisibility(View.GONE);
mBtnStopRide.setVisibility(View.GONE);
} else if (mPreferences
.getBoolean(Preferences.IS_RIDE_PAUSE, false)) {
mBtnStartRide.setVisibility(View.VISIBLE);
mBtnPauseRide.setVisibility(View.GONE);
mBtnStopRide.setVisibility(View.VISIBLE);
} else {
mBtnStartRide.setVisibility(View.GONE);
mBtnPauseRide.setVisibility(View.VISIBLE);
mBtnStopRide.setVisibility(View.VISIBLE);
}
setAllText();
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
/**
* Function to load map. If map is not created it will create it for you
* */
private void initilizeMap() {
if (mGoogleMap == null) {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (mGoogleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
} else {
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mRectLine = new PolylineOptions().width(6).color(Color.BLUE);
}
} else {
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mRectLine = new PolylineOptions().width(6).color(Color.BLUE);
animateCameraTo(mDirectionsPoints.get(0).latitude,
mDirectionsPoints.get(0).longitude);
}
}
/**
* Handler which handle the timer of ride
*/
public static Handler mCountDownHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
Log.i(TAG, msg.getData().getString("time"));
mTxtTimer.setText("Timer - " + msg.getData().getString("time"));
};
};
/**
* #author Scorpion
*
*/
private class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
mDirectionsPoints.add(new LatLng(intent.getExtras().getDouble(
Preferences.LATITUDE), intent.getExtras().getDouble(
Preferences.LONGITUDE)));
setAllText();
if (!mDirectionsPoints.isEmpty() && mDirectionsPoints.size() == 1) {
mGoogleMap.addMarker(new MarkerOptions()
.position(mDirectionsPoints.get(0)).anchor(0.8f, 1.0f)
.title("Your Location"));
}
animateCameraTo(
intent.getExtras().getDouble(Preferences.LATITUDE),
intent.getExtras().getDouble(Preferences.LONGITUDE));
}
}
/**
*
*/
public void setAllText() {
mTxtLatLong.setText("Lat - "
+ mPreferences.getString(Preferences.LATITUDE, "0.0")
+ ", Lng - "
+ mPreferences.getString(Preferences.LONGITUDE, "0.0"));
mTxtSpeed.setText("Speed - "
+ mPreferences.getString(Preferences.SPEED, "0.0"));
mTxtTotalSize.setText("Distance - "
+ mPreferences.getString(Preferences.DISTANCE, "0.0"));
}
/**
* Animate to position on Google Maps
*
* #param lat
* #param lng
*/
private void animateCameraTo(final double lat, final double lng) {
// Saving the points in a polyline
for (int i = 0; i < mDirectionsPoints.size(); i++) {
// Elevation array
mRectLine.add(mDirectionsPoints.get(i));
}
// Drawing the path on the map
mGoogleMap.addPolyline(mRectLine);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
new LatLng(lat, lng), 17);
mGoogleMap.animateCamera(cameraUpdate);
}
}
Also tried this :-
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(17.385044, 78.486671)).zoom(12).build();
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
What i wish is whenever user come back to this activity again, he should be able to see the path and location markers as well. I am storing all the lat long so that is not an issue for me, but things are not working with animateCamera and markers both right now. Using Google Maps v2 first time so not sure what exactly the problem is. Look forward to get some quick help or tips on it.
hello u can using SharedPreference then cache location. when re open app u can call "animateCamera()". importance, save location when location changed.
public View onCreateView(final LayoutInflater layoutInflater, final ViewGroup viewGroup, final Bundle bundle) {
SupportMapFragment.newInstance();
...
new Thread(new Runnable() {
#Override
public void run() {
SystemClock.sleep(1000);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// same SharedPreference
String model = SharedManager.getInstant(activity).getModel(Constant.CACHE_LOCATION);
if(model == null || model.isEmpty()){
return;
}
try {
LatLng latLng = new Gson().fromJson(model, LatLng.class);
animateCamera(latLng);
} catch (Exception e) {
}
}
});
}
}).start();
return inflate;
}
private void animateCamera(LatLng latLng) {
final CameraPosition cameraPosition = new CameraPosition.Builder().target(
latLng).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), new GoogleMap.CancelableCallback() {
#Override
public void onFinish() {
new Handler().post(new Runnable() {
#Override
public void run() {
// todo something
}
});
}
#Override
public void onCancel() {
}
});
}
Try this:
create your own class like:
public class MapUtil {
public static void animateMapToPositionAndZoom(GoogleMap googleMap, LatLng position, float zoomLevel) {
Log.i("animate map to position and zoom","Camera update on location change inclucding zoom");
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(position, zoomLevel);
googleMap.moveCamera(cameraUpdate);
}
}
Override this in your activity:
private LatLng myLatLng;
#Override
public void onConnected(Bundle arg0) {
if (myLatLng!= null) {
MapUtil.animateMapToPositionAndZoom(googleMap, myLatLng, currentZoomLevel);
}
}
May it help you.

Multiple onResume() when coming back to my activity from Home

When I am navigating out from my (main) activity and then coming back by clicking the icon on the Home screen - the activity is automatically Resumed->Paused->Resumed.
I am expecting for only one onResume().
My activity creates an AsyncTask in the onResume() function (the activity is not calling to other activities at all) and currently two additional AsyncTasks are created instead of one.
I did some tests and noticed that it happens when this activity is declared as "SingleTask" in the Mainfest. With 'SingleTop" it goes fine and onResume() is called only once.
HELP!
This is my code of the main activity:
public class HomeFinderActivity extends ListActivity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
private Location location;
private static final String LOG_TAG = "::HomeFinderActivity->Asynctask";
private ArrayList<Home> home_parts = new ArrayList<Home>();
private ListViewAdapter m_adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// instantiate ListViewAdapter class
m_adapter = new ListViewAdapter(this, R.layout.row, home_parts);
setListAdapter(m_adapter);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
}
//Asynctask to retrieve cursor from database and sort list by distance
private class SortList extends AsyncTask<Location, Void, ArrayList<Home>> {
#Override
protected ArrayList<Home> doInBackground(Location... location) {
try {
if (home_parts.isEmpty()){
home_parts=Home.getHomeParts(location[0], getApplicationContext());
}
else{
for (Home d : home_parts){
if (location != null){
d.setmDistance((int) (d.getmLatitude()), d.getmLongitude(),(double) (location[0].getLatitude())
, (double) (location[0].getLongitude()));
}
}
}
} finally {
}
Collections.sort(home_parts, new Comparator(){
public int compare(Object o1, Object o2) {
Home p1 = (Home) o1;
Home p2 = (Home) o2;
return (int) p1.getmDistance()- (int) p2.getmDistance();
}
});
return home_parts;
}
protected void onPostExecute(ArrayList<Home> address) {
m_adapter = new ListViewAdapter(HomeFinderActivity.this, R.layout.row, address);
// display the list.
setListAdapter(m_adapter);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
//starting handling location
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
Log.e(LOG_TAG, "onResume() started");
if (location != null) {
onLocationChanged(location);
}
else
{
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
Log.e(LOG_TAG, "onPause() started");
locationManager.removeUpdates(this);
}
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
SortList showList = new SortList();
showList.execute(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
/** Called when the user clicks the Add Entry button */
public void goAddEntry(View view) {
Intent intent = new Intent(this, AddEntry.class);
startActivity(intent);
}
}

Getting user current location on google mapview

Hi I have been trying to get and pinpoint the location of the phone (user current location) however I have no luck. I hope somebody can help me with the code.
Just to add some more, I am receiving a "Couldn't get connection factory client" error. Does this have something to do with the ability to return the user location?
If it helps I have been following the tutorial by thenewboston.
Or does this have something to do with my API key? But I can receive the map properly, but cannot pinpoint the user's current location
The main code:
public class Map extends MapActivity implements LocationListener{
MapView map;
long start;
long stop;
MyLocationOverlay compass;
MapController controller;
int x,y;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;
LocationManager lm;
LocationListener ll;
String towers;
int lat = 0;
int longi = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = (MapView)findViewById(R.id.mapview);
map.setBuiltInZoomControls(true);
touch t = new touch();
overlayList = map.getOverlays();
overlayList.add(t);
compass = new MyLocationOverlay(Map.this, map);
overlayList.add(compass);
controller = map.getController();
GeoPoint point = new GeoPoint(832332,4121093);
controller.animateTo(point);
controller.setZoom(8);
d = getResources().getDrawable(R.drawable.pointer);
//placing location
lm =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Location loc = lm.getLastKnownLocation(towers);
if(loc != null){
lat = (int) (loc.getLatitude() *1E6);
longi = (int)(loc.getLongitude()*1E6);
GeoPoint location = new GeoPoint(lat, longi);
OverlayItem overlayitem = new OverlayItem(location , "wassup", "2nd string");
CustomPinPoint custom = new CustomPinPoint(d, Map.this);
custom.insertPinPoint(overlayitem);
overlayList.add(custom);
}else{
Toast.makeText(Map.this, "Location is null", Toast.LENGTH_LONG).show();
lm.requestLocationUpdates(towers, 1500, 1, this);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
compass.disableCompass();
super.onPause();
lm.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
compass.enableCompass();
super.onResume();
lm.requestLocationUpdates(towers, 500, 1, this);
}
I think you can ignore the alertdialog
public class touch extends Overlay {
public boolean onTouchEvent(MotionEvent e, MapView m){
if(e.getAction()== MotionEvent.ACTION_DOWN){
start = e.getEventTime();
x = (int) e.getX();
y = (int) e.getY();
touchedPoint = map.getProjection().fromPixels(x, y);
}
if(e.getAction()== MotionEvent.ACTION_UP){
stop = e.getEventTime();
}
if(stop-start >1200){
AlertDialog alert = new AlertDialog.Builder(Map.this).create();
alert.setTitle("Option");
alert.setMessage("Pick the option");
alert.setCanceledOnTouchOutside(true);
alert.setButton("Place pointer pinpoint",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
OverlayItem overlayitem = new OverlayItem(touchedPoint , "wassup", "2nd string");
CustomPinPoint custom = new CustomPinPoint(d, Map.this);
custom.insertPinPoint(overlayitem);
overlayList.add(custom);
}
});
alert.setButton2("Get address",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6()
/1E6, touchedPoint.getLongitudeE6() /1E6, 1);
if (address.size()>0){
String display = "";
for(int i=0 ; i<address.get(0).getMaxAddressLineIndex(); i++){
display +=address.get(0).getAddressLine(i) + "\n";
}
Toast t = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
t.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
}
}
});
alert.setButton3("Toggle View",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(map.isSatellite()){
map.setSatellite(false);
map.setStreetView(true);
}else{
map.setStreetView(false);
map.setSatellite(true);
}
}
});
alert.show();
return true;
}
return false;
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_map, menu);
return true;
}
#Override
public void onLocationChanged(Location l) {
// TODO Auto-generated method stub
lat = (int)(l.getLatitude()*1E6);
longi = (int)(l.getLongitude()*1E6);
GeoPoint location = new GeoPoint(lat, longi);
OverlayItem overlayitem = new OverlayItem(location , "wassup", "2nd string");
CustomPinPoint custom = new CustomPinPoint(d, Map.this);
custom.insertPinPoint(overlayitem);
overlayList.add(custom);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
The CustomPinPoint code :
public class CustomPinPoint extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> pinpoints = new ArrayList<OverlayItem>();
private Context c;
// tesst google code
public CustomPinPoint(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public CustomPinPoint(Drawable defaultMarker, Context context) {
// TODO Auto-generated constructor stub
this(defaultMarker); //original code
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return pinpoints.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return pinpoints.size();
}
public void insertPinPoint(OverlayItem item){
pinpoints.add(item);
// this.populate(); // original code
// test code
populate();
}
#Override
protected boolean onTap(int index){
OverlayItem item = pinpoints.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(c);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
public void addOverlay(OverlayItem overlay) {
// TODO Auto-generated method stub
pinpoints.add(overlay);
populate();
}
}
XML code:
<com.google.android.maps.MapView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/mapview"
android:enabled="true"
android:clickable="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="0t9rHfGlUPgisa8P9MRAsSxhRXTVCL0XJog7uiA"
/>
Here is the example how to do that easily, try to implement this logic into your project:
public class MyMapActivity extends MapActivity {
private MapView map;
private MapController controller;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mymap);
initMapView();
initMyLocation();
map.invalidate();
}
private void initMapView() {
map = (MapView) findViewById(R.id.map);
controller = map.getController();
map.setSatellite(true);
map.setBuiltInZoomControls(true);
}
private void initMyLocation() {
final MyLocationOverlay overlay = new MyLocationOverlay(this, map);
overlay.enableMyLocation();
//overlay.enableCompass(); // does not work in emulator
overlay.runOnFirstFix(new Runnable() {
public void run() {
// Zoom in to current location
controller.setZoom(15);
controller.animateTo(overlay.getMyLocation());
}});
}
}
Well this is embarrassing, it turns out that my code is correct and the problem was that the device's GPS wasn't turned on. Well I hope my code can help anyone in need. Cheers!

Categories

Resources