Java 如果不在函数中传递视图,则无法获取PositionManager的实例
我在这里使用maps SDK,并已初始化map and PositionManager,以便在Java 如果不在函数中传递视图,则无法获取PositionManager的实例,java,android,android-view,here-api,Java,Android,Android View,Here Api,我在这里使用maps SDK,并已初始化map and PositionManager,以便在initialize()方法中获取用户的当前位置现在我有2个getDirections(视图v)它是从视图布局xml文件调用的,因此它能够访问posManager,这是PositioningManager类的实例,但我的第二个方法是跟踪我的骑行,它被按钮调用。单击方法,在这里,当我尝试使用posManager应用程序时抛出错误 com.sjain.routeplanner E/AndroidRuntim
initialize()
方法中获取用户的当前位置现在我有2个getDirections(视图v)
它是从视图布局xml文件调用的
,因此它能够访问posManager
,这是PositioningManager类的实例
,但我的第二个方法是跟踪我的骑行
,它被按钮调用。单击方法,在这里,当我尝试使用posManager应用程序时抛出错误
com.sjain.routeplanner E/AndroidRuntime:致命异常:主
进程:com.sjain.routeplan,PID:26948
java.lang.RuntimeException:无法启动活动组件信息{com.sjain.routeplanner/com.sjain.routeplanner.ViewMapActivity}:
java.lang.NullPointerException:尝试调用虚拟方法
'com.here.android.mpa.common.GeoPosition
上的com.here.android.mpa.common.PositioningManager.getPosition()
空对象引用
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.here.android.mpa.common.GeoPosition
com.here.android.mpa.common.PositioningManager.getPosition()' on a
null object reference
在com.sjain.routeplanner.ViewMapActivity.track_my_ride(ViewMapActivity.java:334)上
在com.sjain.routeplanner.ViewMapActivity.intentInfo上(ViewMapActivity.java:137)
在com.sjain.routeplanner.ViewMapActivity.onCreate(ViewMapActivity.java:101)上
位于android.app.Activity.performCreate(Activity.java:6298)
我也读过如何传递当前活动视图的答案,但似乎没有一个有效。
如果我试图从具有视图引用的getDirection(View v)方法访问posManager,则不会发生此异常,因此我认为这不是posManager未初始化的问题
这是我的ViewMapActivity.java文件
public class ViewMapActivity extends AppCompatActivity {
private static final String LOG_TAG = ViewMapActivity.class.getSimpleName();
// permissions request code
private final static int REQUEST_CODE_ASK_PERMISSIONS = 1;
/**
* Permissions that need to be explicitly requested from end user.
*/
private static final String[] REQUIRED_SDK_PERMISSIONS = new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION};
// map embedded in the map fragment
private Map map = null;
// map fragment embedded in this activity
private MapFragment mapFragment = null;
// TextView for displaying the current map scheme
private TextView textViewResult;
// MapRoute for this activity
private static MapRoute mapRoute = null;
private PositioningManager posManager;
boolean paused = false;
private MapMarker marker;
private RouteItem route = null;
// Define positioning listener
PositioningManager.OnPositionChangedListener positionListener = new
PositioningManager.OnPositionChangedListener() {
public void onPositionUpdated(PositioningManager.LocationMethod method,
GeoPosition position, boolean isMapMatched) {
// set the center only when the app is in the foreground
// to reduce CPU consumption
if (!paused) {
map.setCenter(position.getCoordinate(),
Map.Animation.NONE);
Log.d("MainActivity.class", "onPositionUpdated: " + position.getCoordinate().toString());
marker.setCoordinate(position.getCoordinate());
}
}
@Override
public void onPositionFixChanged(PositioningManager.LocationMethod locationMethod, PositioningManager.LocationStatus locationStatus) {
Log.d("MainActivity.class", "onPositionFixChanged: " + locationStatus);
String status = locationStatus.toString();
if (Objects.equals(status, "AVAILABLE")) {
marker.setCoordinate(posManager.getPosition().getCoordinate());
} else if (Objects.equals(status, "TEMPORARILY_UNAVAILABLE")) {
marker.setCoordinate(posManager.getLastKnownPosition().getCoordinate());
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkPermissions();
intentInfo();
}
private void intentInfo() {
try{
......
String type = this.getIntent().getStringExtra("type");
// if type is display just display the route
// if track then display the eta and current status
if(Objects.equals(type, "track")) {
String location = this.getIntent().getStringExtra("location");
track_my_ride(location);
}
}
catch (Error e) {
Log.e("ViewMapActivity.class", "intentInfo: ", e);
}
}
@Override
protected void onResume() {
super.onResume();
paused = false;
if (posManager != null) {
posManager.start(PositioningManager.LocationMethod.GPS);
}
}
@Override
protected void onPause() {
super.onPause();
if (posManager != null) {
posManager.stop();
}
paused = true;
super.onPause();
}
@Override
protected void onDestroy() {
if (posManager != null) {
// Cleanup
posManager.removeListener(positionListener);
}
map = null;
super.onDestroy();
}
private void initialize() {
setContentView(R.layout.activity_map_view);
// Search for the map fragment to finish setup by calling init().
mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFragment);
mapFragment.init(new OnEngineInitListener() {
@Override
public void onEngineInitializationCompleted(OnEngineInitListener.Error error) {
if (error == OnEngineInitListener.Error.NONE) {
// retrieve a reference of the map from the map fragment
map = mapFragment.getMap();
// Set the map center coordinate to the Vancouver region (no animation)
map.setCenter(new GeoCoordinate(19.152568, 72.855825), Map.Animation.NONE);
// Set the map zoom level to the average between min and max (no animation)
map.setZoomLevel((map.getMaxZoomLevel() + map.getMinZoomLevel()) / 2);
// get users current location
posManager = PositioningManager.getInstance();
posManager.start(PositioningManager.LocationMethod.GPS);
posManager.addListener(new WeakReference<>(positionListener));
// create marker to display users current location
marker = new MapMarker();
marker.setCoordinate(posManager.getLastKnownPosition().getCoordinate());
map.addMapObject(marker);
} else {
Log.e(LOG_TAG, "Cannot initialize MapFragment (" + error + ")");
}
}
});
}
/**
* Checks the dynamically controlled permissions and requests missing permissions from end user.
*/
protected void checkPermissions() {
final List<String> missingPermissions = new ArrayList<>();
// check all required dynamic permissions
for (final String permission : REQUIRED_SDK_PERMISSIONS) {
final int result = ContextCompat.checkSelfPermission(this, permission);
if (result != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(permission);
}
}
if (!missingPermissions.isEmpty()) {
// request all missing permissions
final String[] permissions = missingPermissions
.toArray(new String[missingPermissions.size()]);
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_ASK_PERMISSIONS);
} else {
final int[] grantResults = new int[REQUIRED_SDK_PERMISSIONS.length];
Arrays.fill(grantResults, PackageManager.PERMISSION_GRANTED);
onRequestPermissionsResult(REQUEST_CODE_ASK_PERMISSIONS, REQUIRED_SDK_PERMISSIONS,
grantResults);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
@NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
for (int index = permissions.length - 1; index >= 0; --index) {
if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {
// exit the app if one permission is not granted
Toast.makeText(this, "Required permission '" + permissions[index]
+ "' not granted, exiting", Toast.LENGTH_LONG).show();
finish();
return;
}
}
// all permissions were granted
initialize();
break;
}
}
public void getDirections(View v) {
// posManager Works here without any error.
GeoCoordinate coordinate;
if(posManager.getPosition().getCoordinate() != null) {
coordinate = posManager.getPosition().getCoordinate();
}
else if(posManager.getLastKnownPosition().getCoordinate() != null ){
coordinate = posManager.getLastKnownPosition().getCoordinate();
}
else {
// default nesco it park coordinates
//coordinates taken from here maps
coordinate = new GeoCoordinate(19.15254,72.85571);
}
}
public void track_my_ride(String location) {
// 1. clear previous results
textViewResult = (TextView) findViewById(R.id.result);
textViewResult.setText("");
if (map != null && mapRoute != null) {
map.removeMapObject(mapRoute);
mapRoute = null;
}
// 2. Initialize RouteManager
RouteManager routeManager = new RouteManager();
// 3. Select routing options
RoutePlan routePlan = new RoutePlan();
RouteOptions routeOptions = new RouteOptions();
routeOptions.setTransportMode(RouteOptions.TransportMode.CAR);
routeOptions.setRouteType(RouteOptions.Type.FASTEST);
routePlan.setRouteOptions(routeOptions);
GeoCoordinate coordinate;
if(posManager.getPosition().getCoordinate() != null) {
coordinate = posManager.getPosition().getCoordinate();
}
else if(posManager.getLastKnownPosition().getCoordinate() != null ){
coordinate = posManager.getLastKnownPosition().getCoordinate();
}
else {
// default nesco it park coordinates
//coordinates taken from here maps
coordinate = new GeoCoordinate(19.15254,72.85571);
}
// 4. Select Waypoints for your routes
routePlan.addWaypoint(coordinate);
// supposed to be current or last known location of bus
String[] bus_coordinate = location.split(",");
routePlan.addWaypoint(new GeoCoordinate(
Double.parseDouble(bus_coordinate[0]),
Double.parseDouble(bus_coordinate[1])));
// 5. Retrieve Routing information via RouteManagerEventListener
RouteManager.Error error = routeManager.calculateRoute(routePlan, routeManagerListener);
if (error != RouteManager.Error.NONE) {
Toast.makeText(getApplicationContext(),
"Route calculation failed with: " + error.toString(), Toast.LENGTH_SHORT)
.show();
}
}
private RouteManager.Listener routeManagerListener = new RouteManager.Listener() {
public void onCalculateRouteFinished(RouteManager.Error errorCode,
List<RouteResult> result) {
if (errorCode == RouteManager.Error.NONE && result.get(0).getRoute() != null) {
// create a map route object and place it on the map
mapRoute = new MapRoute(result.get(0).getRoute());
map.addMapObject(mapRoute);
// Get the bounding box containing the route and zoom in (no animation)
GeoBoundingBox gbb = result.get(0).getRoute().getBoundingBox();
map.zoomTo(gbb, Map.Animation.NONE, Map.MOVE_PRESERVE_ORIENTATION);
textViewResult.setText(String.format(getString(R.string.route_maneuvers), result.get(0).getRoute().getManeuvers().size()));
} else {
textViewResult.setText(
String.format("Route calculation failed: %s", errorCode.toString()));
}
}
public void onProgress(int percentage) {
textViewResult.setText(String.format(getString(R.string.precent_done), percentage));
}
};
}
公共类ViewMapActivity扩展了AppCompatActivity{
私有静态最终字符串LOG_TAG=ViewMapActivity.class.getSimpleName();
//权限请求代码
私有最终静态int请求\代码\请求\权限=1;
/**
*需要从最终用户显式请求的权限。
*/
私有静态最终字符串[]必需的\u SDK\u权限=新字符串[]{
Manifest.permission.ACCESS\u FINE\u位置,Manifest.permission.WRITE\u外部存储,
Manifest.permission.READ_外部_存储,Manifest.permission.ACCESS_位置};
//地图嵌入在地图片段中
私有映射=null;
//此活动中嵌入的映射片段
私有MapFragment MapFragment=null;
//用于显示当前地图方案的文本视图
私有文本视图文本视图结果;
//此活动的映射路径
私有静态MapRoute MapRoute=null;
私人职位经理职位经理;
布尔值=假;
私有地图标记;
private RouteItem route=null;
//定义定位侦听器
PositionManager.OnPositionChangedListener positionListener=新建
PositionManager.OnPositionChangedListener(){
职位更新后的公共无效(职位管理器.LocationMethod,
地理位置,布尔值(匹配){
//仅当应用程序位于前台时才设置中心
//减少CPU消耗
如果(!暂停){
map.setCenter(position.getCoordinate(),
Map.Animation.NONE);
Log.d(“MainActivity.class”,“onPositionUpdate:+position.getCoordinate().toString());
marker.setCoordinate(position.getCoordinate());
}
}
@凌驾
PositionFixChanged上的公共无效(PositionManager.LocationMethod LocationMethod,PositionManager.LocationStatus LocationStatus){
Log.d(“MainActivity.class”,“onPositionFixChanged:+locationStatus”);
字符串状态=locationStatus.toString();
if(Objects.equals(状态为“可用”)){
marker.setCoordinate(posManager.getPosition().getCoordinate());
}else if(Objects.equals(状态“暂时不可用”)){
marker.setCoordinate(posManager.getLastKnownPosition().getCoordinate());
}
}
};
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
检查权限();
intentInfo();
}
私有void intentInfo(){
试一试{
......
字符串类型=this.getIntent().getStringExtra(“类型”);
//如果类型为“显示”,则仅显示路线
//如果跟踪,则显示预计到达时间和当前状态
if(Objects.equals(键入“track”)){
字符串位置=this.getIntent().getStringExtra(“位置”);
追踪我的旅程(位置);
}
}
捕获(错误e){
Log.e(“ViewMapActivity.class”,“intentInfo:”,e);
}
}
@凌驾
受保护的void onResume(){
super.onResume();
暂停=错误;
if(posManager!=null){
posManager.start(positionmanager.LocationMethod.GPS);
}
}
@凌驾
受保护的void onPause(){
super.onPause();
if(posManager!=null){
posManager.stop();
}
暂停=真;
super.onPause();
}
@凌驾
受保护的空onDestroy(){
if(posManager!=null){
//清理
posManager.RemovelListener(positionListener);
}
map=null;
super.ondestory();
}
私有void初始化(){
setContentView(R.layout.activity\u map\u视图);
//通过调用init()搜索映射片段以完成安装。
mapFragment=(MapF
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkPermissions();
intentInfo(); // NOT GOOD HERE.
}
private void intentInfo() {
try{
......
String type = this.getIntent().getStringExtra("type");
// if type is display just display the route
// if track then display the eta and current status
if(Objects.equals(type, "track")) {
String location = this.getIntent().getStringExtra("location");
track_my_ride(location); // You're gonna NPE HERE.
}
}
catch (Error e) {
Log.e("ViewMapActivity.class", "intentInfo: ", e); // You're gonna NPE catch HERE.
}
}