java.lang.RuntimeException:无法在空对象引用上启动活动 ComponentInfo
您好,我的代码出现此错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'double fr.uge.bluetoothle.MapsActivity.calculDistance(double, double, double, double)' on a null object reference
我在 Android Studio 上使用 Java 进行开发。
似乎我无法从 MyLocationListener.java
访问 MapsActivity.java
我认为我没有很好地实例化我的 MpasActivity 类。
我在以下代码中遇到此错误 MyLocationListener.java
package fr.uge.bluetoothle;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
public class MyLocationListener implements LocationListener {
public String longitude;
public String latitude;
public double distance;
private static final String TAG = "Loca";
public MapsActivity mapsActivity;
@Override
public void onLocationChanged(@NonNull Location location) {
/*Toast.makeText(
mapsActivity.getBaseContext(),
"Location changed: Lat: " + location.getLatitude() + " Lng: "
+ location.getLongitude(), Toast.LENGTH_SHORT).show();*/
String longitude = "Longitude: " + location.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + location.getLatitude();
Log.v(TAG, latitude);
distance = mapsActivity.calculDistance(2.58622,48.84008,location.getLongitude(),location.getLatitude());
System.out.println(distance);
}
这里有我的活动名称 MapsActivity.java
package fr.uge.bluetoothle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.location.LocationComponent;
import com.mapbox.mapboxsdk.location.modes.CameraMode;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import java.util.List;
import java.lang.Math;
import com.mapbox.mapboxsdk.style.layers.CircleLayer;
import com.mapbox.mapboxsdk.style.layers.Layer;
import com.mapbox.mapboxsdk.style.layers.LineLayer;
import com.mapbox.mapboxsdk.style.layers.Property;
import com.mapbox.mapboxsdk.style.sources.VectorSource;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineCap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineJoin;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineWidth;
public class MapsActivity extends Activity implements OnMapReadyCallback, PermissionsListener {
private MapView mapView;
private MapboxMap mapboxMap;
private PermissionsManager permissionsManager;
private LocationComponent locationComponent;
MyLocationListener myLocationListener;
private static Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.mapbox_access_token));
setContentView(R.layout.activity_maps);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
//Display Location
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return;
}
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000, 1, locationListener);
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + myLocationListener.getLatitude() + " Lng: "
+ myLocationListener.getLongitude(), Toast.LENGTH_SHORT).show();
}
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {
@Override
public void onStyleLoaded(@NonNull Style style) {
enableLocationComponent(style);
//Add the GPX File
VectorSource vectorSource = new VectorSource("vector-source", getString(R.string.tileset_cyclo));
style.addSource(vectorSource);
//Tracks Layer
/*CircleLayer circleLayer = new CircleLayer("circle-layer-id", "vector-source");
circleLayer.setSourceLayer("tracks");
style.addLayer(circleLayer);*/
//Waypoints Layer
CircleLayer circleLayer1 = new CircleLayer("circle-layer-id-1", "vector-source");
circleLayer1.setSourceLayer("waypoints");
style.addLayer(circleLayer1);
}
});
}
private void enableLocationComponent(Style loadMapStyle) {
/*Check if permissions are enabled and if not request*/
if (PermissionsManager.areLocationPermissionsGranted(this)) {
//Activate the MapBox LocationComponent to show user location
//Adding in LocationComponentOptions is also an optional parameter
locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(this, loadMapStyle);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return;
}
locationComponent.setLocationComponentEnabled(true);
//Set the component's camera mode
locationComponent.setCameraMode(CameraMode.TRACKING);
}
else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
@Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_SHORT).show();
}
@Override
public void onPermissionResult(boolean granted) {
if (granted){
enableLocationComponent(mapboxMap.getStyle());
}
else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onPause() {
super.onPause();
mapView.onLowMemory();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
public Context getContext() {
return mContext;
}
public double calculDistance(double longitude_point, double latitude_point, double longitude_loca, double latitude_loca){
double distance;
distance = Math.acos(Math.sin(Math.toRadians(longitude_point))*Math.sin(Math.toRadians(longitude_loca))+
Math.cos(Math.toRadians(longitude_point))*Math.cos(Math.toRadians(longitude_loca))*
Math.cos(Math.toRadians(latitude_point-latitude_loca)));
distance = distance * 6371;
return distance;
}
}
我不明白问题出在哪里,我认为这就是问题所在来自活动和我的其他 java 文件之间的转换。
Hello I have this error with my code :
java.lang.NullPointerException: Attempt to invoke virtual method 'double fr.uge.bluetoothle.MapsActivity.calculDistance(double, double, double, double)' on a null object reference
I develop on Android Studio in Java.
It seems that I can't access to MapsActivity.java
from MyLocationListener.java
I think I don't instantiate well my MpasActivity class.
I have this error in the folowing code MyLocationListener.java
package fr.uge.bluetoothle;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
public class MyLocationListener implements LocationListener {
public String longitude;
public String latitude;
public double distance;
private static final String TAG = "Loca";
public MapsActivity mapsActivity;
@Override
public void onLocationChanged(@NonNull Location location) {
/*Toast.makeText(
mapsActivity.getBaseContext(),
"Location changed: Lat: " + location.getLatitude() + " Lng: "
+ location.getLongitude(), Toast.LENGTH_SHORT).show();*/
String longitude = "Longitude: " + location.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + location.getLatitude();
Log.v(TAG, latitude);
distance = mapsActivity.calculDistance(2.58622,48.84008,location.getLongitude(),location.getLatitude());
System.out.println(distance);
}
And here there is my activity's name MapsActivity.java
package fr.uge.bluetoothle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.location.LocationComponent;
import com.mapbox.mapboxsdk.location.modes.CameraMode;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import java.util.List;
import java.lang.Math;
import com.mapbox.mapboxsdk.style.layers.CircleLayer;
import com.mapbox.mapboxsdk.style.layers.Layer;
import com.mapbox.mapboxsdk.style.layers.LineLayer;
import com.mapbox.mapboxsdk.style.layers.Property;
import com.mapbox.mapboxsdk.style.sources.VectorSource;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineCap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineJoin;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineWidth;
public class MapsActivity extends Activity implements OnMapReadyCallback, PermissionsListener {
private MapView mapView;
private MapboxMap mapboxMap;
private PermissionsManager permissionsManager;
private LocationComponent locationComponent;
MyLocationListener myLocationListener;
private static Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.mapbox_access_token));
setContentView(R.layout.activity_maps);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
//Display Location
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return;
}
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000, 1, locationListener);
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + myLocationListener.getLatitude() + " Lng: "
+ myLocationListener.getLongitude(), Toast.LENGTH_SHORT).show();
}
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {
@Override
public void onStyleLoaded(@NonNull Style style) {
enableLocationComponent(style);
//Add the GPX File
VectorSource vectorSource = new VectorSource("vector-source", getString(R.string.tileset_cyclo));
style.addSource(vectorSource);
//Tracks Layer
/*CircleLayer circleLayer = new CircleLayer("circle-layer-id", "vector-source");
circleLayer.setSourceLayer("tracks");
style.addLayer(circleLayer);*/
//Waypoints Layer
CircleLayer circleLayer1 = new CircleLayer("circle-layer-id-1", "vector-source");
circleLayer1.setSourceLayer("waypoints");
style.addLayer(circleLayer1);
}
});
}
private void enableLocationComponent(Style loadMapStyle) {
/*Check if permissions are enabled and if not request*/
if (PermissionsManager.areLocationPermissionsGranted(this)) {
//Activate the MapBox LocationComponent to show user location
//Adding in LocationComponentOptions is also an optional parameter
locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(this, loadMapStyle);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return;
}
locationComponent.setLocationComponentEnabled(true);
//Set the component's camera mode
locationComponent.setCameraMode(CameraMode.TRACKING);
}
else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
@Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_SHORT).show();
}
@Override
public void onPermissionResult(boolean granted) {
if (granted){
enableLocationComponent(mapboxMap.getStyle());
}
else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onPause() {
super.onPause();
mapView.onLowMemory();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
public Context getContext() {
return mContext;
}
public double calculDistance(double longitude_point, double latitude_point, double longitude_loca, double latitude_loca){
double distance;
distance = Math.acos(Math.sin(Math.toRadians(longitude_point))*Math.sin(Math.toRadians(longitude_loca))+
Math.cos(Math.toRadians(longitude_point))*Math.cos(Math.toRadians(longitude_loca))*
Math.cos(Math.toRadians(latitude_point-latitude_loca)));
distance = distance * 6371;
return distance;
}
}
I don't understand where is the problem I think That's the problem come from the transition between the activity and my other java file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对
mapsActivity.calculDistance()
的调用会引发异常,因为变量mapsActivity
为null
。您尚未将变量mapsActivity
设置为任何内容。查看您的代码,方法
calculDistance()
基本上是一个实用方法,并不真正属于任何类(它不使用该类的任何方法或成员变量)。您可以简单地通过将static
关键字添加到方法声明中来使其成为静态方法,如下所示:现在您可以从任何其他类中使用此方法,如下所示:
请注意,您正在调用该方法类,而不是类的实例。在这种情况下,您不需要声明变量
mapsActivity
,因为不再使用它。一种更简洁的方法是将此方法移出 MapsActivity 类并将其放入新的实用程序类中(该类应仅包含公共静态方法,并且应具有私有方法)构造函数,因此不可能实际创建该实用程序类的任何实例。
Your call to
mapsActivity.calculDistance()
throws an exception because the variablemapsActivity
isnull
. You haven't set the variablemapsActivity
to anything.Looking at your code, the method
calculDistance()
is basically a utility method and doesn't really belong to any class (it doesn't use any methods or member variables of the class). You can simply make this a static method by adding thestatic
keyword to the method declaration, like this:Now you can use this method from any other class, like this:
Notice that you are calling the method on the class, not on an instance of the class. In this case, you don't need to declare a variable
mapsActivity
, because this is no longer used.A somewhat cleaner approach would be to move this method out of the
MapsActivity
class and put it in a new utility class (which should contain onlypublic static
methods and should have a private constructor so that it is not possible to actually create any instances of that utility class.