2013-08-18 92 views
1

我已经设置了一个按钮,当用户点击它时我试图显示一个烤面包。这里是我的Java代码 -Onclick监听器抛出NullPointerException

file = (Button) findViewById(R.id.file); 

file.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       // Display the file chooser dialog 
       //showChooser(); 
       Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)", Toast.LENGTH_LONG).show(); 
      } 
     }); 

这里是我的XML代码设置按钮 -

<Button 
      android:id="@+id/file" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_below="@id/plt" 
      android:text="File" /> 

这将引发一个NullPointerException就行了file.setOnClickListener(new OnClickListener() {。我究竟做错了什么?

回答

0

如果该线路上一个空指针异常:

file.setOnClickListener(new OnClickListener() 

那么它意味着你file对象为空

添加监听到它之前,请务必初始化文件对象。

3

您是否正在初始化Activity的onCreate()方法中的Button?

如果是这样,请检查您是否有findViewById(R.id.file);

出现您的错误,因为你的按钮“文件”是null,这意味着findViewById(...)没有初始化按钮之前调用

setContentView(R.id.yourlayoutfile); 

使用该ID查找任何视图。原因,因此可以是有处于膨胀布局没有这样的ID,或者说你没叫setContentView(...)

@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.yourlayoutfile); 

     // initialize your button here 
    } 
1

尝试清理项目

项目 - >清理 - >选择你的项目 - >确定, 然后再次运行。

如果你仍然面临着同样的问题,你可以用另外一种方式来设置你的XML单击操作

<Button 
     android:id="@+id/file" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@id/plt" 

     <!--added line-->    
     android:onClick="anyName" 

     android:text="File" /> 

,然后在你的活动中删除按钮的初始化,然后点击听者也

,使代码看起来像

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.id.yourlayoutfile); 
} 

public void anyName(View v){ 
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)", 
    Toast.LENGTH_LONG).show(); 

}

希望得到这个帮助。

+0

我会补充一点,“干净的项目”是一个潜在的修复的原因是因为有时(使用Eclipse),'R.java'与您编写的XML布局不同步,干净的构建将重新生成从头开始编写'R.java' – ataulm

+0

当然,在使用eclipse时这是一个非常常见的问题。 – scriptocalypse