当前位置: 代码迷 >> Android >> 简单的BindService的Demo,总是空指针错误
  详细解决方案

简单的BindService的Demo,总是空指针错误

热度:46   发布时间:2016-05-01 13:27:38.0
简单的BindService的Demo,总是空指针异常
这是Service
Java code
public class MyService extends Service {    MyBinder my = new MyBinder();    public class MyBinder extends Binder{        public int getCount(){            return 5994;        }    }    @Override    public IBinder onBind(Intent intent) {        // TODO Auto-generated method stub        return my;    }}

下面是Activity
Java code
public class StudentQueryCopyActivity extends Activity {       MyBinder my ;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                Intent intent = new Intent(this,MyService.class);        bindService(intent, conn, BIND_AUTO_CREATE);    System.out.println(my.getCount()+".............");                }    ServiceConnection conn = new ServiceConnection() {        public void onServiceDisconnected(ComponentName name) {            System.out.println("diconnected.........");        }                public void onServiceConnected(ComponentName name, IBinder service) {            my = (MyBinder) service;            System.out.println("connected...............");        }    };}


总是提示空指针异常.

------解决方案--------------------
System.out.println(my.getCount()+".............");
这个删除
------解决方案--------------------
探讨

为什么my.getCount()的值值为空呢?它应该是5994啊.

------解决方案--------------------
顶楼上
------解决方案--------------------
探讨

但是已经调用
bindService(intent, conn, BIND_AUTO_CREATE);了啊
my已经指向service了.
  相关解决方案