// 在安卓fragment中写了获取路线规划,代码如下: // BaiduNaviManagerFactory.getRoutePlanManager().routePlan(list, currentPrefer, bundle, handler); // private final Handler handler = new Handler(Looper.getMainLooper()) { // @Override // public void handleMessage(@NonNull Message msg) { // super.handleMessage(msg); // switch (msg.what) { // case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_START: // mFlRetry.setVisibility(View.GONE); // mLayoutTab0.setSelected(false); // mLayoutTab1.setSelected(false); // mLayoutTab2.setSelected(false); // break; // case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_SUCCESS: // mFlRetry.setVisibility(View.GONE); // mRlButton.setVisibility(View.VISIBLE); // updateBtnText(currentPrefer); // new Thread(() -> initData()).start(); // break; // case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_FAILED: // mFlRetry.setVisibility(View.VISIBLE); // break; // default: // break; // } // } // }; // 以上代码中 路线规划成功 后执行了 initData()方法, 方法中获取了3Tab信息和路线详情 这是个耗时操作,如下代码: // BNRoutePlanInfos routePlaneInfos = BaiduNaviManagerFactory.getRoutePlanManager() .getRoutePlanInfo(); // 所以在handler中使用了Thread来开启一个子线程去执行,那么获取3Tab信息和路线详情的getRoutePlanInfo()可能为空吗? // 如果报空指针异常,应该怎么处理?请帮我修改一下以上问题
时间: 2024-01-09 20:04:36 浏览: 21
在handler中使用Thread来开启一个子线程去执行initData()方法是正确的做法,这样可以避免在主线程中执行耗时操作导致UI卡顿的问题。但是需要注意的是,在子线程中调用getRoutePlanInfo()方法可能会返回null,因为该方法的执行时间可能比较长,而子线程的执行速度可能比主线程快,所以有可能在getRoutePlanInfo()方法执行完成之前子线程已经继续执行了下一步操作。如果getRoutePlanInfo()返回null,那么在使用该对象时就会抛出NullPointerException异常。
为了避免这种情况,可以在getRoutePlanInfo()方法返回null时进行延时重试,直到获取到非null的结果为止。具体代码如下:
```
private void initData() {
BNRoutePlanInfos routePlanInfos = null;
while (routePlanInfos == null) {
routePlanInfos = BaiduNaviManagerFactory.getRoutePlanManager().getRoutePlanInfo();
if (routePlanInfos == null) {
try {
Thread.sleep(100); // 延时100毫秒后重试
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 执行其他操作
}
```
这样就可以避免在使用routePlanInfos对象时出现NullPointerException异常了。