2012-02-02 4 views
3

프로그래밍 언어에 익숙하지만 안드로이드 프로그래밍에 익숙하지 않습니다.Android; 클래스 바디에서 edittext 선언하기 (어떤 메소드에서든지)

나는 라벨 (textview), 버튼 및 데이터 입력 (edittext)으로 작동하는 일부 필드가있는 프로그램이 있습니다.

언제든지 프로그램의 시작 부분에서 선언 할 때마다 (물론 수업 중에), 응용 프로그램을 시작할 때 충돌이 발생하고 시뮬레이션에서 "불행히도 프로그램이 중단되었습니다"라는 경고가 표시됩니다.

Eclipse는 선언문에 오류를주지 않으며 문제없이 일반 변수를 정의하는 데 동일한 방법을 사용했습니다. 또한 클래스 본문에 mediaplayer 객체를 선언 할 때도 동일한 오류가 발생합니다.

왜 오류가 발생하는지 알고 계십니까? 그리고 edittext, viewtext 등과 같은 전역 객체를 선언 할 수있는 또 다른 방법이 있습니다 ... 메소드에서 반복적으로 선언하면 이상하게 들립니다.

감사합니다.

공용 클래스 TrainerActivity는 활동 {

Button stopTimer = (Button)findViewById(R.id.StopTimer); 
Button startTimer = (Button)findViewById(R.id.StartTimer); 
EditText totalTime = (EditText)findViewById(R.id.TotalTime); 
EditText enterMin = (EditText)findViewById(R.id.EnterMin); 
EditText enterSec = (EditText)findViewById(R.id.EnterSec); 

private boolean breaker = false; 

@Override 

public void onCreate(Bundle savedInstanceState) 
{ 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 


    startTimer.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      Button_StartTimer(); 
     } 
    }); 

    stopTimer.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      Button_StopTimer(); 
     } 
    }); 
} 

답변

0

당신이 문제를 설명 샘플 코드의 비트를 게시 할 수 확장? 클래스의 EditText 또는 TextView 멤버 변수를 선언해도 좋습니다.

logcat (DDMS에서)은 오류에 대한 정보도 제공해야합니다. 이클립스를 사용하고 있다면 DDMS 용 탭이 있습니다. 그렇지 않으면 명령 줄에서 DDMS를 실행하고 logcat 탭을보고 앱을 실행하십시오 (물론 USB를 통해 전화가 연결되어 있어야합니다). 보고 된 실제 오류를 확인하십시오.

0

이러한 변수는 클래스 본문 또는 메서드 본문 내에 선언 할 수 있습니다. 전자의 경우 변수는 전역 변수이므로 클래스 전체에서 액세스 할 수 있습니다. 후자의 경우에는 로컬 메소드이므로 해당 메소드 내에서만 액세스 할 수 있습니다. 둘 다 proramming에서 일반적으로 볼 수 있습니다.

Android의 일반적인 응용 프로그램은 클래스 본문에 변수를 선언하고 onCreate() 메서드에서 인스턴스를 생성하는 것입니다. 이런 식으로 뭔가 :

public Class MyClass extends Activity{ 

    TextView label;// so this variable can be accessed within any methods in this Class 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(Bundle savedInstanceState); 
      setContentView(R.layout.main) // load the layout of the activity 
      label=(TextView)findViewById(R.id.<the TextView id defined in the layout file>); //this variable get instantiated. From now on you can manipulate it anywhere inside the class. 
     Button submit=(Button)findViewById(R.id.<the Button id defined in the layout file>);//you declared and instantiated it, but it could only be used within this method since you declared it here. 

} 


    } 

그냥 클래스 본문에 변수를 선언하는 경우가 인스턴스화 전에 null 때문에 당신이 그것을 인스턴스화 될 때까지, 대부분의 caeses에, 당신이 그것을 사용할 수 없습니다. 나는 이것이 당신에게 문제가있는 이유라고 생각한다. 실제 문제를 지정할 수 있도록 logcat을 게시하십시오.

7

당신이 시도하는 코드의 예제를 보지 않고는 명확하게 말할 수 없습니다 (우리는 여기서 읽지 않습니다). 그러나? ... 나, 당신은 이런 일을하고있는 추측 할 수

public class MyActivity extends Activity { 

    TextView tv1; // This is fine. 
      TextView tv2 = (TextView) findViewById(R.id.textview2); // Don't do this. 

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

     tv1 = (TextView) findViewById(R.id.textview1); // This is fine 
     tv1.setText("Some text"); // This works 

     tv2.setText("Some text"); // NullPointerException here 

    } 
} 

당신이 setContenetView(...)를 호출하고 그 결과로, tv2가 null되기 전에 당신이 findViewById(...)을 사용하기 때문에 tv2.setText(...)가 실패합니다.

Activity에서 위젯을 인스턴스 멤버로 선언해도 괜찮습니까? 콘텐츠 뷰를 설정하기 전까지는 findViewById(...)을 사용하지 마십시오.

+0

findViewById를 사용하십시오. 문제는 필자가 사용하는 방법으로 동일한 객체를 반복해서 사용하고 싶지 않다는 것입니다. OnCreate에서 시작하면 언어 제한으로 인해 OnCreate에서 시작됩니다. 여기에 아무것도없는 경우 수정하십시오. 이 경우, 내 xml 객체를 만들고 초기화 할 수 있습니까? 미스터 스 쿼크 (MisterSquonk)가 제공 한 샘플 코드가 궁금했던 다른 사람들에게 내가 한 일입니다. –

+0

'onCreate (...) '에서'findViewById (...)'를 호출하면, 그들은'Activity'의 범위 내에서 다양한 객체들을 계속 가리킬 것입니다. 즉, 위의 코드에서'tv1'은'MyActivity'가 파괴 될 때까지'MyActivity'의 모든 메소드에 유효합니다. – Squonk

0

는 위젯을 선언하는 것은에서 onCreate 내부 된 setContentView()() 후에 다시 초기화

Button stopTimer; 
Button startTimer; 
EditText totalTime; 
EditText enterMin; 
EditText enterSec; 

다음 단지에서 onCreate() 메소드 외부 이름을 개체를 시도

좋은 추측 친구가 :) 내가하려고했던
setContentView(R.layout.main); 
stopTimer = (Button)findViewById(R.id.StopTimer); 
startTimer = (Button)findViewById(R.id.StartTimer); 
totalTime = (EditText)findViewById(R.id.TotalTime); 
enterMin = (EditText)findViewById(R.id.EnterMin); 
enterSec = (EditText)findViewById(R.id.EnterSec); 
+0

분명히 말하자면, 기본적으로 이들이 전역 적으로 액세스 할 수 있습니까? –