在Android google maps api v2中从MapFragment到Fragment的类Cast Exception

时间:2014-09-09 21:41:46

标签: android google-maps classcastexception android-maps-v2 mapfragment

好吧,我在这里试图让这个应用程序由导航抽屉和地图片段组成。 我的目标是点击导航抽屉中的一个项目,它会将您带到地图上的指定坐标。 但是当我尝试访问我的地图片段的方法onClick导航抽屉项目时,我遇到了这个Class Cast异常。

这是我的地图片段......

  interface receiveData{

public void navigateToNewLocation(double lat, double lon);}
public class MAPFragment extends Fragment implements receiveData {

public  String IMAGE_RESOURCE_ID = "iconResourceID";
public  String ITEM_NAME = "itemName";
public  String GEO = "39.933333,32.866667";

public void setParameters(double lat, double lon){
    navigateToNewLocation(lat, lon);
}
// Google Map
private GoogleMap googleMap;
  ImageView ivIcon;
  TextView tvItemName;
  MapView mapView;


  String[] coords = GEO.split(",");
  Double c1 = new Double(Double.valueOf(coords[0]));
  Double c2 = new Double(Double.valueOf(coords[1]));

  public MAPFragment() {

  }

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

        View view = inflater.inflate(R.layout.fragment_layout_one, container,
                    false);
        Log.e("coords[0]",coords[0]);

        try {
            // Loading map
            initilizeMap();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return view;
  }


 /**
   * function to load map. If map is not created it will create it for you
   * */
  public void initilizeMap() {
      if (googleMap==null){
        googleMap=((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);
        googleMap.getUiSettings().setRotateGesturesEnabled(true);
        googleMap.setMyLocationEnabled(true);

        Log.e("In MAPFragment","Before coords!=null");


        googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(c1,c2)));


          LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
          Criteria criteria = new Criteria();
          String provider = locationManager.getBestProvider(criteria, true);
          Location location = locationManager.getLastKnownLocation(provider);

          if(location!=null){
              onLocationChanged(location);
          }

          googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

              @Override
              public void onMyLocationChange(Location arg0) {
                  // TODO Auto-generated method stub             
              }
          });

        //checking
        if(googleMap==null){
            Toast.makeText(getActivity().getApplicationContext(), "Unable to create", Toast.LENGTH_SHORT).show();
        }
    }
  }

  @Override
  public void onResume() {
      super.onResume();
      initilizeMap();
  }

  public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub
     // Getting latitude of the current location
      double latitude = location.getLatitude();

      // Getting longitude of the current location
      double longitude = location.getLongitude();

      // Creating a LatLng object for the current location
      LatLng latLng = new LatLng(latitude, longitude);

      // Showing the current location in Google Map
      googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

      // Zoom in the Google Map
      googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

}

  @Override
  public void onDestroyView()
  {
      super.onDestroy();
    mapView.onDestroy();
      }

  public void navigateToNewLocation(double lat, double lon){

      Log.e("INSIDE navigateToNewLoc","next is cam pos");
        // On clicking a user       
        CameraPosition cameraPosition = new CameraPosition.Builder().target(
                new LatLng(lat,lon)).zoom(12).build();
         Log.e("INSIDE navigateToNewLoc","next is animateCam");
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

  }
}

这是我的方法,用于配置MAinActivity中导航抽屉中的项目

public void SelectItem(int possition) {

    Fragment fragment = null;
    Bundle args = new Bundle();

    fragment = new MAPFragment();


Log.e("In main activity","Lets see what happens");



String[] coords = dataList.get(possition).getGeo().split(",");
Double c1 = new Double(Double.valueOf(coords[0]));
Double c2 = new Double(Double.valueOf(coords[1]));



    fragment.setArguments(args);



    FragmentManager frgManager = getFragmentManager();
    final Fragment existingFragment = frgManager.findFragmentById(R.id.map);


    if(existingFragment !=null){

        ((receiveData)existingFragment).navigateToNewLocation(c1,c2);
    }
    else
     frgManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

    mDrawerList.setItemChecked(possition, true);
    setTitle(dataList.get(possition).getItemName());
    mDrawerLayout.closeDrawer(mDrawerList);

}

这是我的日志猫

  09-10 03:00:00.784: E/AndroidRuntime(31030): FATAL EXCEPTION: main
  09-10 03:00:00.784: E/AndroidRuntime(31030): Process: com.findmeWithdrawer, PID: 31030
  09-10 03:00:00.784: E/AndroidRuntime(31030): java.lang.ClassCastException:         com.google.android.gms.maps.MapFragment cannot be cast to com.findmeWithdrawer.receiveData
  09-10 03:00:00.784: E/AndroidRuntime(31030):  at       com.findmeWithdrawer.MainActivity.SelectItem(MainActivity.java:205)

2 个答案:

答案 0 :(得分:0)

您正在向界面投射片段。这是不可能的。

您希望将其强制转换为实现该界面的MAPFragment类:

((MAPFragment)existingFragment).navigateToNewLocation(c1,c2);

这是因为类MAPFragment实现了receiveData接口,其中包含您所需的navigateToNewLocation方法。

答案 1 :(得分:0)

  

您正在向界面投射片段。这是不可能的。   事实并非如此,您可以将类强制转换为接口。没关系。

查看包名称 com.google.android.gms.maps.MapFragment 原始谷歌地图片段无法转换为您的界面。这是问题。