Reputation: 49
I'm using a child class which extends from main to setup some buttons. I am able to change variables created in main, such as TotalMoney from within child.
The problem is findViewById is giving a nullpointer exception. The code within buildthem() works fine when used in the main class.
I am using setContentView(R.layout.main); from within OnCreate in main. The Child class is instantiated and called from OnResume in main class.
Do I need to setContentView in the child aswell, or pass the content view from the main class somehow?
package com.chewyapps.markettrader;
class child extends main {
void buildthem(){
TotalMoney = TotalMoney + 9999;
Button MenuButton = (Button) findViewById(R.id.Menu);
//etc
}
}
I can't findViewById in Oncreate because the full code will use
for(i=0; i<buttonIDs.length; i++) {
Button b = (Button) findViewById(buttonIDs[i]);
//do other stuff
}
The for loop is needed for other things relating to each button. If I can get the basic example working though I assume the full code will work.
It hadn't occured to me before to mention this, but the child class is in a seperate file called child.java, from my main.java file in onResume I use:
child childObject = new child ();
childObject.buildthem();
Upvotes: 1
Views: 907
Reputation: 10908
Why not put this line:
Button MenuButton = (Button) findViewById(R.id.Menu);
in onCreate()
, then you can either pass MenuButton
into buildthem()
as a parameter or reference it directly, depending on your design.
Please note that Java convention is to have variable names start with a lowercase letter, so menuButton
not MenuButton
.
EDIT
Then why not create an array of Button
s in onCreate()
that you can later iterate through?
Button myButtons[] = new Button[buttonIDs.length];
for(int i=0; i<buttonIDs.length; i++) {
myButtons[i] = (Button) findViewById(buttonIDs[i]);
}
Then just iterate over the myButtons
array in your child class.
Upvotes: 1
Reputation: 5435
What about:
Button MenuButton = (Button) this.findViewById(R.id.Menu);
or
Button MenuButton = (Button) Child.this.findViewById(R.id.Menu);
Upvotes: 0