初始化时android映射给出错误

时间:2016-02-01 18:57:54

标签: java android xml

java.lang.RuntimeException:无法启动活动ComponentInfo {in.jainrishabh.noteelite / in.jainrishabh.noteelite.MapView}:java.lang.NullPointerException:尝试调用虚方法'void com.google.android.gms空对象引用上的.maps.GoogleMap.setOnMapClickListener(com.google.android.gms .maps.GoogleMap $ OnMapClickListener)'

任何人都知道我为什么会得到NullPointer异常

GoogleMap googleMap;
SharedPreferences sharedPreferences;
int locationCount = 0;
private ArrayList<UserDetailsPojo> pojoArrayList;
private float latia;
private float longia;
private Editor editor;

SharedPreferences prefs;
float lat;
float lng;

String lat_temp;
String long_temp;

private ListView userNamesListView;
private ListAdapter userListAdapter;

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

    prefs = this.getSharedPreferences("sharedpref", Context.MODE_PRIVATE);

    latia = prefs.getFloat("latitude", -34);
    longia = prefs.getFloat("longitude", 151);

    LatLng myLocation = new LatLng(latia, longia);

    pojoArrayList = new ArrayList<UserDetailsPojo>();

    // For the third argument, we need a List that contains Strings.
    //We decided to display undergraduates names on the ListView.
    //Therefore we need to create List that contains undergraduates names
    userListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());

    //Toast.makeText(getApplicationContext(), "lati is:"+latia, Toast.LENGTH_LONG).show();
    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();

    }else { // Google Play Services are available

        // Getting reference to the SupportMapFragment of activity_main.xml
        MapFragment fm = (MapFragment) getFragmentManager().findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);

        // Opening the sharedPreferences object
        sharedPreferences = getSharedPreferences("location", -34);

        // Getting number of locations already stored
        locationCount = sharedPreferences.getInt("locationCount", 151);

        // Getting stored zoom level if exists else return 0
        String zoom = sharedPreferences.getString("zoom", "0");

        // If locations are already saved
        if(locationCount!=0){

            String lat = "";
            String lng = "";

            // Iterating through all the locations stored
            for(int i=0;i<locationCount;i++){

                // Getting the latitude of the i-th location
                lat = lat_temp;


                // Getting the longitude of the i-th location
                lng = long_temp;

                // Drawing marker on the map
                drawMarker(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng)));
            }

            // Moving CameraPosition to last clicked position
            googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng))));

            //googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 13));
            // Setting the zoom level in the map on last position  is clicked
            googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        }
    }

    googleMap.setOnMapClickListener(new OnMapClickListener() {

        @Override
        public void onMapClick(LatLng point) {
            locationCount++;

            // Drawing marker on the map
            drawMarker(point);

            /** Opening the editor object to write data to sharedPreferences */
            SharedPreferences.Editor editor = sharedPreferences.edit();

            // Storing the latitude for the i-th location
            editor.putString("lat"+ Integer.toString((locationCount-1)), Double.toString(point.latitude));

            // Storing the longitude for the i-th location
            editor.putString("lng"+ Integer.toString((locationCount-1)), Double.toString(point.longitude));

            // Storing the count of locations or marker count
            editor.putInt("locationCount", locationCount);

            /** Storing the zoom level to the shared preferences */
            editor.putString("zoom", Float.toString(googleMap.getCameraPosition().zoom));

            /** Saving the values stored in the shared preferences */
            editor.commit();

            Toast.makeText(getBaseContext(), "Marker is added to the Map", Toast.LENGTH_SHORT).show();

        }
    });

    googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {
        @Override
        public void onMapLongClick(LatLng point) {

            // Removing the marker and circle from the Google Map
            googleMap.clear();

            // Opening the editor object to delete data from sharedPreferences
            SharedPreferences.Editor editor = sharedPreferences.edit();

            // Clearing the editor
            editor.clear();

            // Committing the changes
            editor.commit();

            // Setting locationCount to zero
            locationCount=0;

        }
    });
}

private void drawMarker(LatLng point){
    // Creating an instance of MarkerOptions
    MarkerOptions markerOptions = new MarkerOptions();

    // Setting latitude and longitude for the marker
    markerOptions.position(point);

    // Adding marker on the Google Map
    googleMap.addMarker(markerOptions);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public List<String> populateList(){

    // We have to return a List which contains only String values. Lets create a List first
    List<String> userNamesList = new ArrayList<String>();

    // First we need to make contact with the database we have created using the DbHelper class
    AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);

    // Then we need to get a readable database
    SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();

    // We need a a guy to read the database query. Cursor interface will do it for us
    //(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
    Cursor cursor = sqliteDatabase.query(AndroidOpenDbHelper.TABLE_USER, null, null, null, null, null, null);
    // Above given query, read all the columns and fields of the table

    startManagingCursor(cursor);

    // Cursor object read all the fields. So we make sure to check it will not miss any by looping through a while loop
    while (cursor.moveToNext()) {
        // In one loop, cursor read one undergraduate all details
        // Assume, we also need to see all the details of each and every undergraduate
        // What we have to do is in each loop, read all the values, pass them to the POJO class
        //and create a ArrayList of undergraduates



        //int Time = cursor.getInt(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_TIME));
        double latia = cursor.getDouble(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_LATI));
        double longia = cursor.getDouble(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_LONGI));

        // Finish reading one raw, now we have to pass them to the POJO
        UserDetailsPojo ugPojoClass = new UserDetailsPojo();
        ugPojoClass.setLati(latia);
        ugPojoClass.setLongi(longia);

// Lets pass that POJO to our ArrayList which contains undergraduates as type
        pojoArrayList.add(ugPojoClass);

        lat_temp = Double.toString(latia);
        long_temp = Double.toString(longia);
        Log.d("latis1",lat_temp);
        Log.d("longis1",long_temp);


    }

    // If you don't close the database, you will get an error
    //  sqliteDatabase.close();

    return userNamesList;
}

}

  

块引用

<fragment
    android:id="@+id/map"
    android:layout_width="wrap_content"
    android:layout_height="700dp"
    android:layout_weight="4"
    android:name="com.google.android.gms.maps.MapFragment"
     />

这是我的Mapview XML

1 个答案:

答案 0 :(得分:0)

您可能在实例化之前引用了googleMap变量。尝试更改第一行的GoogleMap googleMap;
相反。
GoogleMap googleMap = new GoogleMap();
此外,请务必在else案例中设置setOnMapClickListener,以使其按预期工作。如果地图对象不存在(即Google Play服务不可用),您也不想设置事件监听器。