在MapView中使用底部表格时出错,要怎么处理

来源:爱站网时间:2021-09-29编辑:网友分享
爱站技术小编创建了一个MapView,其中我使用了从数据库调用的经度和纬度来绘制多个标记,在MapView中使用底部表格时出错,那么要怎么处理这个问题呢?小编用一篇文章详细的告诉大家。

问题描述


在MapView中使用底部表格时出错,那么要怎么处理这个问题呢?

现在,我要在单击此标记时显示底页并在工作表上显示特定数据。我从这里Slide in view from bottom over Google Map on Marker click

获得了一些关于底片的参考

但是实现本文后,我得到一个错误

错误是

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: part.time.job.v2, PID: 4236
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.bottomsheet.BottomSheetBehavior.setPeekHeight(int)' on a null object reference
        at part.time.job.v2.LabourFragment.onCreateView(LabourFragment.java:115)

这是我的JAVA代码

package part.time.job.v2;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.PlaceLikelihood;
import com.google.android.libraries.places.api.net.FindCurrentPlaceRequest;
import com.google.android.libraries.places.api.net.FindCurrentPlaceResponse;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.maps.android.ui.IconGenerator;

import java.util.Arrays;
import java.util.List;

import model.Jobpost;

import static com.android.volley.VolleyLog.TAG;


/**
 * A simple {@link Fragment} subclass.
 */
public class LabourFragment extends Fragment  implements OnMapReadyCallback {
    private GoogleMap mGoogleMap;
    private MapView mMapview;
    private int STORAGE_PERMISSION_CODE = 1;
    private CameraPosition mCameraPosition;
    private FusedLocationProviderClient mFusedLocationProviderClient;

    private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);
    private static final int DEFAULT_ZOOM = 15;
    private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
    private boolean mLocationPermissionGranted;

    private Location mLastKnownLocation;
    Dialog myDialog;
    private BottomSheetBehavior bottomSheetBehavior;
    private View bottomSheet;


    // Keys for storing activity state.
    private static final String KEY_CAMERA_POSITION = "camera_position";
    private static final String KEY_LOCATION = "location";

    // Used for selecting the current place.
    private static final int M_MAX_ENTRIES = 5;
    private String[] mLikelyPlaceNames;
    private String[] mLikelyPlaceAddresses;
    private List[] mLikelyPlaceAttributions;
    private LatLng[] mLikelyPlaceLatLngs;
    private PlacesClient mPlacesClient;

    public LabourFragment() {
        // Required empty public constructor
    }

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



        if (savedInstanceState != null) {
            mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
            mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
        }
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_labour, container, false);
//        myDialog = new Dialog(getActivity());
        bottomSheet = view.findViewById(R.id.bottom_sheet);
        bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);  //error occur on this line
        bottomSheetBehavior.setPeekHeight(200);
        bottomSheetBehavior.setHideable(true);
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);


        Places.initialize(getActivity(), getString(R.string.google_maps_key));
        mPlacesClient = Places.createClient(getActivity());


        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());


        return view;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        if (mGoogleMap != null) {
            outState.putParcelable(KEY_CAMERA_POSITION, mGoogleMap.getCameraPosition());
            outState.putParcelable(KEY_LOCATION, mLastKnownLocation);
            super.onSaveInstanceState(outState);
        }
    }

    @Override
    public void onViewCreated(@NonNull View view,  Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mMapview = (MapView) view.findViewById(R.id.mapView);

        if (mMapview!=null){
            mMapview.onCreate(null);
            mMapview.onResume();
            mMapview.getMapAsync(this);
        }
    }



    @Override
    public void onMapReady(final GoogleMap googleMap) {

        mGoogleMap=googleMap;

        FirebaseFirestore mDatabase = FirebaseFirestore.getInstance();
        CollectionReference mOrderRef = mDatabase.collection("Job Post1");

        mOrderRef.get().addOnSuccessListener(new OnSuccessListener() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                for(QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
                    if(documentSnapshot.contains("lat") && documentSnapshot.contains("lon")) {
                        String lat = (String) documentSnapshot.get("lat");
                        String lon = (String) documentSnapshot.get("lon");
                        final String title = (String) documentSnapshot.get("title");
                        final String jobdate = (String) documentSnapshot.get("jobdate");
                        final String time = (String) documentSnapshot.get("time");



                            if(lat != null && lon != null && !lat.isEmpty() && !lon.isEmpty()) {
                            double latitude = Double.parseDouble(lat.trim());
                            double longitude = Double.parseDouble(lon.trim());
                            IconGenerator iconGen = new IconGenerator(getActivity());

                            googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.fromBitmap(iconGen.makeIcon(title))));
                            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 18.0f));



                          googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                              @Override
                              public boolean onMarkerClick(Marker marker) {
                                  updateBottomSheetContent(marker);
                                  return false;
                              }
                          });
                                googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
                                    @Override
                                    public void onMapClick(LatLng latLng) {
                                        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                                    }
                                });
                        }

                    }
                }

            }

        });



    }

    private void updateBottomSheetContent(Marker marker) {
        TextView name = (TextView) bottomSheet.findViewById(R.id.detail_name);
        name.setText(marker.getTitle());
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
    }


}

xml视图

bottom_sheet xml

思路:


您的xml中没有具有“ R.id.bottom_sheet” id的视图,但是您试图通过findViewbyIdId()获取视图,这就是为什么bottomSheet变量具有null值,而且bottomsheetbehaviour值也为null并产生null指针的原因尝试访问其上的任何方法时发生异常。在您的情况下,以下行:

 

bottomSheetBehavior.setPeekHeight(200);

 

以上内容就是爱站技术频道小编为大家分享的在MapView中使用底部表格时出错,要怎么处理,看完以上分享之后,大家应该都知道出现这种问题要怎么处理了吧。

上一篇:对于Apache poi折线图,如何使第一列不在y轴上显示?

下一篇:AWS s3在部署并在本地工作后未使用MultipartFile并且无法正常工作将文件上传到tomcat服务器,怎么办?

相关阅读

热门软件源码

最新软件源码下载