4

I have experience with programming languages but am a bit new to android programming.

I have a program with some fields that function as labels(textview), buttons, and data entry(edittext).

Whenever i declare them at the beginning of the program out of any methods(but in the class of course), when I start my application it crashes and simulation gives a "unfortunately, your program has stopped" alert.

Eclipse doesn't give any errors for the declaration and i did use the same way for defining regular variables with no issue. It also gives the same error when i declare a mediaplayer object in the class body.

Does anyone know why it gives error? And is there another way to declare global objects like edittext, viewtext, etc... Declaring them over and over again in methods sounds weird to me.

Thank you!!

public class TrainerActivity extends Activity {

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();
        }
    });
}
Dogan Sinar
  • 41
  • 1
  • 1
  • 3

4 Answers4

8

Without seeing example code of what you're trying it's impossible to say for definite (we don't do mind-reading here). But let me guess, you're doing something like this?...

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

    }
}

The tv2.setText(...) will fail because you used findViewById(...) BEFORE you call setContenetView(...) and as a result, tv2 will be null.

It's quite acceptable to declare your widgets as instance members in your Activity but don't try to use findViewById(...) until AFTER you have set your content view.

Squonk
  • 48,735
  • 19
  • 103
  • 135
  • Good guess buddy :) I was trying to use findViewById. Problem is I don't want to initiate same objects over and over again to be able to use it in my methods. And I believe if I initiate them in OnCreate it will be just initiated in OnCreate due to language restrictions, please correct if I am missing anything here. In this case, is it possible to create and initiate my xml objects globally? For others that were wondering, yes the sample code MisterSquonk gave is what I was doing. – Dogan Sinar Feb 02 '12 at 02:47
  • Once you've called `findViewById(...)` in `onCreate(...)` then they will continue to point at the various objects throughout the scope of your `Activity`. In other words, `tv1` in my code above will be valid for any and all methods in `MyActivity` until `MyActivity` is destroyed. – Squonk Feb 02 '12 at 04:50
1

try declaring the widget objects names only outside the onCreate() method

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

then initialise them after setContentView() inside 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);
Ian Low
  • 399
  • 4
  • 14
0

Can you post a bit of sample code that illustrates the issue? It is fine to declare a member variable that is an EditText or TextView in the class.

logcat(in DDMS) should be give you some info about the error as well. If you are using eclipse there is a tab for DDMS, if not you can just run DDMS from a command line look at the logcat tab and launch your app (with your phone plugged in via usb, of course.) You should be able to see the actual error being reported.

Matt
  • 492
  • 2
  • 12
0

You can declare these variables inside the Class body or inside the method body. In the former case, the variables are global and thus can be accessed within the whole class; in the latter case, they are local and thus can be only accessed within that method. Both of them could be commonly seen in proramming.

In Android, the typical application is that you declare the variables in the Class body and instantiate them in the onCreate() method. Something like this:

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.

}


    }

If you just declare a variable in the Class body,in most caeses, you can't use it until you instantiate it, because they are null before the instantiation. I think this is why you have problems. Please post the logcat so we can specify the real problem.

Huang
  • 4,812
  • 3
  • 21
  • 20