This is a common issue on java and happens when you're trying to access a variable in a nested class.

This issue is very common when you try to use a variable which needs to be accessed from another class !  Sometimes, you don't notice when this will happen, for example using a threadPool on cordova will need an inner class to be executed :

String password = "qweqwe";
String config = "MyObject";

cordova.getThreadPool().execute(new Runnable() { // we are executing a nested class !
	public void run() {
		try {
                        Session session = new Session();
			session.setConfig(config);
			session.setPassword(password);
				 		
		} catch (Exception e) {
			error(e.getMessage().toString());
			e.printStackTrace();  
		}
	}
});

The previous code will throw an exception because you are accesing config and password and it's not a final variable.

This issue can be easily fixed declaring the variable with problem as final.

// Note that you can declare final any kind of variable like objects, classes, numbers etc ...

final String password = "qweqwe";
final String config = "MyObject";

cordova.getThreadPool().execute(new Runnable() { // we are executing a nested class !
	public void run() {
		try {
                        Session session = new Session();
			session.setConfig(config);
			session.setPassword(password);
				 		
		} catch (Exception e) {
			error(e.getMessage().toString());
			e.printStackTrace();  
		}
	}
});

Although the solution is easy, if you don't know how to solve it ,it can be a really headache sometimes.


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors