在片段内设置MapFragment

时间:2019-05-08 00:23:04

标签: java android google-maps android-fragments

我正在尝试在活动片段中设置com.google.android.gms.maps.SupportMapFragment。它在第三个片段上,但是当我尝试多种方法时,出现空指针异常。我认为解决方案位于代码内,可能位于position = 2的代码部分内?这是在地图片段显示在屏幕上时执行的代码。

我意识到这是一个空指针异常,但是解决此问题的要求是不同的,并且与普通程序不同,在普通程序中,我可以在开始时对其进行定义,并且在使用片段的情况下它可以正常工作,这会导致很多问题我

我能够将地图包含在xml中,当我访问放置在地图中的片段时,我可以看到地图并且可以与之交互,但是当我尝试以编程方式添加标记甚至初始化地图时崩溃。

我已经尝试过使用默认的地图活动中的代码来尝试地图,supportmapfragments和许多其他事情。

这是我的map_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    tools:background="@color/CafeSeaBlue"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:tools="http://schemas.android.com/tools">

    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="80dp"
        android:background="@drawable/card_background" />

    <android.support.v7.widget.AppCompatTextView
        android:id="@+id/latText1"
        android:layout_below="@+id/longText"
        android:layout_marginBottom="50dp"
        android:background="@color/White"
        android:text="Map Screen"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="84dp"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1" />

    <fragment
        class="com.google.android.gms.maps.SupportMapFragment"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="140dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="50dp"/>

</FrameLayout>

您可以看到该片段的ID为“地图”

这是我的参考活动


public class HomeActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, MyRecyclerViewAdapter.ItemClickListener, OnMapReadyCallback {


//        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
//                .findFragmentById(R.id.map);
//        mapFragment.getMapAsync(this);


    private SessionHandler session;
    private ProgressDialog pDialog;
    GoogleApiClient mGoogleApiClient;
    LocationManager mLocationManager;
    TextView tv1;
    TextView tv2;

    Double globalLong;
    Double globalLat;

    private SwipeRefreshLayout mSwipeRefreshLayout;

    private MyRecyclerViewAdapter adapter;

    Location mLastLocation;

//    private GoogleMap mMap;
//
//    private static MapView mapView;


    private static MapView mapFragment;
    private GoogleMap gmap;


    private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey";

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        final View background = findViewById(R.id.home_background_view);
        final ViewPager viewPager = (ViewPager) findViewById(R.id.home_view_pager);
        MainPagerAdapter adapter = new MainPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);



//        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
//                .findFragmentById(R.id.map);
//        mapFragment.getMapAsync(this);


        TabLayout tabLayout = (TabLayout) findViewById(R.id.am_tab_layout);
//        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        tabLayout.setupWithViewPager(viewPager);

        //call method to load the data to the feed
        loadLocations();


        //set screen to view fragment 1 (centre)
        viewPager.setCurrentItem(1);


        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                if(position == 0)
                {
                }

                }if(position == 1){

                    Button reload = (Button) findViewById(R.id.reload);

                    reload.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            //when reload icon is pressed, reload data
                            loadLocations();
                        }
                    });

                }if(position ==2){

                    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                            .findFragmentById(R.id.map);
                    mapFragment.getMapAsync(HomeActivity.this);

                    Toast.makeText(HomeActivity.this, "Position 2", Toast.LENGTH_SHORT).show();

                    onMapReady(gmap);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void loadLocations() {
        //(code removed)
        //load locations for fragment 1

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void onLocationChanged(Location location) {
        double currentLatitude = location.getLatitude();
        double currentLongitude = location.getLongitude();

        globalLat = location.getLatitude();
        globalLong = location.getLongitude();

        Log.d("Location","Longitude = "+currentLongitude);
        Log.d("Location","Latitude = "+currentLatitude);



        if(tv1 != null)
            tv1.setText(Double.toString(currentLatitude));


        if(tv2 != null)
            tv2.setText(Double.toString(currentLongitude));

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
    //progress bar
    private void displayLoader() {
        pDialog = new ProgressDialog(HomeActivity.this);
        pDialog.setMessage("Loading.. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(this, "This is item number " + adapter.getItem(position), Toast.LENGTH_SHORT).show();

    }

    @Override //saves instant state
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        Bundle mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY);
        if (mapViewBundle == null) {
            mapViewBundle = new Bundle();
            outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle);
        }

    }

    //life cycle
    @Override
    protected void onPause() {
        super.onPause();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    @Override
    public void onMapReady(GoogleMap map) {
        //mMap = googleMap;

        // Add a marker in Sydney and move the camera
//        LatLng sydney = new LatLng(-34, 151);
//        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

        //Toast.makeText(this, "some toast", Toast.LENGTH_SHORT).show();

        //mMap.setMapStyle()
//        gmap=map;
//
//        gmap.addMarker(new MarkerOptions()
//                .position(new LatLng(10, 10))
//                .title("Hello world"));

        //gmap.clear();
    }

//    void refreshItems() {
//        // Load items
//        loadLocations();
//        // Load complete
//        onItemsLoadComplete();
//    }
//
//    void onItemsLoadComplete() {
//        // Update the adapter and notify data set changed
//        // ...
//
//        // Stop refresh animation
//        mSwipeRefreshLayout.setRefreshing(false);
//    }

}

我知道我的代码很乱,如果很难阅读,对不起。

我希望能够在地图上设置标记,但是每次尝试都将其崩溃。在运行mapFragment.getMapAsync(HomeActivity.this);部分中看到的(position=2)时,出现以下错误

2019-05-08 00:58:17.485 32151-32151/im.craig.locateio E/AndroidRuntime: FATAL EXCEPTION: main
    Process: im.craig.locateio, PID: 32151
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
        at im.craig.locateio.HomeActivity$1.onPageSelected(HomeActivity.java:386)
        at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1947)
        at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:686)
        at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:670)
        at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:631)
        at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:612)
        at android.support.design.widget.TabLayout$ViewPagerOnTabSelectedListener.onTabSelected(TabLayout.java:2831)
        at android.support.design.widget.TabLayout.dispatchTabSelected(TabLayout.java:1608)
        at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1601)
        at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1569)
        at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1874)
        at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:2059)
        at android.view.View$PerformClick.run(View.java:24770)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
2019-05-08 00:58:18.140 32151-32228/im.craig.locateio W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
2019-05-08 00:58:18.150 32151-32228/im.craig.locateio I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:4
2019-05-08 00:58:18.150 32151-32228/im.craig.locateio I/DynamiteModule: Selected remote version of com.google.android.gms.googlecertificates, version >= 4
2019-05-08 00:58:18.160 32151-32228/im.craig.locateio W/zygote64: Unsupported class loader
2019-05-08 00:58:18.165 32151-32228/im.craig.locateio W/zygote64: Skipping duplicate class check due to unsupported classloader

但是,即使我尝试在它之前重新初始化,我似乎也会出现错误。

关于我的程序的另一个值得注意的事情可能是,当如上所示的if(position == 1){时,我正在那里创建一个on click监听器并在其中初始化内容,这是我需要做的才能使其正常运行。

您可能还会看到,我试图将以下代码放在没有运气的地方。

//        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
//                .findFragmentById(R.id.map);
//        mapFragment.getMapAsync(this);

0 个答案:

没有答案