当前位置: 首页 > 知识库问答 >
问题:

GoogleMap为v2片段返回Null

奚正谊
2023-03-14

我正在调用tabhost片段活动中的映射片段

mTabHost.addTab(mTabHost.newTabSpec("tab4").setIndicator("Commend",tabIcon4Light), Map_Locations_Fragment.class, null);
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
<fragment 
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/rg_views"
    class="com.google.android.gms.maps.SupportMapFragment"/> 
public class Map_Locations_Fragment extends Fragment implements LocationListener, LocationSource, OnMarkerClickListener, OnInfoWindowClickListener {
View inflatedView;
Context context = null;
ViewGroup group;
private ProgressDialog pd;
private String popoid;

private GoogleMap mMap;
private OnLocationChangedListener mListener;
private LocationManager locationManager;
private String phoneNumber;
private JSONObject json;
private JSONObject json2;
private JSONArray nameArray;
private JSONArray valArray;
private JSONArray valArray2 = null;
private JSONArray nameArray2;

private LatLng userLocation = null;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    if (container == null) {
        return null;
    }

    if (inflatedView != null) {
        ViewGroup parent = (ViewGroup) inflatedView.getParent();

        if (parent != null)
            parent.removeView(inflatedView);
    }

    try {
        inflatedView = inflater.inflate(R.layout.fragment_map_locations,
                container, false);
        context = getActivity().getApplicationContext();
        popoid = getActivity().getString(R.string.popoid);   
            setUpMapIfNeeded();

    } catch (InflateException e) {

    }
    return inflatedView;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

private void locationCheck() {
    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    if (locationManager != null) {
        boolean gpsIsEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        if (!gpsIsEnabled) {
            buildAlertMessageNoGps();
        } else {
            locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 5000L, 10F, this);
        }

        Location location = locationManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        double latitute, longitude = 0;
        if (location != null) {
            latitute = location.getLatitude();
            longitude = location.getLongitude();
            userLocation = new LatLng(latitute, longitude);
        }
    } else {
        // Show some generic error dialog because something must have gone
        // wrong with location manager.
    }
}

// Ask to turn on GPS in its off
private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage(
            "Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(false)
            .setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(final DialogInterface dialog,
                                final int id) {
                            startActivity(new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                        }
                    })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog,
                        final int id) {
                    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                    boolean networkIsEnabled = locationManager
                            .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                    if (networkIsEnabled) {
                        locationManager.requestLocationUpdates(
                                LocationManager.NETWORK_PROVIDER, 5000L,
                                10F, (LocationListener) getActivity());
                    }
                    dialog.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}

@Override
public void onPause() {
    if (locationManager != null) {
        locationManager.removeUpdates(this);
    }
    super.onPause();
}

@Override
public void onResume() {
    super.onResume();
    context = getActivity().getApplicationContext();
    if (Repeatables.isNetworkAvailable(context) == true) {
        locationCheck();
        setUpMapIfNeeded();
    } else {

    }
}

/**
 * Sets up the map if it is possible to do so (i.e., the Google Play
 * Services)
 */
private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the
    // map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.

        mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();

        if (isGoogleMapsInstalled()) {

            if (locationManager != null) {
                mMap.setMyLocationEnabled(true);
            }
            // Check if we were successful in obtaining the map.

            if (mMap != null) {
                // This is how you register the Location Source
                mMap.setLocationSource(this);
                setUpMap();
            }

        } else {
            Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage("Please install Google Maps");
            builder.setCancelable(false);
            builder.setPositiveButton(
                    "Install",
                    (android.content.DialogInterface.OnClickListener) getGoogleMapsListener());
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    }
}

 public void onDestroyView() {
        super.onDestroyView();
        SupportMapFragment f = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
        if (f != null){ 
            getFragmentManager().beginTransaction().remove(f).commitAllowingStateLoss();
        } 
    } 

public boolean isGoogleMapsInstalled() {
    try {
        @SuppressWarnings("unused")
        ApplicationInfo info = getActivity().getPackageManager().getApplicationInfo(
                "com.google.android.apps.maps", 0);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
}

public OnClickListener getGoogleMapsListener() {
    return new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("market://details?id=com.google.android.apps.maps"));
            startActivity(intent);

            // Finish the activity so they can't circumvent the check
            //finish();
        }
    };
}

/**
 * This is where we can add markers or lines, add listeners or move the
 * camera.
 * <p>
 * This should only be called once and when we are sure that {@link #mMap}
 * is not null.
 */
private void setUpMap() {
    mMap.setMyLocationEnabled(true);

    // Set up sat/street/reg view
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    RadioGroup rgViews = (RadioGroup) inflatedView.findViewById(R.id.rg_views);

    rgViews.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.rb_normal) {
                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            } else if (checkedId == R.id.rb_satellite) {
                mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
            } else if (checkedId == R.id.rb_terrain) {
                mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
            }
        }
    });

    // Setting a custom info window adapter for the google map
    mMap.setInfoWindowAdapter(new InfoWindowAdapter() {

        // Use default InfoWindow frame
        @Override
        public View getInfoWindow(Marker arg0) {
            return null;
        }

        // Defines the contents of the InfoWindow
        @Override
        public View getInfoContents(Marker arg0) {

            // Getting view from the layout file info_window_layout
            View v = getLayoutInflater(getArguments()).inflate(R.layout.map_popup, null);

            // Getting the position from the marker
            // LatLng latLng = arg0.getPosition();

            // Getting reference to the TextView to set latitude
            TextView tvTitle = (TextView) v.findViewById(R.id.popTitle);

            // Getting reference to the TextView to set longitude
            TextView tvSnippet = (TextView) v.findViewById(R.id.popSnippet);

            StringTokenizer tokens = new StringTokenizer(arg0.getSnippet(),
                    ":");
            String address = tokens.nextToken();
            phoneNumber = tokens.nextToken();

            if (phoneNumber.equals("0")) {
                ((Button) v.findViewById(R.id.btnCall))
                        .setVisibility(View.GONE);
            } else {
                ((Button) v.findViewById(R.id.btnCall))
                        .setVisibility(View.VISIBLE);
            }

            tvTitle.setText((arg0.getTitle()));

            tvSnippet.setText(address);

            // Returning the view containing InfoWindow contents
            return v;

        }
    });

    new MoveOutOfUIthread().execute();

    mMap.setOnInfoWindowClickListener(this);
    mMap.setOnMarkerClickListener(null);

}

@Override
public void activate(OnLocationChangedListener listener) {
    mListener = listener;
}

@Override
public void deactivate() {
    mListener = null;
}

@Override
public void onLocationChanged(Location location) {
    if (mListener != null) {
        mListener.onLocationChanged(location);
        userLocation = new LatLng(location.getLatitude(),
                location.getLongitude());

        // Zoom to users location
        // mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(
        // location.getLatitude(), location.getLongitude())));
    }
}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub
    // Toast.makeText(this, "provider disabled", Toast.LENGTH_SHORT).show();
}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
    // Toast.makeText(this, "provider enabled", Toast.LENGTH_SHORT).show();
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
    // Toast.makeText(this, "status changed", Toast.LENGTH_SHORT).show();
}

// What happens when the pop box is clicked.
@Override
public void onInfoWindowClick(Marker marker) {
    // TODO Auto-generated method stub
    Log.e("InfoWindow", "Click");
    Intent i = new Intent(Intent.ACTION_DIAL);
    String p = "tel:" + phoneNumber;
    i.setData(Uri.parse(p));
    startActivity(i);
}

// What happens when the pin is clicked other than the pop up box.
@Override
public boolean onMarkerClick(Marker marker) {
    // TODO Auto-generated method stub
    Log.e("Marker", "Click");
    return false;
}

