将上下文传递给片段

时间:2013-09-27 14:51:58

标签: android android-fragments

我遇到一个问题,将一个新对象从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();
    }

2 个答案:

答案 0 :(得分:2)

在服务中你可以使用this作为上下文,你不需要给它上下文。

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

答案 1 :(得分:0)

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