当前位置: 代码迷 >> Android >> Unable to instantiate activity ComponentInfo 初学Android,请教上面有甚么区别
  详细解决方案

Unable to instantiate activity ComponentInfo 初学Android,请教上面有甚么区别

热度:75   发布时间:2016-05-01 14:49:21.0
Unable to instantiate activity ComponentInfo 初学Android,请问下面有甚么区别
两个可以说是一样的,但为什么第二个会报错
private OnClickListener listener2=new OnClickListener()
{
public void onClick(View v)
{
Intent intent=new Intent(MainActivity.this, ExampleService.class);//这样就对了
switch (v.getId())
{
case R.id.btnStartService:
startService(intent);
break;
case R.id.btnEndService:
stopService(intent);
break;
}

}
};


  private OnClickListener listener = new OnClickListener() {
  Intent intent = new Intent(MainActivity.this, ExampleService.class);//这样就错了
public void onClick(View v) {
switch(v.getId()) {
case R.id.btnStartService :
startService(intent);
break;
case R.id.btnEndService : 
stopService(intent);
break;
}
}
};

------解决方案--------------------
第二个Intent intent = new Intent(MainActivity.this, ExampleService.class);在创建OnClickListener的时候就执行实例化了。而作为一个类的成员变量,是在初始化这个类的时侯执行, 你的MainActivity都还在初始化中,现在要用它,自然会报错。
------解决方案--------------------
第二个intent = new Intent(MainActivity.this, ExampleService.class)中MainActivity为null,你Log一下MainActivit.this是什么看看
  相关解决方案