java.lang.NullPointerException for google map API v2 - java

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.

Related

Why does my Activity get destroyed upon adding a fragment (#2)?

I want to make it clear that this question will look very similar to one I asked earlier, but that I'm not asking exactly the same thing.
In my previous question, I got a RuntimeException/IllegalStateException, which told me my Activity got destroyed upon adding a new fragment.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tim.timapp
/com.example.tim.timapp.MainActivity}: java.lang.IllegalStateException:
Activity has been destroyed
In that case, it turned out it had to do with me creating new instances of MainActivityin an invalid way:
MainActivity ma = new MainActivity();
(PSA: Don't do the above, use MainActivity ma = (MainActivity) getActivity(); instead.)
I have now corrected this in my entire project, and am getting almost exactly the same error. Let me be clear: I (think I) know the original error was fixed, because I got a different error in between these two RE's, which I was able to fix myself.
To reiterate on my gibberish: Got the first RE, fixed it with the answer on my question, got a different error, fixed that myself, got almost exactly the same RE.
I have searched through my entire project to see if I had anything similar to the error I made before, but I can't find anything, so here I am. So basically, the answer I got on my previous question fixed my issue, temporarily. That answer however, does not help me with this new error I'm getting, that's why I'm asking this question.
TL;DR: Answer on Q1 fixed my issue at first(which makes it a working answer), but it does not fix the issue I'm having right now, which is almost the same.
The actual question
So, now we've got that bit out of the way, let's get on with my issue. So, I'm getting a RuntimeException/IllegalStateExcetion:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.tim.timapp/com.example.tim.timapp.MainActivity}:
java.lang.IllegalStateException: Activity has been destroyed
(PS. It's only a RE because I have my app navigate to the GeneralSettings fragment on startup, for debugging ease.)
I've read up on this kind of error, but nothing I could find that applies on my project.
So, what is causing this RuntimeException/IllegalStateException?
Full log
04-05 14:17:53.140 23411-23411/? I/art: Not late-enabling -Xcheck:jni (already on)
04-05 14:17:53.190 23411-23411/com.example.tim.timapp W/System: ClassLoader referenced unknown path: /data/app/com.example.tim.timapp-1/lib/x86_64
04-05 14:17:53.210 23411-23411/com.example.tim.timapp D/TEST DBHandler: sInstance == null
04-05 14:17:53.370 23411-23411/com.example.tim.timapp D/AndroidRuntime: Shutting down VM
04-05 14:17:53.370 23411-23411/com.example.tim.timapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tim.timapp, PID: 23411
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tim.timapp/com.example.tim.timapp.MainActivity}: java.lang.IllegalStateException: Activity has been destroyed
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
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)
Caused by: java.lang.IllegalStateException: Activity has been destroyed
at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1433)
at android.app.BackStackRecord.commitInternal(BackStackRecord.java:687)
at android.app.BackStackRecord.commit(BackStackRecord.java:663)
at com.example.tim.timapp.MainActivity.DrawVariableFragments(MainActivity.java:276)
at com.example.fragments.Settings.GeneralSettingsFragment.onCreateView(GeneralSettingsFragment.java:58)
at android.app.Fragment.performCreateView(Fragment.java:2220)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:973)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
at android.app.BackStackRecord.run(BackStackRecord.java:793)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535)
at android.app.FragmentController.execPendingActions(FragmentController.java:325)
at android.app.Activity.performStart(Activity.java:6252)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
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) 
MainActivity (Snippet)
package com.example.tim.timapp;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static boolean isMainShown = false;
private static boolean isSettingsShown = false;
private static boolean doSavePopup = false;
private static String backTitle = "";
private String tag = "TEST MA";
DBHandler dbHandler;
Menu menu;
public void DrawVariableFragments(String base,String token){
// FragmentManager fm = getFragmentManager();
ArrayList<String> Data;
dbHandler = DBHandler.getInstance(this);
int AmountOfEntries;
int SettingsContainer;
String SettingsTag;
Fragment SettingsVariableFragment;
Fragment SettingsEmptyFragment;
if (base.equalsIgnoreCase("StuffManager")) {
Data = new ArrayList<String>() {{add("StuffManager"); add("name"); add("tag"); }};
SettingsContainer = R.id.FragmentContainer2;
SettingsTag = getString(R.string.navdrawer_stuffmanager);
SettingsVariableFragment = new StuffManagerVariableFragment();
SettingsEmptyFragment = new StuffManagerEmptyFragment();
} else if (base.equalsIgnoreCase("GeneralSettings")) {
Data = new ArrayList<String>() {{add("GeneralSettings"); add("name"); add("ip"); add("port"); add("username"); add("pass"); }};
SettingsContainer = R.id.FragmentContainerGeneralSettings;
SettingsTag = getString(R.string.navdrawer_generalsettings);
SettingsVariableFragment = new GeneralSettingsVariableFragment();
SettingsEmptyFragment = new GeneralSettingsEmptyFragment();
} else {
Log.e(tag, "String Base not recognised");
return;
}
AmountOfEntries = dbHandler.returnArray(base, Data.get(1)).size();
FragmentManager fm = getFragmentManager().findFragmentByTag(SettingsTag).getChildFragmentManager();
if ((dbHandler.returnArray(base, Data.get(1))).size() == 0 ) {
// Log.d(tag, "SettingsContainer1: " + String.valueOf(SettingsContainer) + "; SettingsEmtpyFragment1: " + SettingsEmptyFragment + "; Base1: " + base);
fm.beginTransaction().add(SettingsContainer, SettingsEmptyFragment, (base + "EmptyFragment")).commit();
fm.executePendingTransactions();
return;
}
if (AmountOfEntries > 0) {
String EmptyFragName = (base + "EmptyFragment");
if ((fm.findFragmentByTag(EmptyFragName)) != null) {
fm.beginTransaction().remove(fm.findFragmentByTag(EmptyFragName)).commit();
fm.executePendingTransactions();
}
for (int i = 0; i < AmountOfEntries; i++) {
ArrayList<String> fragmentData = new ArrayList<>();
for (int k=1; k < Data.size(); k++) {
int j=k-1;
fragmentData.set(j, (dbHandler.returnArray(base, Data.get(k)).get(j)));
}
if (token.equalsIgnoreCase("edit")) {
LinearLayout linearLayout = (LinearLayout) findViewById(SettingsContainer);
linearLayout.removeAllViews();
DrawVariableFragments(base ,"draw");
} else if (token.equalsIgnoreCase("add")) {
if (fm.findFragmentByTag(fragmentData.get(i)) == null) {
fm.beginTransaction().add(SettingsContainer, SettingsVariableFragment, fragmentData.get(0)).commit();
fm.executePendingTransactions();
if (base.equalsIgnoreCase("StuffManager")) {
((StuffManagerVariableFragment) fm
.findFragmentByTag(fragmentData.get(i)))
.setText(fragmentData.get(0), fragmentData.get(1));
} else if (base.equalsIgnoreCase("GeneralSettings")) {
((GeneralSettingsVariableFragment) fm
.findFragmentByTag(fragmentData.get(i)))
.setText(fragmentData.get(0), fragmentData.get(1), fragmentData.get(2), fragmentData.get(3));
}
}
} else if (token.equalsIgnoreCase("draw")) {
fm.beginTransaction().add(SettingsContainer, SettingsVariableFragment, fragmentData.get(0)).commit();
fm.executePendingTransactions();
if (base.equalsIgnoreCase("StuffManager")) {
((StuffManagerVariableFragment) fm
.findFragmentByTag(fragmentData.get(i)))
.setText(fragmentData.get(0), fragmentData.get(1));
} else if (base.equalsIgnoreCase("GeneralSettings")) {
((GeneralSettingsVariableFragment) fm
.findFragmentByTag(fragmentData.get(i)))
.setText(fragmentData.get(0), fragmentData.get(1), fragmentData.get(2), fragmentData.get(3));
}
}
}
} else {
Log.d("TEST", "WTF, nameArray.size != 0 && !> 0");
}
}
}
GeneralSettingsFragment (Snippet)
package com.example.fragments.Settings;
public class GeneralSettingsFragment extends Fragment {
MainActivity ma;
DBHandler dbHandler;
private static Menu optionsMenu;
public static boolean hideDeleteAllButton = false;
LinearLayout linearLayout;
View rootView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_generalsettings, container, false);
ma = (MainActivity) getActivity();
linearLayout = (LinearLayout) rootView.findViewById(R.id.FragmentContainerGeneralSettings);
if (linearLayout == null) {
Log.e("GMF", "Layout is null");
} else if (linearLayout.getChildCount() == 0) {
GeneralSettingsInitialInputDialog GSIID = new GeneralSettingsInitialInputDialog();
GSIID.show(getFragmentManager(), "dialog");
hideDeleteAllButton = true;
} else {
hideDeleteAllButton = false;
}
ma.DrawVariableFragments("GeneralSettings", "draw");
return rootView;
}
}
You are still doing things in an unsupported way. In MainActivity.DrawVariableFragments() you are creating a new GeneralSettingsVariableFragment() and then call getChildFragmentManager() on it and attempt to commit a fragment.
The GeneralSettingsFragment has not yet been attached to an Activity so it does not have a host. This throws the IllegalStateException("Activity has been destroyed") exception you are seeing when you try to commit the FragmentTransaction.
It is unclear why you are creating a new GeneralSettingsVariableFragmentwhen you are already inside a new instance of one.
To properly lookup an existing fragment use getFragmentManager().findFragmentByTag(...) or getFragmentManager().findFragmentById(...).

