位于Android服务中的访问数据结构时为空指针

时间:2010-12-22 23:12:16

标签: android binding service android-activity nullpointerexception

我在我的Android应用程序中运行了一个服务,其中包含我想在Activity中使用的HashMap。所以我将服务绑定到我的活动,并在两个之间创建了一个链接,以便使用数据结构。

到目前为止我就是这样做的:

活动(相关代码):

private ServiceConnection mConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder service) {
        imService = ((IMService.IMBinder) service).getService();            
    }

    public void onServiceDisconnected(ComponentName className) {
        imService = null;
        Toast.makeText(ViewFlipperTest.this,
                R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
    }
};


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    bindService(new Intent(ViewFlipperTest.this, IMService.class),
            mConnection, Context.BIND_AUTO_CREATE); 
                 .
                 .
                 .
}
protected void onResume() {
    super.onResume();
    bindService(new Intent(ViewFlipperTest.this, IMService.class),
            mConnection, Context.BIND_AUTO_CREATE);     
}

private void getMap(ViewFlipper flipper2) {

    Map<Integer, internalChatObj> tempMap = imService.getMapwData();
   }

服务(相关代码):

public class IMService extends Service implements IAppManager{
                .
                .
                .

public Map getMapwData(){
    if(getNumberOpenChats()>0){
        return openChatMapwData;
    }
    else
        return null;

}
}

每次我尝试运行getMap()方法时,都会得到一个空指针。我甚至检查了imService是否为null并且每次都为null。它似乎正在尝试从服务获取数据,但绑定到服务是空的,是吗?如果地图为空,我在服务中检查发送null,这不应该是一个问题。

任何帮助?

根据威尔的提示进行修改 新代码

private ServiceConnection mConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder service) {
        imService = ((IMService.IMBinder) service).getService();
        dialog.dismiss();
    }

    public void onServiceDisconnected(ComponentName className) {
        imService = null;
        Toast.makeText(ViewFlipperTest.this,
                R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
    }
};

public void onCreate(Bundle savedInstanceState) {
    dialog = ProgressDialog.show(getApplicationContext(), null,"Loading..", true, false);
}

编辑II

IMBinder Class(看似标准,没有?)

public class IMBinder extends Binder {
    public IAppManager getService() {
        return IMService.this;
    }
}

是否有必要使用IMService.this而不是这个?

1 个答案:

答案 0 :(得分:0)

这似乎是一个时间问题;你不应该调用getMap函数,除非你确定存在imService变量,这是在调用onServiceConnected之后。