java – Android; Declare EditText in the class body (in any method)
I have programming language experience, but I'm a little new to Android programming
I have a program that contains fields for textview, buttons, and edit text
Whenever I declare them in any way at the beginning of the program (in class, of course), when I start my application, it crashes and simulates giving an "unfortunately, your program has stopped" alarm
Eclipse doesn't give any declared errors, and I do use the same way to define normal variables without problems The same error occurs when I declare a mediaplayer object in the class body
Who knows why it went wrong? Is there another way to declare global objects, such as EditText, viewtext... It sounds strange to me to declare them again and again in methods
thank you!!
Public class traineractivity extension{
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(); } }); }
Solution
If you don't see the sample code of the code you're trying, it's impossible to say it explicitly (we won't read it here) But let me guess, are you doing such a thing
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 } }
tv2. Settext (...) will fail because you used findviewbyid (...) before calling setcontentview (...), so TV2 will be null
It is entirely acceptable to declare your widget as an instance member in an activity, but do not try to use findviewbyid (...) after setting up the content view