Local variable is accessed from within inner class, needs to be declared final (java)

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.

Become a more social person