Java.lang.NullPointerException:在null对象引用上的moveCamera(cameraUpdate)

时间:2016-11-28 08:27:20

标签: java android

开发GPS追踪器应用程序。我在这个应用程序中使用了片段找到我自己我放了一个mylocation按钮,将我重定向到MapFragment文件。但是我在moveCamera(cameraUpdate)上得到了NullPointerException

我的错误如下:

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.moveCamera(com.google.android.gms.maps.CameraUpdate)' on a null object reference
at aark.co.in.locateme.fragments.MapFragment.onCreateView(MapFragment.java:217)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2074)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1286)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:758)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1671)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:532)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)

这里是mapFragment.java代码。

   public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle
        savedInstanceState){
            View rootview = inflater.inflate(R.layout.fragment_map, container, false);
            // Getting a reference to the AutoCompleteTextView
            mMapView = (MapView) rootview.findViewById(R.id.maps);
            mMapView.getMapAsync(onMapReadyCallback);
            mMapView.onCreate(savedInstanceState);
            dbHelper = new SQLiteHandler(getActivity());
          //   MapView mapView;
          //  ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.mapToday)).getMapAsync(onMapReadyCallback);
          //  SupportMapFragment mapFragment ;
           // ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(onMapReadyCallback);
           // ((MapView) getSupportFragmentManager().findFragmentById(R.id.maps))


          // MapsInitializer.initialize(getActivity().getApplicationContext());
           FloatingActionButton fab = (FloatingActionButton) rootview.findViewById(R.id.fabChat);
            fab.setOnClickListener(new View.OnClickListener() {


               // @Contract("_, null -> null") — method returns null if its second argument is null @Contract("_, null -> null; _, !null -> !null") — method returns null if its second argument is null and not-null otherwise @Contract("true -> fail") — a typical assertFalse method which throws an exception if true is passed to it

                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), AddUserMapActivity.class);
                    startActivity(intent);
                }
            });

//        FloatingActionButton fabnav= (FloatingActionButton) rootview.findViewById(R.id.fabNav);
//        fabnav.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                showDistance();
//            }
//        });

            mMapView.onResume();// needed to get the map to display immediately

            //       try {
            //           MapsInitializer.initialize(getActivity().getApplicationContext());
            //       } catch (Exception e) {
            //           e.printStackTrace();
            //       }


            // latitude and longitude
            //Getting Current Location Here
            GPSTracker mGPS = new GPSTracker(getActivity());
            if (!mGPS.canGetLocation()) {
                mGPS.showSettingsAlert();
            } else {
                latitude = mGPS.getLatitude();
                longitude = mGPS.getLongitude();
            }

            if (latitude != 0.0 && longitude != 0.0) {
                // create marker
                MarkerOptions marker = new MarkerOptions().position(
                        new LatLng(latitude, longitude)).title("You");
                marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
                if (marker != null) {
                    // adding marker
                    mGoogleMap.addMarker(marker);
                }
                // Changing marker icon
            }
            //Setting camera position
            //CameraPosition cameraPosition = new Builder()
              //      .target(new LatLng(latitude, longitude)).zoom(17).build();
            LatLng latLng = new LatLng(latitude, longitude);
            CameraUpdate cameraUpdate  = CameraUpdateFactory.newLatLngZoom(latLng,17);
            mGoogleMap.moveCamera(cameraUpdate);

