How to create a global variable visible by all classes

Put your problem here if it does not fit any of the other categories.

How to create a global variable visible by all classes

Postby prepbgg » Tue Jan 05, 2010 5:10 pm

Newbie question.

I have some java code which (when simplified) reads as follows:

[import statements]

public class XXX extends Activity {
...
String strAA = "SSS";
...
}

class YYYView extends View {
...
String strBB;
...

public YYYView(Context context){
super(context);
}

@Override protected void onDraw(Canvas canvas){
super.onDraw(canvas);
...
strBB = strAA;
...
}
...
}

My problem is that Eclipse complains that strAA in the onDraw method "cannot be resolved".

How can I create a global variable that can be read (and written to) from within any class within the package?
prepbgg
Freshman
Freshman
 
Posts: 5
Joined: Tue Jan 05, 2010 4:53 pm

Top

Postby wjspoel » Tue Jan 05, 2010 6:01 pm

Make it static, see more info here
wjspoel
Junior Developer
Junior Developer
 
Posts: 18
Joined: Thu Dec 24, 2009 10:40 pm

Postby prepbgg » Tue Jan 05, 2010 6:03 pm

I realised that the problem was that I was trying to refer within class YYYView to a variable associated with class XXX without specifying a specific instance of the class XXX.

I have worked round this by defining the variable within class YYYView instead. Since I know the name (myYYYView) of the instance of YYYView I am able to refer within class XXX to myYYYView.strBB.

However, if in future I need to refer to the Activity class, how would I find the name of the instance of the Activity class?
prepbgg
Freshman
Freshman
 
Posts: 5
Joined: Tue Jan 05, 2010 4:53 pm

Postby wjspoel » Tue Jan 05, 2010 6:12 pm

There are multiple solutions, the best one depends on your structure. But one solutions is:
when you create YYYView within the activity class, you can give the the activity class (this) as parameter to the new YYYView class like
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. YYYView yview = new YYYView(this);
  3.  
  4.  
Parsed in 0.029 seconds, using GeSHi 1.0.8.4
wjspoel
Junior Developer
Junior Developer
 
Posts: 18
Joined: Thu Dec 24, 2009 10:40 pm

Postby prepbgg » Tue Jan 05, 2010 11:19 pm

Thanks for your two replies. I've only just seen the first one, which came in while I was posting my second.

If I follow the "YYYView yview = new YYYView(this);" route, what type do I give the "this" parameter in the definition of the YYYView class? Do I define a constructor with a parameter "Activity thisActivity"?
prepbgg
Freshman
Freshman
 
Posts: 5
Joined: Tue Jan 05, 2010 4:53 pm

Postby prepbgg » Wed Jan 06, 2010 4:02 pm

I've now tried both techniques successfully, and am beginning to understand some aspects of "scope".

Thanks for your advice.
prepbgg
Freshman
Freshman
 
Posts: 5
Joined: Tue Jan 05, 2010 4:53 pm

Top

Return to Other Coding-Problems

Who is online

Users browsing this forum: No registered users and 15 guests