Android: google maps into a fragment

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));
}
});

Not able to display path from current location to destination google maps V2

I am trying to draw path from current location to destination using the answer Android: How to draw route directions google maps API V2 from current location to destination.
But in place of the hard coded I longitude and Latitude of the current location I want to use my real location. But whenever I try to do that, the App is crashing with error in line location = mMap.getMyLocation();
Any help is appreciated.
MapsActivity.Java
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
Location location;
LatLng myPosition;
GMapV2Direction md;
LatLng fromPosition = getYourLocation();
LatLng toPosition = new LatLng(13.683660045847258, 100.53900808095932);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
md = new GMapV2Direction();
setUpMapIfNeeded();
LatLng coordinates = new LatLng(13.685400079263206, 100.537133384495975);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 16));
mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start"));
mMap.addMarker(new MarkerOptions().position(toPosition).title("End"));
Document doc = md.getDocument(fromPosition, toPosition, GMapV2Direction.MODE_DRIVING);
int duration = md.getDurationValue(doc);
String distance = md.getDistanceText(doc);
String start_address = md.getStartAddress(doc);
String copy_right = md.getCopyRights(doc);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
for(int i = 0 ; i < directionPoint.size() ; i++) {
rectLine.add(directionPoint.get(i));
}
mMap.addPolyline(rectLine);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
/*myPosition = getLocation();
ZoomCurrentLocation(myPosition);*/
}
}
}
private LatLng getYourLocation() {
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
double latitude = 0;
double longitude = 0;
if (location != null) {
// Getting latitude of the current location
latitude = location.getLatitude();
// Getting longitude of the current location
longitude = location.getLongitude();
// Creating a LatLng object for the current location
}
LatLng latLng = new LatLng(latitude, longitude);
return latLng;
}
private void ZoomCurrentLocation(LatLng myPosition)
{
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myPosition, 16));
}
private void setUpMap(LatLng myPosition) {
mMap.addMarker(new MarkerOptions().position(myPosition).title("Marker"));
}
}
Do you mean location = mMap.getMyLocation(); is the method getYourLocation() in the code, and the crash is at Location location = locationManager.getLastKnownLocation(provider); ?
If so, it may cause by NullPointer Exception, you need use new api FusedLocationApi to avoid getLastLocation null pointer.
Please check here to know how to use it. And here is the code for it on my github.
For the destination you can check here to get some idea.

