Variable is accessed from within inner class - java

I have these varibles:
private boolean MineRunning;
private BigInteger MineProfit;
etc....
I want to call the countdown method:
countdown(MineRunning, MineProfit, MineTime, MineProgressbar, MineProgressstatus);
ca. 10 Times for different things
The method:
private void countdown(boolean running, BigInteger profit, BigInteger time, ProgressBar progressBar, int progressStatus) {
if(!running && Reference.Storage_Filled.add(profit).compareTo(Reference.Storage_Capacity) == 0 ||
!running && Reference.Storage_Filled.add(profit).compareTo(Reference.Storage_Capacity) == -1){
running = true;
new CountDownTimer(time.longValue(), Reference.countDownInterval.longValue()){
public void onTick(long millisUntilFinished){
progressStatus++;
progressBar.setProgress(progressStatus);
}
public void onFinish(){
Reference.totalGravel = Reference.totalGravel.add(profit);
Gravelrefresh();
progressStatus = 0;
progressBar.setProgress(progressStatus);
running = false;
}
}.start();
}
}
If I call this method i get an error:
variable is accessed from within inner class
I dont want to make the varibles to final because I have to edit these in the method. What can I do instead?
Thanks.

If your inner class is performing work on a separate thread, which seems to be the case here, you cannot access variables from this inner class. What you can do however, you can pass these variables as parameters to your inner class constructor, create new variables, copy them and manipulate.
Or you just declare them as final, that's not a problem most of the time.

Any variable accessed by an inner class must either be final or be a class scoped variable. There is no way around that. Either don't update those variables, or follow the rules.
Adding final normally isn't a problem. Final doesn't prevent you from mutating an object, it just prevents you from assigning to the reference. You can still call a function like setProgress that changes its internal state.

What if you make those variables static
private static boolean MineRunning;
private static BigInteger MineProfit;
...
And make your method parameter less
private void countdown(){
//Your code here
}

Related

How do you create an instance variable to call a non-static method from another class?

class V
{
void print_V(int number)
{
String v= "v";
int count= number;
System.out.print("Letter" + v.repeat(count));
}
void print_V()
{
System.out.print("v");
}
public static void call_Print_V(int n)
{
print_V(n);
}
}
class Main
{
public static void main(String[] args)
{
v call_Print_V = new v();
call_Print_V.print_V(input);
}
}
I tried searching on the Internet for how to create instance methods but found none of them helpful. I tried to format the instance method in a similar way to the examples that I found but I still couldn't get my method to be called.
Try to make the method you want to call public. I assume this is Java.
So instead of:
void print_V()
do:
public void print_V()
Methods of classes are private by default. Private methods can not be called outside of their class scope.
Also, I would consider not declaring public or private bad practise. Same goes for snake case, so please read the following article about code conventions. It makes live for other programmers a lot easier.
https://www.geeksforgeeks.org/java-naming-conventions/
You are trying to call print_V in a non static context.
Give your class a constructor and call the method from the constructor.
Also, the recursive class initialzer call in main only needs to be
new V();
You can refer to your class in there as "this" (keyword) so no reference required if you make an ondestroy listener method for System.exit()
Also, input variable looks like it should be args[1] from main array argument to feed into constructor as argument
new V(new Integer(args[1]).intValue());
An instance variable is any non-static variable "created as a global at construction time".
It usually is initialised in a constructor, or remains null until something wants to use it. Only globals, instance variables in the class, can remain null until they are required for use.
import W;
class V{
W otherclass; // non static instance variable a global
boolean startedW = false; // non static instance variable a global
int arg1; // this classes non static instance variable a global
// a constructor is for when a class starts
// constructor a constructor is NOT a method only a class initializer
V(int arg1){ // any arguments fed to the class go in the ellipses curved brackets
this.arg1 = arg1;
otherclass = new W();
startedW = true;
// next line calls a method from class W
T typo = otherclass.someMethodToCall();
// would probably follow is more work here but...whatever
}// end of constructor 1
// constructor overloading , a second constructor
V(String args1){
arg1 = new Integer(args1).intValue();
} // end constructor 2
public static void main(String args[]){
// doing anything much in main is difficult
// because of non static context errors for variables and methods
new V(args[1]);
}
}// end class

Object within another object, require them to modify values used elsewhere

