0

The project initially has an activity that implements LocationListener to listen to user location. Our team decided to change the UI to employ a sliding tab layout in the MainActivity so that each tab would replace the activities we had previously.

So what I did was to copy and paste the code in the LocationListening activity into the tab fragment and made some changes to place where the context is required by replacing 'this' with 'getContext()'.

This is the full code of the tab fragment.

public class Tab2 extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    public String currentLatitude, currentLongitude;
    public Location myCurrentLocation;
    public String mLastUpdateTime;
    public LatLng destination = new LatLng(1.24940, 103.83032);
    private final static int proximity = 20000;
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(getContext())
                    .setSmallIcon(R.drawable.cast_ic_notification_0)
                    .setContentTitle("You are here")
                    .setAutoCancel(true)
                    .setVibrate(new long[]{0,1000,200,1000,200,1000}).setContentText("Reached destination!!");
    View v;


    // Sets an ID for the notification
    int mNotificationId = 001;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.tab_2,container,false);
        buildGoogleApiClient();
        createLocationRequest();
        return v;
    }

    @Override
    public void onConnected(Bundle connectionHint) {
        Toast.makeText(getContext(), "Connected", Toast.LENGTH_SHORT).show();
        Location myLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (myLastLocation != null) {
            currentLatitude = String.valueOf(myLastLocation.getLatitude());
            currentLongitude = String.valueOf(myLastLocation.getLongitude());
        }

        startLocationUpdates();
    }

    @Override
    public void onLocationChanged(Location location) {
        myCurrentLocation = location;
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        updateUI(myCurrentLocation);
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.e("g", "onConnectionFailed");
    }

    @Override
    public void onPause() {
        super.onPause();
        stopLocationUpdates();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(getContext())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .setAccountName("something@gmail.com")
                .build();
        mGoogleApiClient.connect();
    }

    private void updateUI(Location location) {
        LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
        double currentDistance = SphericalUtil.computeDistanceBetween(currentLocation, destination);
        Toast.makeText(getContext(), "Current distance is: " + currentDistance, Toast.LENGTH_SHORT).show();
        if (currentDistance<proximity){
            // Gets an instance of the NotificationManager service
            NotificationManager mNotifyMgr = (NotificationManager) getActivity().getSystemService(getActivity().NOTIFICATION_SERVICE);
            // Builds the notification and issues it.
            mNotifyMgr.notify(mNotificationId, mBuilder.build());
            Toast.makeText(getContext(), "Entered proximity range!", Toast.LENGTH_SHORT).show();

        }

    }

    public void reachDestination(View view) {
        onPause();
    }
    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

    @Override
    public void onConnectionSuspended(int a) {
        Log.d("t", "connection suspended");
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10000);
        mLocationRequest.setFastestInterval(3000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    protected void startLocationUpdates() {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
    public void update(View view) {
        EditText firstPart = (EditText) v.findViewById(R.id.firstpart);
        EditText secondPart = (EditText) v.findViewById(R.id.secondpart);
        String first = firstPart.getText().toString();
        String second = secondPart.getText().toString();
        TextView display = (TextView) v.findViewById(R.id.display);
        display.setText(first + second);
        onResume();

    }
}

On running the app, I got a NullPointerException when it is trying to post a notification.

E/AndroidRuntime(16805): FATAL EXCEPTION: main
E/AndroidRuntime(16805): Process: com.example.something.travelapp, PID: 16805
E/AndroidRuntime(16805): java.lang.NullPointerException
E/AndroidRuntime(16805):    at android.app.Notification$Builder.applyStandardTemplate(Notification.java:1634)
E/AndroidRuntime(16805):    at android.app.Notification$Builder.makeContentView(Notification.java:1756)
E/AndroidRuntime(16805):    at android.app.Notification$Builder.buildUnstyled(Notification.java:1804)
E/AndroidRuntime(16805):    at android.app.Notification$Builder.build(Notification.java:1876)
E/AndroidRuntime(16805):    at android.support.v4.app.NotificationCompatKitKat$Builder.build(NotificationCompatKitKat.java:115)
E/AndroidRuntime(16805):    at android.support.v4.app.NotificationCompat$BuilderExtender.build(NotificationCompat.java:471)
E/AndroidRuntime(16805):    at android.support.v4.app.NotificationCompat$NotificationCompatImplKitKat.build(NotificationCompat.java:664)
E/AndroidRuntime(16805):    at android.support.v4.app.NotificationCompat$Builder.build(NotificationCompat.java:1561)
E/AndroidRuntime(16805):    at com.example.something.travelapp.UI.Tab2.updateUI(Tab2.java:125)
E/AndroidRuntime(16805):    at com.example.something.travelapp.UI.Tab2.onLocationChanged(Tab2.java:82)
E/AndroidRuntime(16805):    at com.google.android.gms.location.internal.zzk$zzb.handleMessage(Unknown Source)
E/AndroidRuntime(16805):    at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(16805):    at android.os.Looper.loop(Looper.java:212)
E/AndroidRuntime(16805):    at android.app.ActivityThread.main(ActivityThread.java:5135)
E/AndroidRuntime(16805):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(16805):    at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(16805):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
E/AndroidRuntime(16805):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
E/AndroidRuntime(16805):    at dalvik.system.NativeStart.main(Native Method)

I have no idea why there is a NullPointerException here. I'm very new to android programming and would really appreciate some help.

randy
  • 53
  • 4
  • 1
    i think `getContext()` is null in `new NotificationCompat.Builder(getContext())` – Shayan Pourvatan Nov 14 '15 at 10:05
  • You're right, the getContext() indeed is null. I've moved the NotificationCompat.Builder initialisation to the updateUI method and it worked! Thank you! – randy Nov 14 '15 at 11:12

0 Answers0