1

我在将新对象从 util 类实例化为片段类时遇到问题。实例化需要传递上下文,但我无法获取上下文。

我尝试通过 getActivity() 但仍然收到 GpsAssist.getLatitude 的 NULL POINTER EXCEPTION(因为这是第一个被调用的)错误。

我正在尝试从 GpsAssist 调用方法 getLatitude() 和 getLongitude()

下面是我的代码。可以使用所有的帮助。

谢谢

MapsActivity 类:

 public class MapsActivity extends Fragment {


GoogleMap map;
private View view;
GpsAssist gAssist = new GpsAssist(getActivity());
double  lat = gAssist.getLatitude();
double lng = gAssist.getLongitude();


private final LatLng MOUNTAIN_VIEW = new LatLng(lat, lng);

private LatLngBounds loc = new LatLngBounds(new LatLng(37, -121), new LatLng(37,-121));

public void get(){


}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {



    View view = inflater.inflate(R.layout.map_test, container, false);

    if(map == null){
        map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
        map.addMarker(new MarkerOptions().position(MOUNTAIN_VIEW).title("Marker"));
        map.animateCamera(CameraUpdateFactory.newCameraPosition(posi()));

    }else{

        //map.moveCamera(CameraUpdateFactory.newLatLngBounds(loc, 15));

    }


    return view;
}
public CameraPosition posi(){
    CameraPosition posi = new CameraPosition.Builder()
    .target(MOUNTAIN_VIEW)
    .zoom(17)
    .build();
    return posi;
}




@Override
public void onDestroyView() {
       try{
            SupportMapFragment fragment = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map));
                FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                ft.remove(fragment);
                ft.commit();
                //map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
              }catch(Exception e){
              }
            super.onDestroyView();
}







}

我的 GpsAssist 课程:

  public class GpsAssist extends Service  {


//Primitive declarations
private double lat;
private double lng;
private String provider;

//Class instances
private Context context;
private Geocoder gCoder;
Location location;


public GpsAssist(Context context){

    this.context = context;
}


//Checking if GPS is enabled

LocationManager lManager;

public Location gpsConnected(){

    lManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    boolean gpsEnabled = lManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    boolean networkEnabled = lManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);



    if(! gpsEnabled && ! networkEnabled ){

    Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivity(i);
    }else {


         location = lManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);



        if(location != null){

             lat = getLatitude();
             lng = getLongitude();

            Toast t = Toast.makeText(context, "Your location" + lat + " " + lng, Toast.LENGTH_SHORT);
            t.show();

            String addresses = getAddress(lat, lng, 2);
            Toast address = Toast.makeText(context, addresses, Toast.LENGTH_LONG);
            address.show();


        }else{

            Toast t = Toast.makeText(context, "Cannot get your location", Toast.LENGTH_SHORT);
            t.show();
        }

    }
    return location;
}

//Method to find the best possible provider
public String getProvider(){

    Criteria criteria = new Criteria();
    //true means that only enabled providers will be returned
    provider = lManager.getBestProvider(criteria, true);

    return provider;
}

public double getLatitude(){
    lat = location.getLatitude();
    return lat;
}

public double getLongitude(){
    lng = location.getLongitude();
    return lng;
}

public String getAddress(double lat, double lng, int maxR){

    String addres = "";
    gCoder = new Geocoder(context, Locale.getDefault());
    try {
    List<Address> address = gCoder.getFromLocation(lat, lng, maxR);

        if(address != null){

            Address adName = address.get(0);

            StringBuilder str = new StringBuilder("Address: \n");
            for(int i=0; i<adName.getMaxAddressLineIndex(); i++){
                str.append(adName.getAddressLine(i)).append("\n");
            }
            addres = str.toString();
            System.out.println(addres);
        }else{

             addres = "Address is null";
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
4

2 回答 2

2

在服务中,您可以仅将this其用作上下文,而无需为其提供上下文。

你也使用了错误的服务。服务是由意图启动的,而不是通过创建新对象

于 2013-09-27T14:58:11.990 回答
0

查看 GpsAssist 类的代码,getLatitude() 和 getLongitude() 引用了 location 实例变量,看起来该变量仅由 gpsConnected() 调用填充。由于您尚未调用 gpsConnected(),因此 location 将为空,从而导致您的空指针异常。您可以在 onCreate 中调用 gpsConnected() 并在调用 gpsConnected() 之后移动调用 getLatitude() 和 getLongitude()

于 2013-09-27T15:02:40.037 回答