2016-03-18 37 views
-3

我是Android新手,我試圖通過一些教程學習Android。這裏是logcat中的錯誤,當我嘗試開始使用button.I認爲問題是這兩個按鈕不是通過findViewById方法找到的。我該如何解決它。 錯誤:Andorid.button.OnClickListener中的空指針

03-18 00:57:46.964: E/AndroidRuntime(1066): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cs656/com.example.cs656.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference 

,這裏是活動

import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 


public class MainActivity extends Activity { 

    private Button log_in; 
    private Button register; 
    private Button.OnClickListener Button_Listener = new Button.OnClickListener(){ 
     public void onClick(View v){ 
      setTitle("kkkkkkkkkkkk"); 
     } 
    }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) {   
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     log_in = (Button) findViewById(android.R.id.button1); 
     log_in.setOnClickListener(Button_Listener); 

     register = (Button) findViewById(android.R.id.button2); 

    } 
} 

XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:baselineAligned="true" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 

    <Button android:id ="@+id/register" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Register" /> 

    <Button android:id ="@+id/log_in" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Log In" />  

</LinearLayout> 
+0

當您調用'findViewById(android.R.id.button1)'時,您希望得到'register'或'log_in'按鈕中的哪一個? –

回答

2

更改此行

log_in = (Button) findViewById(android.R.id.button1); 
    register = (Button) findViewById(android.R.id.button2); 

log_in = (Button) findViewById(R.id.log_in); 
    register = (Button) findViewById(R.id.register); 

你的id在xml和java文件中不匹配。

+0

謝謝,你解決了我的問題。看起來我犯了一個愚蠢的錯誤。 – user6080598

1

更換

log_in = (Button) findViewById(android.R.id.button1); 
    register = (Button) findViewById(android.R.id.button2); 

log_in = (Button) findViewById(R.id.log_in); 
    register = (Button) findViewById(R.id.register); 

android.R.id.button1嘗試在Android的默認個XML進行搜索,而不是在您創建的XML。 另外,使用與xml中聲明的相同的id。

+0

這是OP問題的不正確答案。 –