在Fragment中侦听位置导致NullPointerException

时间:2015-11-14 10:02:56

标签: java android android-fragments nullpointerexception

项目最初有一个实现LocationListener以侦听用户位置的活动。我们的团队决定更改UI以在MainActivity中使用滑动选项卡布局,以便每个选项卡都将替换我们之前的活动。

所以我做的是将LocationListening活动中的代码复制并粘贴到选项卡片段中,并通过替换'这个'进行一些更改以放置需要上下文的位置。与' getContext()'。

这是标签片段的完整代码。

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

    }
}

在运行应用程序时,我在尝试发布通知时遇到了NullPointerException。

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)

我不知道为什么这里有NullPointerException。我对android编程非常陌生,非常感谢你的帮助。

0 个答案:

没有答案