I have currently created a new CountDownTimer object in my java file, I then have that timer have an onFinish() method where it makes another new CountDownTimer object that has required functionality in it's own onFinish() method.
However when I create a boolean value outside of the second timer (and maintain it as false) and then attempt to modify this boolean to true within the onFinish() method of the second timer it gives me the error:"Variable [boolean variable name] is accessed from within inner class, needs to be declared final".
When I declare the variable final though I absolutely cannot modify it.
So what is the most effective way to go about resolving this problem? I cannot lose the functionality of the timers, yet my experience with java is very shallow. I apologise if this question seems silly.
I would love to also use something like a getter/setter method but with a timer I am not sure if that would even be effective.
Thank you to everyone who replies in advance! It is greatly appreciated! :)
For the sake of clarity: I require the timer to set a boolean flag that will detect that the second timer has indeed finished. This will set the boolean flag to true and then with that I modify the functionality of a button I created. In a similar fashion I also desire this second timer to initialize a long value to be referenced outside of it as well.
If the boolean = false then the button causes a rejection of the user.
If the boolean = true then the button accepts the user.
And then I use the long number obtained below.
Code as requested:
boolean clickAppropriate = false;
new CountDownTimer(t1, t2) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
mTextField.setText("text");
new CountDownTimer(t3, t4) {
public void onTick(long millisUntilFinished) {
public void onFinish() {
long startTime = System.nanoTime();
clickAppropriate = true;
}
}.start();
}
}.start();
Easiest fix I see here without modifying the structure of your solution is to choose ´final boolean[] clickAppropriate = new boolean[1]´ and work with ´clickAppropriate[0]´ element instead. Choosing AtomicBoolean might give extra benefit if you work with multiple threaded environment.
You can use the this keyword together with the outer class (The class where the boolean is declared) name to access its member.
Example:
public class Outer {
public boolean bool = false;
public class Inner {
public void displayOuterClassVariable () {
System.out.println(Outer.this.bool);
}
}
}
In your case, you need to use your outer class name with clickApprpriate. But it seems like your variable is declared in a method. You have to put that variable in the class in order to use this syntax.
This is an interesting question. The way that you have your code currently structured, you will not be able to alter the contents of your clickAppropriate variable from within your anonymous CountDownTimer class declaration.
This is what Oracle writes in regards to accessing local variables from within Anonymous Classes:
"An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final."
http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
This is the reason why your compiler is giving you this error.
One way that you can access and alter your clickApproriate variable from within your anonymous class is to change this variable from being a local variable to being a class variable.
I was able to successfully compile the below code without any errors.
public class Main
{
static boolean clickAppropriate;
public static void main(String args[])
{
clickAppropriate = false;
new CountDownTimer()
{
public void onFinish()
{
clickAppropriate = true;
};
}.start();
}
}
One thing that I would point out that is not evident - your use of anonymous classes is in affect overriding any code declared in your class file. For example, each time you declare your anonymous class CountDownTimer as follows:
new CountDownTimer(t1, t2) {
public void onTick(long millisUntilFinished) {
}
};
This is overriding any code in the onTick() method that might be present in the CountDownTimer class file. This is correct when the onTick() method is abstract, but might not be what you had intended if this method is a regular class method. Best of luck.

Static variables, threads and constructor Java

