NullPointerException since changing Google Maps API key - java

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

Related

Running GoogleApiClient on Thread results in error

I am new to android. I am trying to display current location in my MainActivity.
But as my network is slow I am getting the entire front end very late. So i decided to use Threads. So my location based part of the code runs silently in the background.Things worked Perfectly but my OnResume function throws an error. And I am not sure how to proceed further about it.
My Thread code in MainActivity OnCreate:
UserLocationDetails locationDetails=new UserLocationDetails();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
GoogleApiClient mGoogleApiClient;
SmsManager smsManager = SmsManager.getDefault();
private LocationRequest mLocationRequest;
TextView userLocationView;
Button settings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Runnable runnable=new Runnable() {
#Override
public void run() {
mGoogleApiClient=new GoogleApiClient.Builder(MainActivity.this).
addConnectionCallbacks(MainActivity.this).
addOnConnectionFailedListener(MainActivity.this).
addApi(LocationServices.API).build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
};
Thread googleApiClientThread=new Thread(runnable);
googleApiClientThread.start();
OnResume Function:
#Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
Log.i(TAG, "OnResume, Connected back!");
}
Logcat Error:
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void com.google.android.gms.common.api.GoogleApiClient.connect()' on a null object reference
at androidfactory.mafi.com.wru.MainActivity.onResume(MainActivity.java:113)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1280)
at android.app.Activity.performResume(Activity.java:6096)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3011)
            at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3063)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
            at android.app.ActivityThread.access$800(ActivityThread.java:155)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5343)
            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:905)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Null Pointer Exception is thrown because in onResume() it is trying to call method on mGoogleApiClient, but it is not created as its creation is done inside of Runnable background thread, so there is asynchronous execution of code.
you can check before calling connect() for null reference.
protected void onResume() {
super.onResume();
if(mGoogleApiClient != null){
mGoogleApiClient.connect();
Log.i(TAG, "OnResume, Connected back!");
}
}
Why do you need to initialize the GoogleApiClient inside a thread inside onCreate?
You can just declare it without a thread.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient=new GoogleApiClient.Builder(this).
addConnectionCallbacks(this).
addOnConnectionFailedListener(this).
addApi(LocationServices.API).build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
then your onResume should work fine.
#Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
Log.i(TAG, "OnResume, Connected back!");
}
About your comment :
If its NOT NULL , why should I connect again ? Only if its null I
should be connecting right ??
You cannot call connect() from a NULL Object such mGoogleApiClient. Since you initialized it on a separated thread, Android calls onCreate()-->onStart()-->onResume() one after another in this order, so when you reach onResume(), your mGoogleApiClient was not initialized yet by the thread, that's why you got the error.
Just by initializing a mGoogleApiClient you are NOT CONNECTING ANYTHING! So you need to call connect() if you plan to use any feature from Google Play Service.

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

Android Studio NullPointerException, trying to use parse.com

I am trying to use Parse.com for the user login/signup activity for my apps, and I am learning how to use it by following this tutorial http://www.androidbegin.com/tutorial/android-parse-com-simple-login-and-signup-tutorial/ . But after I typed in everything, my app keep crashing and giving NullPointerException
And here is my MainActivity
package com.example.ed.parselogintutorial;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.parse.Parse;
import com.parse.ParseAnonymousUtils;
import com.parse.ParseUser;
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
Parse.initialize(this, "T9so2huSfs1xMHwEjx9vSeUuKeyBZsXVyG4QHi7K", "yiQz0RMs9TCkWu8EsdsoVxcPWGlTyAmO20JuEh0X");
super.onCreate(savedInstanceState);
//Determine whether the current user is an anonymous user
if (ParseAnonymousUtils.isLinked(ParseUser.getCurrentUser())) {
//If user is anonymous, send the user to LoginSignupActivity.class
Intent intent = new Intent(MainActivity.this,
LoginSignupActivity.class);
startActivity(intent);
finish();
} else {
//If current user is no anonymous user
//Get current user data from Parse.com
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
//Send logged in users to Welcome.class
Intent intent = new Intent(MainActivity.this, Welcome.class);
startActivity(intent);
finish();
} else {
//Send User to LoginSignupActivity.class
Intent intent = new Intent(MainActivity.this,
LoginSignupActivity.class);
startActivity(intent);
finish();
}
}
}
}
Here is the stack
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ed.parselogintutorial/com.example.ed.parselogintutorial.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.parse.ParseUser.isLinked(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
asdsa
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.parse.ParseUser.isLinked(java.lang.String)' on a null object reference
at com.parse.ParseAnonymousUtils.isLinked(ParseAnonymousUtils.java:51)
at com.example.ed.parselogintutorial.MainActivity.onCreate(MainActivity.java:28)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
I am sorry if there is a very clear mistake here as I am new to android development, please anyone who used Parse.com before or have any knowledge regarding this error, please teach me how to solve it. Thank you in advance.
Reading the comments below in the tutorial, there are issues with the given code. Here is the suggestions from one of the comments:
It's early so I am not that sure what they were going for here... Get
rid of the ParseApplication.java and put this in your
mainactivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); <<----UNDER THIS (left in for location purpose)
// Add your initialization code here
Parse.initialize(this, "YOUR_APPLICATION_ID", "YOUR_CLIENT_KEY");
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// If you would like all objects to be private by default, remove this
// line.
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
// Determine whether the current user is an anonymous user
if (ParseAnonymousUtils.isLinked(ParseUser.getCurrentUser())) { <<----(left in for location purpose)
Essentially, the problem is that you're not calling setContentView(R.layout.activity_main); before you try to call Parse functions.

I can't find this NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I have an issue I need help with. I am running into a NullPointerException no matter what I do with this app, and at this point it is seriously holding up this project. I have reviewed the logcat multiple times, made changes and re run the app and every time it turns out a nullpointerexception. For the life of me I can't seem to figure out what is causing it. Can someone point out where it is, and if possible, why it occurred since as far as I can tell I have everything assigned a value.
GameStart.java:
package com.saphiric.simproject;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by Saphiric on 11/12/14.
*/
public class GameStart extends Activity {
/**
* Necessary activity variables
*/
int clickCount = 0;
TextView storyText;
Button advanceGame;
DecisionFragment decisionFragment;
ControlsFragment controlsFragment;
public View.OnClickListener decisionTime = new View.OnClickListener(){
public void onClick(View v) {
clickCount = clickCount + 1; // Increments clickCount by 1 per click
// /**
// * Will handle checking how far into the story the player is
// * and update components as necessary.
// */
// switch (clickCount) {
// case 1:
// storyText.setText(R.string.story_opening_two);
// break;
//
// case 2:
// FragmentTransaction decisionTime = fragmentManager.beginTransaction();
// // Replace the fragment currently inside of the fragmentContainer
// decisionTime.replace(R.id.fragmentContainer, decisionFragment);
// decisionTime.commit();
// break;
//
// default:
// System.out.println("An error occurred");
// }
// System.out.println(clickCount);
}
};
/**
* Android activity methods
* #param savedInstanceState is the apps savedInstanceState
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_start);
// UI element handles
advanceGame = (Button) findViewById(R.id.advanceButton);
storyText = (TextView) findViewById(R.id.storyText);
decisionFragment = new DecisionFragment();
controlsFragment = new ControlsFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// UI will add the ControlsFragment in it's starting state for that activity.
fragmentTransaction.add(R.id.fragmentContainer, controlsFragment).commit();
// Sets the advanceButton to run decisionTime method
advanceGame.setOnClickListener(decisionTime);
}
}
LogCat:
12-07 13:16:10.142 19915-19915/com.saphiric.simproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.saphiric.simproject, PID: 19915
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.saphiric.simproject/com.saphiric.simproject.GameStart}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1069)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.saphiric.simproject.GameStart.onCreate(GameStart.java:75)
at android.app.Activity.performCreate(Activity.java:5312)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2552)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
            at android.app.ActivityThread.access$800(ActivityThread.java:156)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5872)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1069)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
            at dalvik.system.NativeStart.main(Native Method)
The null pointer happens at line 75 , i.e.
advanceGame.setOnClickListener(decisionTime);
Here, the only thing that can be null is advanceGame. This means that
advanceGame = (Button) findViewById(R.id.advanceButton);
is not able to find your button from your view. Check the id of the button if its exactly the same as you defined it in your android xml.
I believe that advanceGame is null.
You can't find button by findViewById(R.id.advanceButton);
NPE is at line 75
advanceGame.setOnClickListener(decisionTime);
it is clear from
at com.saphiric.simproject.GameStart.onCreate(GameStart.java:75)
Looks like at
advanceGame = (Button) findViewById(R.id.advanceButton);
view was not found. You can debug that or add check at 75
if(null != advanceGame) advanceGame = (Button) findViewById(R.id.advanceButton);
I think just check #+id of your activity_game_start.xml layout of advanceGame button
it might have different name

java.lang.NullPointerException for google map API v2

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.

Categories