自定义类,它应该返回一个位置但返回null位置

时间:2016-07-22 20:52:35

标签: java android location

我创建了一个LocationBuddy类,负责为我需要的所有其他片段和活动提供位置。我在片段中创建了这个类的实例,然后调用方法getUpdatedLocation()来接收该位置。 问题是getUpdatedLocation方法在LocationBuddy类之外调用时返回null,我认为我已经初始化了一切。

LocationBuddy Class

public class LocationBuddy implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
{
 GoogleApiClient client;
 Context context;

// Private instance variables
private Location updatedLocation;
private boolean clientConnected = false;
private boolean locationUpdated = false;
private int updateInterval;
private final static String TAG = "LocationBuddy";
private String lastUpdateTime;
private Location lastLocation;

// Create the LocationBuddy Object and initialize it with the current context
public LocationBuddy (Context c, int milliseconds)
{
    this.context = c;
    this.updateInterval = milliseconds;
    this.updatedLocation = null;
    this.lastLocation = null;
    Log.d(TAG, "LocationBuddy created with an update Interval of "+updateInterval+" milliseconds.");
}



// Google Location methods

@Override
public void onConnected(@Nullable Bundle bundle)
{
    lastLocation = LocationServices.FusedLocationApi.getLastLocation(client);
    if (lastLocation != null)
    {

        updatedLocation = lastLocation;

    }
    // Create a location request called locationRequest
    LocationRequest locationRequest = LocationRequest.create();


    // Set it's priority to high accuracy
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    // Set it to update to an interval set on object creation
    locationRequest.setInterval(updateInterval);

    // If another app is requesting location updates
    locationRequest.setFastestInterval(updateInterval);

    // Call requestLocationUpdates in the Api with this request
    LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);





}

@Override
public void onConnectionSuspended(int i)
{
    Log.d(TAG, "The Google API client has been suspended");
}

@Override
public void onLocationChanged(Location location)
{
    Log.d(TAG, "The location has been changed to " + location.toString());
    locationUpdated = true;
    lastLocation = location;
    updatedLocation = lastLocation;

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
{

}

// Public Methods
public void initialize()
{

    // Build the GoogleApi Client
    client = new GoogleApiClient.Builder(context)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    connectToGoogleApiClient();

}




public void connectToGoogleApiClient()
{
    client.connect();
    clientConnected = true;
}

public void disconnectFromGoogleApiClient()
{
    client.disconnect();
    clientConnected = false;
}



public String statusReport()
{
    return "Location Buddy: Client connected: "+clientConnected+", Location updated: "+locationUpdated+", Update interval: "+updateInterval;
}

public Location getUpdatedLocation()
{
    return updatedLocation;
}

public int getUpdateInterval()
{
    return updateInterval;
}



public boolean isLocationUpdated()
{

    return locationUpdated;
}

public boolean isClientConnected()
{
    return clientConnected;
}

// Return a String description of this instance
public String toString()
{
    return "LocationBuddy[updatedLocation=" + updatedLocation + ",interval=" + updateInterval + ", clientConnected="+clientConnected+ ", locationUpdated="+locationUpdated+"]";
}

}

这是使用此LocationBuddy对象的PackageListFragment.java类的片段。

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    courier = new Courier(getContext());
    buddy = new LocationBuddy(getContext(), 1000);
    buddy.initialize();

}

这是从PackageListFragment类

中的OnActivityCreated方法调用的
currentLocation = buddy.getUpdatedLocation();

这是logcat的错误:

07-22 16:13:24.351 27538-27538/com.shipwebsource.courier E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.shipwebsource.courier, PID: 27538
                                                                       java.lang.NullPointerException
                                                                           at com.shipwebsource.courier.Extras.LocationBuddy.getUpdatedLocation(LocationBuddy.java:146)
                                                                           at com.shipwebsource.courier.PackageListFragment.onActivityCreated(PackageListFragment.java:306)
                                                                           at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1983)
                                                                           at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1092)
                                                                           at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
                                                                           at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
                                                                           at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
                                                                           at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
                                                                           at android.os.Handler.handleCallback(Handler.java:733)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:136)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                                           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:785)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                                             at dalvik.system.NativeStart.main(Native Method)
07-22 16:13:26.119 27538-28841/com.shipwebsource.courier  D/dalvikvm:GC_FOR_ALLOC freed 1427K, 18% free 7077K/8620K, paused 8ms, total 8ms

1 个答案:

答案 0 :(得分:0)

您永远不会将client变量设置为任何内容。在您设置其他内容之前(我可以告诉您),它只会被创建并且永远不会分配给新的GoogleApiClient。