MainActivity.java代码如下

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);
		//Setting Start Navigation
		aController = (AppController) getApplicationContext();

		mToolbar = (Toolbar) findViewById(R.id.toolbar);
		setSupportActionBar(mToolbar);
		getSupportActionBar().setDisplayShowHomeEnabled(true);
		drawerFragment = (FragmentDrawer)
				getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
		drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
		drawerFragment.setDrawerListener(this);

		// display the first navigation drawer view on app launch
		displayView(0);
		//Setting End Navigation
		//Setting Font in Calibri
		font_calibri = Typeface.createFromAsset(getAssets(), "calibri_bold.ttf");
		txtUserName = (TextView) findViewById(R.id.txt_profile_name);
		//Intent i=getIntent();

		sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
		editor = sharedPreferences.edit();
		icprofile = (ImageView) findViewById(R.id.ic_profile);
		String stringpath = sharedPreferences.getString("key_profile_pic", "Null Value");
		String stringname = sharedPreferences.getString("key_profile_name", "Null Value");
		String stringnumber = sharedPreferences.getString("key_mobile", "Null Value");
		txtUserName.setText(stringname);
		File imgFile = new File(stringpath);
		if (imgFile.exists()) {
			Bitmap bmp = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
			Bitmap circleImage = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Bitmap.Config.ARGB_8888);
			BitmapShader shader = new BitmapShader(bmp, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
			Paint paint = new Paint();
			paint.setShader(shader);
			paint.setAntiAlias(true);
			Canvas c = new Canvas(circleImage);
			c.drawCircle(bmp.getWidth() / 2, bmp.getHeight() / 2, bmp.getWidth() / 2, paint);
			icprofile.setImageBitmap(circleImage);
		}

		icprofile.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), ProfileActivity.class);
				startActivity(intent);

				///Now set this bitmap on imageview
			}
		});
		if (name != null && email != null) {
			name = stringname;
			email = stringnumber;
		}


		//Checking For GPS Enabled Or Disabled
		LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//			showGPSDisabledAlertToUser();
		} else {
			showGPSDisabledAlertToUser();
		}
		//For Fragment Stack
		//Checking Google Play Services
		name = stringname;
		email = stringnumber;
		// Make sure the device has the proper dependencies.
		GCMRegistrar.checkDevice(this);

		// Make sure the manifest was properly set - comment out this line
		// while developing the app, then uncomment it when it's ready.
		GCMRegistrar.checkManifest(this);

		registerReceiver(mHandleMessageReceiver, new IntentFilter(
				DISPLAY_MESSAGE_ACTION));

		// Get GCM registration id
		final String regId = GCMRegistrar.getRegistrationId(this);

		// Check if regid already presents
		if (regId.equals("")) {
			// Registration is not present, register now with GCM
			GCMRegistrar.register(this, SENDER_ID);
		} else {
			// Device is already registered on GCM
			if (GCMRegistrar.isRegisteredOnServer(this)) {
				// Skips registration.
				Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
			} else {
				// Try to register again, but not in the UI thread.
				// It's also necessary to cancel the thread onDestroy(),
				// hence the use of AsyncTask instead of a raw thread.
				final Context context = this;
				mRegisterTask = new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... params) {
						// Register on our server
						// On server creates a new user
						ServerUtilities.register(context, name, email, regId);
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						mRegisterTask = null;
					}

				};
				mRegisterTask.execute(null, null, null);
			}
		}

		// ATTENTION: This was auto-generated to implement the App Indexing API.
		// See https://g.co/AppIndexing/AndroidStudio for more information.
		client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
	}

	@Override
	public void onDrawerItemSelected(View view, int position) {
		displayView(position);
	}

	private void displayView(int position) {
		Fragment fragment = null;
		String title = getString(R.string.app_name);
		switch (position) {
			case 0:
				fragment = new HomeFragment();
				title = getString(R.string.title_home);
				break;
			case 1:
				fragment = new FriendsFragment();
				title = getString(R.string.title_friends);
				isExit = false;
				break;
			case 2:
				fragment = new MessageFragment();
				title = getString(R.string.title_messages);
				isExit = false;
				break;
			case 3:
				fragment = new MapFragment();
				title = getString(R.string.title_map);
				isExit = false;
				break;
			case 4:
				fragment = new SettingFragment();
				title = getString(R.string.title_setting);
				isExit = false;
				break;
			case 5:
				fragment = new AboutFragment();
				title = getString(R.string.title_about);
				isExit = false;
				break;
			default:
				break;
		}

如果有的话,请你找到解决方案。

谢谢你花了宝贵的时间..

0 个答案:

没有答案