I have spent a while trying to get this to work and I keep getting stuck somewhere at every tutorial. In short I am trying to make a tabbed app where one of the tabs it a google maps.
I have fixed all of the usual mistakes:
I have downloaded everything relevant through SDK.
I have an API key in place.
I have added compile com.google.android.gms:play-services:7.5.0 to my dependencies.
I am trying to follow this code, but I keep getting an error.
Error I am receiving from logcat:
07-06 13:46:20.046 17948-17948/dolphin.dolphinapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: dolphin.dolphinapp, PID: 17948
java.lang.NullPointerException: IBitmapDescriptorFactory is not initialized
at com.google.android.gms.common.internal.zzu.zzb(Unknown Source)
at com.google.android.gms.maps.model.BitmapDescriptorFactory.zzvH(Unknown Source)
at com.google.android.gms.maps.model.BitmapDescriptorFactory.defaultMarker(Unknown Source)
at dolphin.dolphinapp.MainActivity$MapFragment.onCreateView(MainActivity.java:655)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1105)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:551)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:513)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:494)
at dolphin.dolphinapp.MainActivity.onTabSelected(MainActivity.java:152)
at android.support.v7.internal.app.WindowDecorActionBar.selectTab(WindowDecorActionBar.java:640)
at android.support.v7.internal.app.WindowDecorActionBar$TabImpl.select(WindowDecorActionBar.java:1224)
at android.support.v7.internal.widget.ScrollingTabContainerView$TabClickListener.onClick(ScrollingTabContainerView.java:568)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Apparently to solve this write MapsInitializer.initialize(getActivity().getApplicationContext());, but that is already in the code I copied.
Here is my Java Code:
public class MapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_location_info, container,
false);
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
MapsInitializer.initialize(getApplicationContext());
googleMap = mMapView.getMap();
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
// Perform any camera updates here
return v;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
My XML File:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Please let me know what I am doing wrong
you should call mMapView.getMapAsync() in your onCreateView then in the callback of onMapReady that you implement you would do MapsInitializer.initialize(this.context);
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getApplicationContext());
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
}
});
Related
I'm not sure what is wrong with my following code
public class MainActivity extends AppCompatActivity implements LocationListener {
LocationManager locationManager;
String provider; //store gps provider
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//get location of user
provider = locationManager.getBestProvider(new Criteria(), false); //false to check if available ourselves
Location location = locationManager.getLastKnownLocation(provider);
if (location != null){
Log.i("Location info:", "Location achieved!");
}
else{
Log.i("Location info:", "No location");
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this); //(provider, miliseconds, meters, context)
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override //gives location as soon as it changes or updates
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
Log.i("Latitude", String.valueOf(lat));
Log.i("Longitude", String.valueOf(lng));
}
#Override //when location comes available
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override //when gps is available
public void onProviderEnabled(String provider) {
}
#Override //when gps is disabled
public void onProviderDisabled(String provider) {
}
}
I get this error everytime I run it
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jimmy.locationdemo, PID: 19373
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jimmy.locationdemo/com.example.jimmy.locationdemo.MainActivity}: java.lang.IllegalArgumentException: invalid provider: null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2440)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2500)
at android.app.ActivityThread.access$900(ActivityThread.java:163)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1362)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5585)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Caused by: java.lang.IllegalArgumentException: invalid provider: null
at android.location.LocationManager.checkProvider(LocationManager.java:1828)
at android.location.LocationManager.getLastKnownLocation(LocationManager.java:1275)
at com.example.jimmy.locationdemo.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:6279)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2500)
at android.app.ActivityThread.access$900(ActivityThread.java:163)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1362)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5585)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
I have written the permission in the manifest as well. Maybe I'm using the wrong API?
If someone can point me in the right direction that would be awesome.
Hey Im new to Android and wondering if someone can help me. I have a MapsActivity which crashes when navigating to it. I think I've narrowed down to exactly where it is from looking through the errors but I cant figure out what to change.
I've added the whole MapsActivity class below. The problem is occuring in the onConnected method on this line mLocationManager.requestLocationUpdates(provider, 5000, 0, this);
. Android Studio recommends I cast 'this' to LocationListener but this doesn't work and the error I get from doing so is listed below the MapsActivity code.
I have also tried entering mLocationListener in the place of 'this' but doesn't work and I get errors which are listed below too.
ANY HELP IS GREATLY APPRECIATED. THANKS!
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 2;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private LocationManager mLocationManager;
private Location mLastLocation;
private LocationListener mLocationListener;
private String mLatitude;
private String mLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
//create instance of location manager and get location service
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
//mLocationManager.removeUpdates((LocationManager) this);
super.onStop();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(true);
criteria.setBearingRequired(true);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = mLocationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager.requestLocationUpdates(provider, 5000, 0, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null){
mLatitude = String.valueOf(mLastLocation.getLatitude());
mLongitude = String.valueOf(mLastLocation.getLongitude());
Toast.makeText(this, mLatitude + " , " + mLongitude, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Permission denied, please accept permission..", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults){
switch (requestCode){
case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION:{
//if request cancelled the results array is empty
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//do task you wish to do
//Intent intent = (new Intent(this, MapsActivity.class));
//startActivity(intent);
}else{
//permission denied, disable functionality(GPS)
}
return;
}
//other cases go here
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
}
}
Casting errors -
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.a8460p.locationotes, PID: 23305
java.lang.ClassCastException: com.example.a8460p.locationotes.MapsActivity cannot be cast to android.location.LocationListener
at com.example.a8460p.locationotes.MapsActivity.onConnected(MapsActivity.java:106)
at com.google.android.gms.common.internal.zzm.zzq(Unknown Source)
at com.google.android.gms.internal.zzaal.zzo(Unknown Source)
at com.google.android.gms.internal.zzaaj.zzvE(Unknown Source)
at com.google.android.gms.internal.zzaaj.onConnected(Unknown Source)
at com.google.android.gms.internal.zzaan.onConnected(Unknown Source)
at com.google.android.gms.internal.zzzy.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzl$1.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzf$zzj.zzwZ(Unknown Source)
at com.google.android.gms.common.internal.zzf$zza.zzc(Unknown Source)
at com.google.android.gms.common.internal.zzf$zza.zzu(Unknown Source)
at com.google.android.gms.common.internal.zzf$zze.zzxa(Unknown Source)
at com.google.android.gms.common.internal.zzf$zzd.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Replacing 'this' with mLocationListener errors -
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.a8460p.locationotes, PID: 24073
java.lang.IllegalArgumentException: invalid listener: null
at android.location.LocationManager.checkListener(LocationManager.java:1733)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:461)
at com.example.a8460p.locationotes.MapsActivity.onConnected(MapsActivity.java:106)
at com.google.android.gms.common.internal.zzm.zzq(Unknown Source)
at com.google.android.gms.internal.zzaal.zzo(Unknown Source)
at com.google.android.gms.internal.zzaaj.zzvE(Unknown Source)
at com.google.android.gms.internal.zzaaj.onConnected(Unknown Source)
at com.google.android.gms.internal.zzaan.onConnected(Unknown Source)
at com.google.android.gms.internal.zzzy.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzl$1.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzf$zzj.zzwZ(Unknown Source)
at com.google.android.gms.common.internal.zzf$zza.zzc(Unknown Source)
at com.google.android.gms.common.internal.zzf$zza.zzu(Unknown Source)
at com.google.android.gms.common.internal.zzf$zze.zzxa(Unknown Source)
at com.google.android.gms.common.internal.zzf$zzd.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Make MapsActivity implements android.location.LocationListener instead of com.google.android.gms.location.LocationListener
For First crash: this crash is occuring due to the incorrect import for location listener class which you have implements to your Activity.
Change com.google.android.gms.location.LocationListener with android.location.LocationListener
and for second crash use bellow LocationListener, this crash is occuring due your null reference of location listener object.
private LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
Your requestLocationUpdates could not find instance of Listener so add MapsActivity.this to requestLocationUpdates
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager.requestLocationUpdates(provider, 5000, 0, MapsActivity.this);//Changed here
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null){
mLatitude = String.valueOf(mLastLocation.getLatitude());
mLongitude = String.valueOf(mLastLocation.getLongitude());
Toast.makeText(this, mLatitude + " , " + mLongitude, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Permission denied, please accept permission..", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
I have a mapsview and it works fine when using getMap() although it shows me a depricated warning. But when i change getMap() to getMapAsync() the app will crash.
Here's my code
public class MapsActivity extends AppCompatActivity implements GoogleMap.OnInfoWindowClickListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnInfoWindowCloseListener,
LocationListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMapAsync(this);
mMap.setOnInfoWindowClickListener(this);
mMap.setOnInfoWindowCloseListener(this);
mMap.setOnMarkerDragListener(this);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
markerPoints.add(latLng);
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(latLng);
}
});
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
//Getting the coordinates
toLatitude = marker.getPosition().latitude;
toLongitude = marker.getPosition().longitude;
dest = new LatLng(toLatitude, toLongitude);
mMap.animateCamera(CameraUpdateFactory.newLatLng(dest));
return ((toLatitude == my_marker.getPosition().latitude) && (toLongitude == my_marker.getPosition().longitude));
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();
}
private void setUpMap() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
Toast.makeText(MapsActivity.this, "Anda harus menyetujuinya agar dapat menikmati semua fitur yang ada", Toast.LENGTH_LONG).show();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder()
.zoom(15) // Sets the zoom
.target(new LatLng(-6.597629,106.79957))
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
Here's the xml layout
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
What's wrong with my code? Any help will be greatly appreciated.
Thanks.
I suppose that mMap is the GoogleMap object here.What you are doing is using mMap before it gets initialized so it must be throwing null pointer exception.
Make sure to use mMap object in onMapReady Callback.Hope it solves
your problem.So, in short all you need to do is place all your mMap
usages in onMap Ready callback
At the moment of getMapAsync call the onMapReady is not done. Be sure that ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) is not null or onMapReady() has finished with success.
I created this class:
public class GetAddressPositionTask extends
AsyncTask<String, Integer, LatLng> {
//...
}
It has the below function in it:
#Override
public void onPostExecute(LatLng result) {
Log.i("GEOCODE", result.toString());
super.onPostExecute(result);
Intent i = new Intent(this.mainContxt , MapsActivity.class);
i.putExtra("latlng" , result);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
this.mainContxt.startActivity(i);
}
I am trying to send data to the Activity called MapsActivity from the onPostExecute method.
In MapsActivity I have before onCreate this:
LatLng position = new LatLng(34.6767, 33.04455);
My onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (getIntent() != null) {
Intent intent = getIntent();
if (getIntent().getExtras().getParcelable("latlng")!= null) {
position = getIntent().getExtras().getParcelable("latlng");
}
else {
Log.d("NULL?", "position is empty!");
}
} else {
}
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.
map);
mapFragment.getMapAsync(this);
}
This is my onMapReady that created the pin with the position that I initialized and when you type an address and press the search button, it calls the above class that has the onPost function and trying to pin a location in the map if the position is not null.
#Override
public void onMapReady(final GoogleMap map) {
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
map.animateCamera(zoom);
map.addMarker(new MarkerOptions()
.title("Shop")
.snippet("Is this the right location?")
.position(position))
.setDraggable(true);
// map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
map.setOnInfoWindowClickListener(this);
map.setOnMarkerDragListener(this);
ImageButton search = (ImageButton) findViewById(R.id.search);
final EditText searchaddress = (EditText) findViewById(R.id.locationsearch);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//FIND LOCATION BY ADDRESS
if (searchaddress.getText().toString() != null && !searchaddress.getText().toString().isEmpty()) {
new GetAddressPositionTask(getApplicationContext()).execute(searchaddress.getText().toString());
map.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
map.animateCamera(zoom);
//Marker marker = null;
map.clear();
//marker.setPosition(position);
map.addMarker(new MarkerOptions()
.title("Shop")
.snippet("Is this the right location?")
.position(position))
.setDraggable(true);
// map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
map.setOnInfoWindowClickListener(MapsActivity.this);
map.setOnMarkerDragListener(MapsActivity.this);
} else {
Toast.makeText(getApplicationContext(), "Please enter an address!", Toast.LENGTH_LONG).show();
}
}
});
}
The process I do is open MapsActivity, then type a correct address and trying to display it.
The result is that the position doesn't being changed BUT i don't get in logcat the message NULL?﹕ position is empty! after clicking the button.
This is the logcat from the first time I navigate to MapsActivity and then click a button that calls the class:
02-24 20:55:35.133 5907-5907/guide_me_for_all.guide_me_for_all E/Spinner﹕ setPopupBackgroundDrawable: incompatible spinner mode; ignoring...
02-24 20:55:35.143 5907-5907/guide_me_for_all.guide_me_for_all E/Spinner﹕ setPopupBackgroundDrawable: incompatible spinner mode; ignoring...
02-24 20:55:35.143 5907-5907/guide_me_for_all.guide_me_for_all E/Spinner﹕ setPopupBackgroundDrawable: incompatible spinner mode; ignoring...
02-24 20:55:35.223 5907-5907/guide_me_for_all.guide_me_for_all I/Choreographer﹕ Skipped 47 frames! The application may be doing too much work on its main thread.
02-24 20:55:36.775 5907-5907/guide_me_for_all.guide_me_for_all I/Timeline﹕ Timeline: Activity_launch_request id:guide_me_for_all.guide_me_for_all time:42579264
02-24 20:55:36.865 5907-5907/guide_me_for_all.guide_me_for_all I/x﹕ Making Creator dynamically
02-24 20:55:37.265 5907-5907/guide_me_for_all.guide_me_for_all I/Google Maps Android API﹕ Google Play services client version: 6587000
02-24 20:55:37.285 5907-5907/guide_me_for_all.guide_me_for_all I/Google Maps Android API﹕ Google Play services package version: 6776034
02-24 20:55:38.406 5907-5907/guide_me_for_all.guide_me_for_all I/dalvikvm﹕ Could not find method android.content.pm.PackageManager.getPackageInstaller, referenced from method com.google.android.gms.common.ew.c
02-24 20:55:38.406 5907-5907/guide_me_for_all.guide_me_for_all W/dalvikvm﹕ VFY: unable to resolve virtual method 441: Landroid/content/pm/PackageManager;.getPackageInstaller ()Landroid/content/pm/PackageInstaller;
02-24 20:55:38.406 5907-5907/guide_me_for_all.guide_me_for_all D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000f
02-24 20:55:39.117 5907-5907/guide_me_for_all.guide_me_for_all D/NULL?﹕ position is empty!
02-24 20:55:39.377 5907-5907/guide_me_for_all.guide_me_for_all I/Choreographer﹕ Skipped 57 frames! The application may be doing too much work on its main thread.
02-24 20:55:39.517 5907-5907/guide_me_for_all.guide_me_for_all I/libblt_hw﹕ Library opened (handle = 0, fd = 100)
02-24 20:55:39.788 5907-5907/guide_me_for_all.guide_me_for_all I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy#424fec18 time:42582274
02-24 20:55:41.970 5907-5912/guide_me_for_all.guide_me_for_all I/dalvikvm﹕ Jit: resizing JitTable from 4096 to 8192
02-24 20:55:47.946 5907-6133/guide_me_for_all.guide_me_for_all I/GEOCODE_background﹕ lat/lng: (64.963051,-19.020835)
02-24 20:55:47.946 5907-5907/guide_me_for_all.guide_me_for_all I/GEOCODE﹕ lat/lng: (64.963051,-19.020835)
02-24 20:55:47.946 5907-5907/guide_me_for_all.guide_me_for_all I/Timeline﹕ Timeline: Activity_launch_request id:guide_me_for_all.guide_me_for_all time:42590434
some bit confusing code and explanation,
Lets go with step wise.
Step 1: Update your MapsActivity's onCreate()
Like,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
As here Intent is not required as you are only calling MapsActivity within same MapsActivity. We will update map in onPostExecute() of Activity then no need to start Activity again.
Step 2: Create Constructor for GetAddressPositionTask with GoogleMap map parameter to update your map position in onPostExecute() of GetAddressPositionTask. And onPostExecute()
Like,
public class GetAddressPositionTask extends
AsyncTask<String, Integer, LatLng> {
GoogleMap googleMap;
LatLng mapPosition;
GetAddressPositionTask(GoogleMap map, LatLng position)
{
googleMap = map;
mapPosition = position;
}
//...
#Override
public void onPostExecute(LatLng result) {
if(result != null)
{
Log.i("GEOCODE", result.toString());
mapPosition = result;
googleMap.clear();
googleMap.addMarker(new MarkerOptions()
.title("Shop")
.snippet("Is this the right location?")
.position(mapPosition))
.setDraggable(true);
}
}
}
Step 3: How the search Button's onClick() look like, No extra code required,
public void onClick(View v) {
//FIND LOCATION BY ADDRESS
if (searchaddress.getText().toString() != null && !searchaddress.getText().toString().isEmpty()) {
GetAddressPositionTask addressTask = new GetAddressPositionTask(map, position);
addressTask.execute(searchaddress.getText().toString());
} else {
Toast.makeText(getApplicationContext(), "Please enter an address!", Toast.LENGTH_LONG).show();
}
}
I have been trying to solve this issue for ages and I can't find where the problem is.
I am having trouble only with some devices that run Android 2.2. I tested on Android 4.1.2 and it works fine.
The error I am getting:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.coldice.plotfinder/com.coldice.plotfinder.MapFragment}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2668)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2684)
at android.app.ActivityThread.access$2300(ActivityThread.java:126)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2038)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4632)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.coldice.plotfinder.MapFragment.onCreate(MapFragment.java:67)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2632)
... 11 more
So looking back to my class MapFragment line 67 which is
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
I am aware that googlemap API v2 requires API level 12 or higher as noted here, but I am using lower so I called
getSupportFragmentManager();
The MapFragment class code is below:
public class MapFragment extends SherlockFragmentActivity {
private static final String TAG = "MapFragment";
private GoogleMap googleMap; // Google map
private int mapType = GoogleMap.MAP_TYPE_SATELLITE;
private Polyline polyline;; // Drawing the area of the land by using the polygon
private boolean isDrawn=false;
static String fileToBeRead =null; // The file name to be read
ArrayList<Cooridnates> cooridnatesList;
// Image utility saving
ImageSaveUtil imageUtil = new ImageSaveUtil();
#Override
public void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Theme_Sherlock);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Different colors for each marker
float[] markerColours = {BitmapDescriptorFactory.HUE_AZURE,BitmapDescriptorFactory.HUE_BLUE,BitmapDescriptorFactory.HUE_CYAN,BitmapDescriptorFactory.HUE_GREEN,
BitmapDescriptorFactory.HUE_MAGENTA,BitmapDescriptorFactory.HUE_ORANGE,BitmapDescriptorFactory.HUE_RED,BitmapDescriptorFactory.HUE_ROSE,
BitmapDescriptorFactory.HUE_VIOLET,BitmapDescriptorFactory.HUE_YELLOW};
// The code I am getting java.lang.NullPointerException
FragmentManager fragmentManager = getSupportFragmentManager();
SupportMapFragment mapFragment = (SupportMapFragment)fragmentManager.findFragmentById(R.id.map);
googleMap = mapFragment.getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// If there is a file to be read, then read the coordinates
if(fileToBeRead!=null)
{
readData(fileToBeRead);
fileToBeRead =null;
}
// Getting the coordinates List
cooridnatesList = MainActivity.getList();
if(cooridnatesList!=null)
{
// Adding a marker from each point
for(int i=0;i<cooridnatesList.size();i++)
{
LatLng point = new LatLng(cooridnatesList.get(i).getLat(),cooridnatesList.get(i).getLon());
googleMap.addMarker(new MarkerOptions()
.position(point)
.title("My Land")
.snippet("Point: "+cooridnatesList.get(i).getLat()+","+cooridnatesList.get(i).getLon())
.icon(BitmapDescriptorFactory.defaultMarker(markerColours[i%10])));
}
googleMap.getUiSettings().setCompassEnabled(true); // Setting the compass enabled in the map
googleMap.getUiSettings().setZoomControlsEnabled(true); // Zooming is enabled
googleMap.getUiSettings().setMyLocationButtonEnabled(true); // My location button is enabled
// Zooming the camera from the first point entered
LatLng cameraLatLng = new LatLng(cooridnatesList.get(0).getLat(),cooridnatesList.get(0).getLon());
float cameraZoom = 10;
if(savedInstanceState != null){
mapType = savedInstanceState.getInt("map_type", GoogleMap.MAP_TYPE_SATELLITE);
double savedLat = savedInstanceState.getDouble("lat");
double savedLng = savedInstanceState.getDouble("lng");
cameraLatLng = new LatLng(savedLat, savedLng);
cameraZoom = savedInstanceState.getFloat("zoom",18);
}
// Setting the map type such as satellites or street view
googleMap.setMapType(mapType);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(cameraLatLng, cameraZoom));
//Displaying the land area
final TextView landInformation = (TextView)findViewById(R.id.textViewLandInformation);
double area = calculateArea(cooridnatesList);
landInformation.setText(getString(R.string.land_area)+"\n"+Math.round(area)+" SQ.M");
}
}
Try moving all code that references your GoogleMap to onStart() or onResume(). The map in a map fragment isn't instantiated until after the fragment has gone through onCreateView (link). Also, you need to check your googleMap for null, because if google play services aren't installed, or the map isn't available for some other reason, it will be null.