2012-03-03 60 views
0

我試圖從活動綁定到服務時出現以下問題。從活動綁定到服務時獲取NullPointerException

代碼活動,這活動是TabActivity的一部分

public class SettingsActivity extends Activity{ 

private BkgService myBkgService; 
Button BtnSubmit; 

public void onCreate(Bundle savedInstanceState) { 

setContentView(R.layout.settings); 
BtnSubmit = (Button)findViewById(R.id.XmlBtnSubmit); 
BtnSubmit.setOnClickListener(onSubmit); 

Intent bindIntent = new Intent(this, BkgService.class); 
bindService(bindIntent, serviceConncetion, Context.BIND_AUTO_CREATE); 
} 


private ServiceConnection serviceConncetion = new ServiceConnection() { 

     @Override 
     public void onServiceConnected(ComponentName name, IBinder service) { 
      myBkgService = ((BkgService.MyBinder)service).getService(); 
     } 

     @Override 
     public void onServiceDisconnected(ComponentName name) { 
      myBkgService = null; 
     } 
    }; 

private OnClickListener onSubmit = new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      myBkgService.startCounting(); 
     } 
    }; 
} 

現在我的服務代碼看起來像這樣

public class BkgService extends Service{ 
    private IBinder mBinder; 
    private int i; 


    public void onCreate() { 
      super.onCreate(); 
    } 

    @Override 
    public IBinder onBind(Intent arg0) { 
      return mBinder; 
    } 

    public class MyBinder extends Binder { 
    BkgService getService() { 
      return BkgService.this; 
     } 
    } 

    public int startCounting(){ 
     return i=i+1; 
    } 

} 

現在,當我的活動點擊我的btnSubmit按鈕,我收到空指針異常。我檢查了我是因爲在myBkgService.startCounting()myBkgService是空的。我無法找出爲什麼我得到這個空指針。我的活動是否沒有正確綁定到服務?請爲此提出一些解決方案。我在這裏卡住了。

回答

0

確保您在AndroidManifest.xml中聲明你的服務。如果你不這樣做,那麼對bindService的調用將返回false。

我也注意到你沒有初始化你的mBinder,在你的BkgService中需要如下的東西。

private IBinder mBinder = new MyBinder(); 
+0

感謝它的工作。我錯過了這個.... – 2012-03-03 15:05:02

1

試試這個方法:

public void onCreate(Bundle savedInstanceState) { 

    setContentView(R.layout.settings); 
    BtnSubmit = (Button)findViewById(R.id.XmlBtnSubmit); 
    BtnSubmit.setOnClickListener(onSubmit); 

    serviceConncetion = new ServiceConnection() { 

      @Override 
      public void onServiceConnected(ComponentName name, IBinder service) { 
       myBkgService = ((BkgService.MyBinder)service).getService(); 
      } 

      @Override 
      public void onServiceDisconnected(ComponentName name) { 
       myBkgService = null; 
      } 
    }; 
    Intent bindIntent = new Intent(this, BkgService.class); 
    bindService(bindIntent, serviceConncetion, Context.BIND_AUTO_CREATE); 
}