简体   繁体   English

GoogleApiClient空指针异常

[英]GoogleApiClient null pointer exception

I try to learn android development and now i developing an app with fused location service. 我尝试学习Android开发,现在我正在开发一个融合位置服务的应用程序。

I got a RunFragment.java class when i want to put the GoogleMap fragment, Textviews with latitude and longitude and some other widgets. 当我想把GoogleMap片段,Textviews与纬度和经度以及其他一些小部件放在一起时,我得到了一个RunFragment.java类。 First of all i want to connect to GoogleApiClient and i created new class that will do all this job and leave RunFragment.java clear. 首先,我想连接到GoogleApiClient,我创建了一个新类,它将完成所有这些工作,并保持RunFragment.java清除。 (Is that a good idea??) When i try to run my app i got this error: (这是一个好主意??)当我尝试运行我的应用程序时,我收到此错误:

     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.content.Context.getMainLooper()' on a null object reference
        at com.google.android.gms.common.api.GoogleApiClient$Builder.<init>(Unknown Source)
        at com.runtheworld.roman.runtheworld.GoogleAPI.buildGoogleApiClient(GoogleAPI.java:28)
        at com.runtheworld.roman.runtheworld.RunFragment.onCreate(RunFragment.java:39)
        at android.app.Fragment.performCreate(Fragment.java:2031)

There is the relevant classes: 有相关的课程:

RunFragment.java RunFragment.java

package com.runtheworld.roman.runtheworld;

import android.app.Fragment;
import android.os.Bundle;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;



public class RunFragment extends Fragment  {

private static View view;

// TextViews
TextView lat,lon;

// GoogleApi
private GoogleAPI mGoogleApiClient = new GoogleAPI(getActivity());



// Default Constructor
public RunFragment() {
}


@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    mGoogleApiClient.buildGoogleApiClient();
}
@Override
public void onStart(){
    super.onStart();
    mGoogleApiClient.Connect();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (view != null) {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null)
            parent.removeView(view);
    }
    try {
        view = inflater.inflate(R.layout.run_fragment, container, false);
    } catch (InflateException e) {
        // Map already created
    }

    lat = (TextView)view.findViewById(R.id.lat);
    lon = (TextView)view.findViewById(R.id.lon);
    lat.setText(String.valueOf(mGoogleApiClient.getLat()));
    lon.setText(String.valueOf(mGoogleApiClient.getLon()));


    return view;
}




}

GoogleAPI.java GoogleAPI.java

package com.runtheworld.roman.runtheworld;


import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;

public class GoogleAPI  implements GoogleApiClient.ConnectionCallbacks,    GoogleApiClient.OnConnectionFailedListener {

private Context context;
private GoogleApiClient mGoogleApiClient;
private boolean isConnected;
// Location
Location mLastLocation;

public GoogleAPI(Context c) {
    context = c;
}


protected synchronized void buildGoogleApiClient() {
    Log.d("MYTAG", "BUILDING GOOGLE API");
    mGoogleApiClient = new GoogleApiClient.Builder(context)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

public boolean Connect(){
    if (!mGoogleApiClient.isConnected())
        mGoogleApiClient.connect();
    else
    Log.d("MYTAG","GoogleApiClient is already connected!");
    return isConnected;
}

@Override
public void onConnected(Bundle bundle) {
    Log.d("MYTAG", "GOOGLE API CONNECTED!");
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
    }
}

public double getLat(){
    return mLastLocation.getLatitude();
}
public double getLon(){
    return mLastLocation.getLongitude();
}
@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

}

Can anyone help ? 有人可以帮忙吗?

It sounds like your initial problem was fixed in the comments, here is how you can complete the functionality. 听起来您的初始问题已在评论中修复,以下是您可以如何完成功能。

First, to fix the NPE, make sure that mLocation is not null before you reference it: 首先,要修复NPE,请确保在引用之前mLocation不为null:

public double getLat(){
    double retVal = 0d;
    if (mLastLocation != null){
       retVal = mLastLocation.getLatitude();
    }
    return retVal;
}
public double getLon(){
    double retVal = 0d;
    if (mLastLocation != null){
       retVal = mLastLocation.getLongitude();
    }
    return retVal;
}

The next problem is that getLastLocation() has a high tendency to return null. 下一个问题是getLastLocation()很有可能返回null。

The best way to get around that is to register a location listener. 解决这个问题的最佳方法是注册位置监听器。

Declare GoogleAPI as a location listener: GoogleAPI声明为位置监听器:

public class GoogleAPI  implements GoogleApiClient.ConnectionCallbacks,    GoogleApiClient.OnConnectionFailedListener, LocationListener{

private Context context;
private GoogleApiClient mGoogleApiClient;
private boolean isConnected;

Then register a listener in onConnected() (see documentation : for how to set up the values for minTime , fastestTime , and distanceThreshold ): 然后在onConnected()注册一个监听器(参见文档 :关于如何设置minTimefastestTimedistanceThreshold ):

        @Override
        public void onConnected(Bundle bundle) {
            Log.d("MYTAG", "GOOGLE API CONNECTED!");
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                    mGoogleApiClient);
            if (mLastLocation == null) {
               mLocationRequest = new LocationRequest();
               mLocationRequest.setInterval(minTime);
               mLocationRequest.setFastestInterval(fastestTime);
                                 mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
              mLocationRequest.setSmallestDisplacement(distanceThreshold);
              LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            }

        }

Then add the location changed callback: 然后添加位置更改回调:

 @Override
    public void onLocationChanged(Location location) {

             mLastLocation = location;

     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM