我正在尝试在与主要活动相关联的片段中实施谷歌地图,并将地图作为应用的第一个视图。但是当我构建它时,下面的错误出现了。
Error:(166, 39) error: cannot find symbol variable MY_PERMISSIONS_REQUEST_LOCATION
有人可以解释为什么以及如何解决? Mainactivity:
public class MainActivity extends AppCompatActivity {
public static GoogleAnalytics analytics;
public static Tracker tracker;
MapsFragment mapFrag;
DrawerLayout mDrawerLayout;
ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;
FragmentTransaction fragmentTransaction;
NavigationView navigationView;
private ParksFragment mParksFragment;
MapsFragment mapFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Tracker t = ((MyApp) getApplication()).getTracker(MyApp.TrackerName.APP_TRACKER);
t.setScreenName("MainActivity");
t.setScreenName("DetailActivity");
t.setScreenName("MapsFragment");
t.setScreenName("ParksFragment");
t.send(new HitBuilders.ScreenViewBuilder().build());
getSupportActionBar().setTitle("Map Location Activity");
mapFragment = new MapsFragment();
mParksFragment = new ParksFragment();
mToolbar = (Toolbar) findViewById(R.id.nav_actionbar);
setSupportActionBar(mToolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync((OnMapReadyCallback) this);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container,new MapsFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Home");
navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.home_category:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.mapframe, new MapsFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Home");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
case R.id.parks_category:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new ParksFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Parks");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
case R.id.monuments_category:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new MonumentsFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Monuments");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
case R.id.theatrescinemas_category:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new TheatresFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Theatres and Cinemas");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
case R.id.museums_category:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new MuseumsFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Museums");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
case R.id.festivals_category:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new FestivalsFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Festivals and Activities");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
case R.id.tips_category:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new TipsFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Local Tips");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
case R.id.settings_category:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new SettingsFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Settings");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
}
return false; }
});
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == MapFragment.MY_PERMISSIONS_REQUEST_LOCATION){
mapFragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
}
MapsFragment:
public class MapsFragment extends SupportMapFragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
private final int[] MAP_TYPES = { GoogleMap.MAP_TYPE_SATELLITE,
GoogleMap.MAP_TYPE_NORMAL,
GoogleMap.MAP_TYPE_HYBRID,
GoogleMap.MAP_TYPE_TERRAIN,
GoogleMap.MAP_TYPE_NONE };
private int curMapTypeIndex = 0;
public MapsFragment(){
}
@Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
getMapAsync(this);
}
}
@Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mGoogleMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
@Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(getActivity())
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
更换变量后,我的应用程序已经建成,但它已经崩溃了。这里是logcat输出:
--------- beginning of crash
06-20 12:47:32.999 20892-20892/com.example.user.appsightseeing E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.appsightseeing, PID: 20892
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.appsightseeing/com.example.user.appsightseeing.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
at com.example.user.appsightseeing.MainActivity.onCreate(MainActivity.java:50)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
答案 0 :(得分:0)
更改此代码
if (requestCode == MapsFragment.MY_PERMISSIONS_REQUEST_LOCATION){
mapFragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
在您的活动中添加此内容
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle ("your title" );