Reputation: 2040
So this seems like an odd question, but there's something I'm not understanding about Android Studio (I just started working with it).
If I want to create a variable in an activity, and then access it within different methods in my activity, I should be able to do that, right? For instance, consider the following code:
public class bakers extends AppCompatActivity {
private Bunz bunz;
BigDecimal baker1Cost = BigDecimal.valueOf(20); //cost of baker1
BigDecimal baker1Bunz = BigDecimal.valueOf(.1); //number of bunz produced by each baker1
TextView baker1CostText = (TextView) findViewById(R.id.baker1Cost);
TextView baker1Owned = (TextView) findViewById(R.id.baker1Owned);
TextView baker1BunzText = (TextView) findViewById(R.id.baker1Bunz);
TextView bunzCount = (TextView) findViewById(R.id.bunzCount3);
TextView moneyCount = (TextView) findViewById(R.id.moneyCount3);
@Override
protected void onResume() {
super.onResume();
setContentView(R.layout.activity_bakers);
bunz = Bunz.getInstance();
bunzCount.setText("Bunz: " + bunz.getBunz());
moneyCount.setText("Money: " + bunz.getMoney());
baker1BunzText.setText(baker1Bunz.toPlainString());
baker1CostText.setText("Cost: " + (baker1Cost));
baker1Owned.setText("Owned: " + bunz.getBaker1());
}
...
In this code, I try to declare and initialize a bunch of variable before my onResume() method, but this doesn't work. I've found that I can declare variables before the onResume() method, but then for instance if I want to update the value of these variables in the onResume() method, that's fine, but if I want to access that variable in another method, such as onClick, I can't do that, and have to redefine the variables.
Is there something I'm doing wrong here? In essence, my question boils down to this: I want to have an instance variable for one activity (not throughout all activities) that I can access and modify anywhere within the activity.
EDIT: It seems as thought initializing and declaring variables before the onResume method works with things like ints, but I can only declare things like Buttons and Textviews - is there any way I can get around this?
Thanks
Upvotes: 2
Views: 1181
Reputation: 341
Why not initialize your variables in the onCreate
method of your Activity? Here you can get an unterstanding of the activity lifecycle.
Upvotes: 1