Хорошо, здесь я пытаюсь сделать это приложение состоящим из ящика навигации и фрагмента карты. Моя цель - щелкнуть элемент в навигационном ящике, и он перенесет вас к указанным координатам на карте. Но я встречаю это исключение класса Cast, когда пытаюсь получить доступ к методу моего фрагмента карты onClick элемента навигационного элемента.Класс Cast Exception from MapFragment to Fragment in android google maps api v2
Вот мой фрагмент карты ...
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);
}
Вот мой журнал Cat
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)
где ваш mainactivity – sunil
я предоставил вам способом по MainActivity, откуда возникает проблема ... Я думаю, что изгоняются быть Enuff –
Можно выделить, что эта проблема существует в этой линии ((receiveData) existingFragment) .navigateToNewLocation (с1, с2); –