2011-09-21 3 views
0

이 안드로이드 코드가 있습니다. xml 파일에 정의 된 버튼에 대한 레이아웃이 있습니다 .i 여기에서 버튼에 텍스트를 설정하고 싶습니다. 그러나 앱에서 강제로 가져 오는 것으로 나타납니다. closes.whats가 잘못 되었습니까?android app force closes

package com.action ; 
    import android.app.Activity; 
    import android.os.Bundle; 
    import android.widget.Button; 

    public class ActionActivity extends Activity { 
    @Override 
    public void onCreate(Bundle i){ 
     super.onCreate(i); 
     Button button=(Button) findViewById(R.id.but); 
     button.setText("Hey!!"); 
     setContentView(R.layout.main); 
     } 
} 

Thnx ...

+1

logcat의 출력도 게시하십시오. – richardwiden

답변

5

당신은 findViewById()를 사용하기 전에 setContentView(R.layout.main);을 사용해야합니다. 당신이하지 않으면

, findViewById() 반환 null (즉 ID와 더 뷰가 현재 레이아웃에 없기 때문에)와 TextView의 텍스트를 설정하려고 할 때 당신이 NullPointerException 얻을 것이다.

onCreate()의 올바른 버전은 다음과 같아야합니다

public void onCreate(Bundle i) { 
    super.onCreate(i); 

    setContentView(R.layout.main); 
    Button button = (Button) findViewById(R.id.but); 
    button.setText("Hey!!"); 
} 
+0

thnx ... 내 나쁜, cudnt 이런 일을 스스로 .... – karyboy

3

넣어 된 setContentView (R.layout.main) 버튼의 인스턴스를 작성하기 전에. 이처럼 는 : findViewById를 (R.id.but)을 설정하기 전에

setContentView(R.layout.main); 

    Button button=(Button) findViewById(R.id.but); 
    button.setText("Hey!!"); 
0

이 된 setContentView (R.Layout.main)를 삽입해야이 nullpointer 예외를 생성 .Because.