NullPointerException since changing Google Maps API key

I'm getting an error in my Android application. The application worked perfectly and then when I was building the apk I realised my Google Maps API key wasn't going to work for multiple users, so I made a new one following the Google tutorial. Now when I install my app I get a force close - could someone help me ?
This is the logcat:
`03-20 15:42:45.209 3906-3906/project.sharethefare E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: project.sharethefare, PID: 3906
java.lang.RuntimeException: Unable to start activity ComponentInfo{project.sharethefare/project.sharethefare.CurrentLocation}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5834)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()' on a null object reference
at project.sharethefare.CurrentLocation.setUpMapIfNeeded(CurrentLocation.java:55)
at project.sharethefare.CurrentLocation.onCreate(CurrentLocation.java:25)
at android.app.Activity.performCreate(Activity.java:6221)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725)
            at android.app.ActivityThread.access$900(ActivityThread.java:172)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5834)
            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:1388)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
`
This is the class:
public class CurrentLocation extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
//________________________________________________________________________________________
#Override
protected void onCreate(Bundle savedInstanceState) { //auto generated
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current_location);
setUpMapIfNeeded(); //part of google maps api
mMap.setMyLocationEnabled(true); //creates a new HomeScreen
}
#Override
protected void onResume() { //Auto Generated
super.onResume();
setUpMapIfNeeded(); //set up map if not already created
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.curLocMap))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
//call the method to continuously check current location
private void setUpMap() {
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
}
//called above. Used to constantly update the users position on the map
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
//create a new latitude and longitude point
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
//make global variables on home screen == to current location
HomeScreen.curLat = location.getLatitude();
HomeScreen.curLong = location.getLongitude();
HomeScreen.curLocSet = true;
//animate the camera to zoom in on position when found
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
};
public void backToHome(View view){ // called when button clicked. returns to homeScreen activity
Intent intent = new Intent(CurrentLocation.this,HomeScreen.class);
startActivity(intent);
}
}
Any help would be greatly appreciated. Thanks in advance

Send Value From onPostExecute() to Activity is always NULL

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();
}
}

Categories