private class MoveOutOfUIthread extends AsyncTask<Void, Void, Void> {
    ProgressDialog dialogLoadingPins = new ProgressDialog(getActivity());

    @Override
    public void onPreExecute() {
        this.dialogLoadingPins.setMessage("Loading Map Pins...");
        this.dialogLoadingPins.show();
    }

    protected Void doInBackground(Void... unused) {
        // your background task here

        String resultURL = Repeatables
                .queryRESTurl("my url goes here");
        try {
            json = new JSONObject(resultURL);

            nameArray = json.names();

            valArray = json.toJSONArray(nameArray);

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(Void unused) {
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        try {
            String TITLE = null;
            String SNIPPET = null;
            for (int i = 0; i < valArray.length(); i++) {

                json2 = new JSONObject(valArray.getString(i));
                nameArray2 = json2.names();

                valArray2 = json2.toJSONArray(nameArray2);
                TITLE = valArray2.getString(0);
                SNIPPET = valArray2.getString(1);
                final LatLng newCords = new LatLng(valArray2.getDouble(3),
                        valArray2.getDouble(2));

                mMap.addMarker(new MarkerOptions()
                        .position(newCords)
                        .title(TITLE)
                        .snippet(SNIPPET)
                        .icon(BitmapDescriptorFactory           .defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));


                builder.include(newCords);
            }
            // builder.include(userLocation);
            // Set Zoom to Markers
            LatLngBounds bounds = builder.build();
            int padding = 30; // offset from edges of the map in pixels
            CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds,
                    padding);
            mMap.moveCamera(cu);

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

        if (dialogLoadingPins.isShowing()) {
            dialogLoadingPins.dismiss();
        }
    }
}    

}

共有1个答案

夹谷腾
2023-03-14

您应该将MapView小部件添加到布局中,如下所示:

<com.google.android.gms.maps.MapView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

然后从MapView对象获取googleMap引用:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.map_fragment_layout,
    container, false);

    mMapView = (MapView) rootView.findViewById(R.id.map);
    mMapView.onCreate(savedInstanceState);

    imageCompass = (ImageView) rootView.findViewById(R.id.mapImageCompass);

    googleMap = mMapView.getMap();

    return rootView;
}
 类似资料:
  • 为什么我得到空指针异常?有什么想法吗?

  • 我在过去的两个小时里一直在试图解决这个问题。试过很多东西。 该片段似乎正在向我的适配器传递空上下文。我尝试在onCreate和onCreateView和onActivityCreated中初始化上下文变量。同样的结果。

  • 我有一个包含框架布局的活动,片段A托管在这里与一起。 此片段A托管了另外两个包含回收器视图的片段——使用< code > fragmentstatepageradar 的片段A1和片段A2。此时,我能够在片段A1和A2中使用< code > getSupportFragmentManager()获得父片段。 单击A1和A2中的回收器视图项会产生另一个片段,比如片段B,它会替换片段A并将其添加到ba

  • 我正在开发一个android应用程序,它有一个活动。该活动有一个ViewPager,它使用FragmentStatePagerAdapter加载两个片段。 正在活动的onResume方法上重新创建此适配器。 那是内存溢出错误吗?为什么getActivity()方法在片段似乎被正确加载的情况下返回null? 提前谢谢你

  • 正如您在onCreate方法中看到的,我在“片段”列表的第0个片段上调用了getView。它返回null。我试着在代码中加入一个计时器,让它每秒运行一次,并检查视图是否为空。在计时器的第二个滴答声中,视图不为空。大体上 主要活动。JAVA 空白碎片。JAVA

  • 在Android中,当我们用一个新的片段替换容器视图时,我们可以使用replace()和addToBackStack(),因此按下back按钮就可以转到上一个片段。 但如果出现以下情况怎么办: 在Activity1中,我可以按下back按钮从fragment2转到fragment1。但当fragment2启动另一个活动时,从Activity2按下back按钮,它会将我带到Activity1中的fr