I have seen this from a recognised sample book so its hard to question then there is something I dont understand.
A class called DataflightsService contains a private static variable called FlightFileAccess that appears to be instantiated everytime we create a new object for DataflightsService as FlightFileAccess's initiation its in the constructor
ie
public class DataflightsService{
private static FlightFileAccess fileAccess=null;
public DataflightsService(String path){
fileAccess=new flightFileAccess(path);
}
public boolean removeflight(String code){
//We use this static instance that wraps functionality to remove a flight
fileAccess.remove(code);
}
}
For me that means that every time we create an instance of DataflightsService, in the constructor are using a different object all the time for the static variable FlightFileAccess
In the original FlightFileAccess Class: we have the remove method that synchronizes a RandomAccessFile
Class FlightFileAccess{
private RandomAccessFile database = null;
private boolean remove(String code){
// Other code goes here and there
synchronized (database) {
//Perform deletion code
}
}
So because we are using a different reference of FlightFileAccess we are also using a different reference of RandomAccessFile?
That means that having FlightFileAccess as static in service does not serve here to synchronize on the RandomAccessFile because it is a new one every time so each DataflightsService instance will do their thing on the random access file ignoring the synchronization.
As opposed to instantiating FlightFileAccess in a static initiator. Am I right?
I would appreciate as many explanations as possible to provide the best way to be able to instantiate DataflightsService as many times as we want (as lets say imagining each client has their own instance of DataflightsService) and after that being able to synchronize on a file for removals for example so that there is no mess of several clients accessing the file. Sorry I need to include a DataflightsService per client bc there are no cookies.
Your example won't compile because the name of the constructor doesn't match the class. But if you mean to name the constructor public DataflightsService(), then part of the issue is that you are overwriting the static variable each time a new object is created.
It sounds like you want this static variable to be initialized only once. Normally you would just assign the variable directly with private static final FlightFileAccess fileAccess = new FlightFileAccess(); or if you wanted to add more logic as if you had a constructor, you could use a static initializer block as follows:
public class Dataflights {
private static final FlightFileAccess fileAccess;
static {
// Static initializer block gets run once when the class is first referenced.
// Not usually used unless you want to add more logic besides just initializing variables.
fileAccess = new FlightFileAccess();
}
private final String path;
public final int id;
public Dataflights(String path) {
this.path = path;
this.id = fileAccess.generateId();
}
static class FlightFileAccess {
private volatile int nextId = 0;
synchronized public int generateId() {
return nextId++;
}
}
public static void main(String[] args) {
Dataflights d = new Dataflights("my/path");
System.out.println("Id is: " + d.id);
}
}
There are many ways to handle contention. I recommend Java Concurrency in Practice if you aren't familiar with Java concurrency.
You are on the right track in your FlightFileAccess class. I can't see the details, but you might also want to use the synchronized keyword in the signature of the remove() method to protect the entire function first. Then, once you have things working, use more tightly targeted synchronize {...} blocks to reduce the amount of code that has to be singly threaded.

Declaring class inside a method - Final keyword [duplicate]

This question already has answers here:
Cannot refer to a non-final variable inside an inner class defined in a different method
(20 answers)
Why are only final variables accessible in anonymous class?
(15 answers)
Closed 9 years ago.
Given the following inner class (IsSomething) within a method:
public class InnerMethod {
private int x;
public class Something {
private int y;
public void printMyNumber(double x)
{
class IsSomething extends Something {
public void print() {
System.out.println(x);
}
}
}
}
}
Why does the X variable has to be FINAL to make it work..?
(I'm talking ofc about the X parameter of the "printMyNumber" function.)
The difference is between local variables vs class member variables. A member variable exists during the lifetime of the enclosing object, so it can be referenced by the inner class instance. A local variable, however, exists only during the method invocation, and is handled differently by the compiler, in that an implicit copy of it is generated as the member of the inner class. Without declaring the local variable final, one could change it, leading to subtle errors due to the inner class still referring to the original value of that variable.
Final local variables
There are two reasons I know for making a local variable or a
parameter final. The first reason is that you don't want your code
changing the local variable or parameter. It is considered by many to
be bad style to change a parameter inside a method as it makes the
code unclear. As a habit, some programmers make all their parameters
"final" to prevent themselves from changing them. I don't do that,
since I find it makes my method signature a bit ugly.
The second reason comes in when we want to access a local variable or
parameter from within an inner class. This is the actual reason, as
far as I know, that final local variables and parameters were
introduced into the Java language in JDK 1.1.
public class Access1 {
public void f() {
final int i = 3;
Runnable runnable = new Runnable() {
public void run() {
System.out.println(i);
}
};
}
}
Inside the run() method we can only access i if we make it final in the outer class. To understand the reasoning, we have to
look at what the compiler does. It produces two files, Access1.class
and Access1$1.class. When we decompile them with JAD, we get:
public class Access1 {
public Access1() {}
public void f() {
Access1$1 access1$1 = new Access1$1(this);
}
}
and
class Access1$1 implements Runnable {
Access1$1(Access1 access1) {
this$0 = access1;
}
public void run() {
System.out.println(3);
}
private final Access1 this$0;
}
Since the value of i is final, the compiler can "inline" it into the inner
class. It perturbed me that the local variables had to be final to be
accessed by the inner class until I saw the above.
When the value of the local variable can change for different
instances of the inner class, the compiler adds it as a data member of
the inner class and lets it be initialised in the constructor. The
underlying reason behind this is that Java does not have pointers, the
way that C has.
Consider the following class:
public class Access2 {
public void f() {
for (int i=0; i<10; i++) {
final int value = i;
Runnable runnable = new Runnable() {
public void run() {
System.out.println(value);
}
};
}
}
}
The problem here is that we have to make a new local data member each time we go through the for loop, so a thought I had today
while coding, was to change the above code to the following:
public class Access3 {
public void f() {
Runnable[] runners = new Runnable[10];
for (final int[] i={0}; i[0]<runners.length; i[0]++) {
runners[i[0]] = new Runnable() {
private int counter = i[0];
public void run() {
System.out.println(counter);
}
};
}
for (int i=0; i<runners.length; i++)
runners[i].run();
}
public static void main(String[] args) {
new Access3().f();
}
}
We now don't have to declare an additional final local variable. In fact, is it not perhaps true that
int[] i is like a common C pointer to an int? It took me 4 years to
see this, but I'd like to hear from you if you have heard this idea
somewhere else.
The methods in an anonymous class don't really have access to local variables and method parameters. Rather, when an object of the anonymous class is instantiated, copies of the final local variables and method parameters referred to by the object's methods are stored as instance variables in the object. The methods in the object of the anonymous class really access those hidden instance variables.
From the JLS :
Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned (§16) before the body of the inner class.
This is because the lifetime of an instance of a local class can be much longer than the execution of the method in which the class is defined. For this reason, a local class must have a private internal copy of all local variables it uses (these copies are automatically generated by the compiler). The only way to ensure that the local variable and the private copy are always the same is to insist that the local variable is final.

Global variables in Java

How do you define Global variables in Java ?
To define Global Variable you can make use of static Keyword
public class Example {
public static int a;
public static int b;
}
now you can access a and b from anywhere
by calling
Example.a;
Example.b;
You don't. That's by design. You shouldn't do it even if you could.
That being said you could create a set of public static members in a class named Globals.
public class Globals {
public static int globalInt = 0;
///
}
but you really shouldn't :). Seriously .. don't do it.
Another way is to create an interface like this:
public interface GlobalConstants
{
String name = "Chilly Billy";
String address = "10 Chicken head Lane";
}
Any class that needs to use them only has to implement the interface:
public class GlobalImpl implements GlobalConstants
{
public GlobalImpl()
{
System.out.println(name);
}
}
You are better off using dependency injection:
public class Globals {
public int a;
public int b;
}
public class UsesGlobals {
private final Globals globals;
public UsesGlobals(Globals globals) {
this.globals = globals;
}
}
Lots of good answers, but I want to give this example as it's considered the more proper way to access variables of a class by another class: using getters and setters.
The reason why you use getters and setters this way instead of just making the variable public is as follows. Lets say your var is going to be a global parameter that you NEVER want someone to change during the execution of your program (in the case when you are developing code with a team), something like maybe the URL for a website. In theory this could change and may be used many times in your program, so you want to use a global var to be able to update it all at once. But you do not want someone else to go in and change this var (possibly without realizing how important it is). In that case you simply do not include a setter method, and only include the getter method.
public class Global{
private static int var = 5;
public static int getVar(){
return Global.var;
}
//If you do not want to change the var ever then do not include this
public static void setVar(int var){
Global.var = var;
}
}
Truly speaking there is not a concept of "GLOBAL" in a java OO program
Nevertheless there is some truth behind your question because there will be some cases where you want to run a method at any part of the program.
For example---random() method in Phrase-O-Matic app;it is a method should be callable from anywhere of a program.
So in order to satisfy the things like Above "We need to have Global-like variables and methods"
TO DECLARE A VARIABLE AS GLOBAL.
1.Mark the variable as public static final While declaring.
TO DECLARE A METHOD AS GLOBAL.
1. Mark the method as public static While declaring.
Because I declared global variables and method as static you can call them anywhere you wish by simply with the help of following code
ClassName.X
NOTE: X can be either method name or variable name as per the requirement and ClassName is the name of the class in which you declared them.
There is no global variable in Java
Nevertheless, what we do have is a static keyword and that is all we need.
Nothing exists outside of class in Java. The static keyword represents a class variable that, contrary to instance variable, only has one copy and that transcends across all the instances of that class created, which means that its value can be changed and accessed across all instances at any point.
If you need a global variable which can be accessed beyond scopes, then this is the variable that you need, but its scope exists only where the class is, and that will be all.
Nothing should be global, except for constants.
public class MyMainClass {
public final static boolean DEBUGMODE=true;
}
Put this within your main class. In other .java files, use it through:
if(MyMainClass.DEBUGMODE) System.out.println("Some debugging info");
Make sure when you move your code off the cutting room floor and into release you remove or comment out this functionality.
If you have a workhorse method, like a randomizer, I suggest creating a "Toolbox" package! All coders should have one, then whenever you want to use it in a .java, just import it!
There is no such thing as a truly global variable in Java. Every static variable must belong to some class (like System.out), but when you have decided which class it will go in, you can refer to it from everywhere loaded by the same classloader.
Note that static variables should always be protected when updating to avoid race conditions.
Understanding the problem
I consider the qualification of global variable as a variable that could be accessed and changed anywhere in the code without caring about static/instance call or passing any reference from one class to another.
Usually if you have class A
public class A {
private int myVar;
public A(int myVar) {
this.myVar = myVar;
}
public int getMyVar() {
return myVar;
}
public void setMyVar(int mewVar) {
this.myVar = newVar;
}
}
and want to access and update myvar in a class B,
public class B{
private A a;
public void passA(A a){
this.a = a;
}
public void changeMyVar(int newVar){
a.setMyvar(newVar);
}
}
you will need to have a reference of an instance of the class A and update the value in the class B like this:
int initialValue = 2;
int newValue = 3;
A a = new A(initialValue);
B b = new B();
b.passA(a);
b.changeMyVar(newValue);
assertEquals(a.getMyVar(),newValue); // true
Solution
So my solution to this, (even if i'm not sure if it's a good practice), is to use a singleton:
public class Globals {
private static Globals globalsInstance = new Globals();
public static Globals getInstance() {
return globalsInstance;
}
private int myVar = 2;
private Globals() {
}
public int getMyVar() {
return myVar;
}
public void setMyVar(int myVar) {
this.myVar = myVar;
}
}
Now you can get the Global unique instance anywhere with:
Globals globals = Globals.getInstance();
// and read and write to myVar with the getter and setter like
int myVar = globals.getMyVar();
global.setMyVar(3);
public class GlobalClass {
public static int x = 37;
public static String s = "aaa";
}
This way you can access them with GlobalClass.x and GlobalClass.s
If you need to update global property, a simple getter/setter wrapper class can be used as global variable. A typical example is shown below.
public class GlobalHolder {
private static final GlobalHolder INSTANCE = new GlobalHolder();
private volatile int globalProperty;
public static GlobalHolder getInstance() {
return INSTANCE;
}
public int getGlobalProperty() {
return globalProperty;
}
public void setGlobalProperty(int globalProperty) {
this.globalProperty = globalProperty;
}
public static void main(String[] args) {
GlobalHolder.getInstance().setGlobalProperty(10);
System.out.println(GlobalHolder.getInstance().getGlobalProperty());
}
}
public class GlobalImpl {
public static int global = 5;
}
you can call anywhere you want:
GlobalImpl.global // 5
Creating an independent file, eg. Example.java to use the 1st solution, is just fine. You can do that also within the app, if e.g. the global variables are special to your current app, etc.:
Create a class at the beginning and declare your variables in there:
class Globals {
static int month_number;
static String month_name;
}
You can then access these variables -- using them as 'Globals.month_number', etc. -- from averywhere in your app.
very simple:
class UseOfGlobal
{
private static int a;
private static int b;
}
but it is always good to have local variables defined inside method blocks where ever possible.
As you probably guess from the answer there is no global variables in Java and the only thing you can do is to create a class with static members:
public class Global {
public static int a;
}
You can use it with Global.a elsewhere. However if you use Java 1.5 or better you can use the import static magic to make it look even more as a real global variable:
import static test.Global.*;
public class UseGlobal {
public void foo() {
int i = a;
}
}
And voilà!
Now this is far from a best practice so as you can see in the commercials: don't do this at home
There are no global variables in Java, but there are global classes with public fields. You can use static import feature of java 5 to make it look almost like global variables.
Generally Global variable (I assume you are comparing it with C,Cpp) define as public static final
like
class GlobalConstant{
public static final String CODE = "cd";
}
ENUMs are also useful in such scenario :
For Example Calendar.JANUARY)
To allow an unqualified access to static members of another class, you can also do a static import:
import static my.package.GlobalConstants;
Now, instead of print(GlobalConstants.MY_PASSWORD);
you can use the Constant directly: print(MY_PASSWORD);
See What does the "static" modifier after "import" mean? to decide about.
And consider the answer of Evan Lévesque about interfaces to carry the Constants.
// Get the access of global while retaining priveleges.
// You can access variables in one class from another, with provisions.
// The primitive must be protected or no modifier (seen in example).
// the first class
public class farm{
int eggs; // an integer to be set by constructor
fox afox; // declaration of a fox object
// the constructor inits
farm(){
eggs = 4;
afox = new fox(); // an instance of a fox object
// show count of eggs before the fox arrives
System.out.println("Count of eggs before: " + eggs);
// call class fox, afox method, pass myFarm as a reference
afox.stealEgg(this);
// show the farm class, myFarm, primitive value
System.out.println("Count of eggs after : " + eggs);
} // end constructor
public static void main(String[] args){
// instance of a farm class object
farm myFarm = new farm();
}; // end main
} // end class
// the second class
public class fox{
// theFarm is the myFarm object instance
// any public, protected, or "no modifier" variable is accessible
void stealEgg(farm theFarm){ --theFarm.eggs; }
} // end class
Going by the concept, global variables, also known as instance variable are the class level variables,i.e., they are defined inside a class but outside methods. In order to make them available completely and use them directly provide the static keyword.
So if i am writing a program for simple arithmetical operation and it requires a number pair then two instance variables are defined as such:
public class Add {
static int a;
static int b;
static int c;
public static void main(String arg[]) {
c=sum();
System.out.println("Sum is: "+c);
}
static int sum() {
a=20;
b=30;
return a+b;
}
}
Output: Sum is: 50
Moreover using static keyword prior to the instance variables enable us not to specify datatypes for same variables again and again. Just write the variable directly.
In general, Java doesn't have any global variables. Other than local variables, all variables comes under the scope of any class defined in the program.
We can have static variables to have the scope of global variables.
without static this is possible too:
class Main {
String globalVar = "Global Value";
class Class1 {
Class1() {
System.out.println("Class1: "+globalVar);
globalVar += " - changed";
} }
class Class2 {
Class2() {
System.out.println("Class2: "+globalVar);
} }
public static void main(String[] args) {
Main m = new Main();
m.mainCode();
}
void mainCode() {
Class1 o1 = new Class1();
Class2 o2 = new Class2();
}
}
/*
Output:
Class1: Global Value
Class2: Global Value - changed
*/
Object-Oriented Programming is built with the understanding that the scope of variables is closely exclusive to the class object that encapsulates those variables.
The problem with creating "global variables" is that it's not industry standard for Java. It's not industry standard because it allows multiple classes to manipulate data asyncronized, if you're running a multi-threaded application, this gets a little more complicated and dangerous in terms of thread-safety. There are various other reasons why using global variables are ineffective, but if you want to avoid that, I suggest you resort to Aspect-Oriented Programming.
Aspect-Oriented Programming negates this problem by putting the parent class in charge of the scope through something called "advices", which adds additional behavior to the code without actually modifying it. It offers solutions to cross-cutting concerns, or global variable usage.
Spring is a Java framework that utilizes AOP, and while it is traditionally used for web-applications, the core application can be used universally throughout the Java framework (8.0 included). This might be a direction you want to explore more.
To define Global Variable you can make use of static Keyword
public final class Tools {
public static int a;
public static int b;
}
now you can access a and b from anywhere by calling
Tools.a;
Tools.b;
Yoy are right...specially in J2ME...
You can avoid NullPointerException by putting inside your MidLet constructor
(proggy initialization) this line of code:
new Tools();
This ensures that Tools will be allocated before any instruction
that uses it.
That's it!

Categories