1

I'm creating an app that has five activities. I have one class with functions and variables that are used in all five activities. I have created a local variable in each activity that initializes the class like this;

localclass = new globalclass(getResouces());

I'm new to android/java development and was wondering about memoryfootprints and such when I tried something. In the first actvity that gets started, localclass get set as formentioned. I then tried to access this variable from the other activities and did this successfully like this in activity second, third and so on;

localclass = com.firstactivity.localclass;

One of the variables the I use are a reference to application resources. In acticity second on onwards I dont get resources like this;

res = getResources();

but like this;

res = com.firstactivity.localclass.res;

This works as long as variables are static. I also access functions in globalclass the same way.

Is this bad pratice?

1615903
  • 32,635
  • 12
  • 70
  • 99
user1086500
  • 380
  • 5
  • 20
  • 1
    First learn about how to write title of question? – Dipak Keshariya Dec 14 '12 at 12:52
  • He he he... I tried to find a good title, but didn't fine one that described my question better than the one I gave. Suggestions are welcome!! ;-) – user1086500 Dec 14 '12 at 13:15
  • 1
    @user1086500: Your question is good, but the fact why it lacks attention was it doesn't have a good title. – Sahil Mahajan Mj Dec 14 '12 at 13:20
  • @user1086500 I don't have any issue about your title but your title is not good and if your question's title is not good then some users are not reading your question. – Dipak Keshariya Dec 14 '12 at 13:21
  • 1
    It could be something like this- _How to acces/refer local resources in global classes_ or whatever it is. and also dont use signatures(**--TOMMY**), the rectangle displaying your name and repo is actually your signature. – Sahil Mahajan Mj Dec 14 '12 at 13:25
  • I understand. I'll try to change it to something more better. But then again, I feel the answers given are good enough to make me reedit my code. Thanks for your feedback! – user1086500 Dec 14 '12 at 13:25

2 Answers2

5

Generally using static class as a variable holder really isn't a good practice. Try passing variables you need in other activities by intents instead. See this as it explains more why this is not a good approach.

Community
  • 1
  • 1
slezadav
  • 6,104
  • 7
  • 40
  • 61
3

Take a look at Application class. You create a class that extends Application:

public class YourApplication extends Application {
    // functions, variables, whatever it is you need across your whole program
} 

You get a reference to your application by calling this in your activities/services:

YourApplication app = (YourApplication)getApplication();

Also, remember to declare the Application in your manifest file.

<application android:name="the.package.name.YourApplication" />
1615903
  • 32,635
  • 12
  • 70
  • 99