In the following Java code I am populating an ArrayList in one class then using the ArrayList in another class. However, the array transfers but is filled with null values. I have debugged the code and the ArrayList does get populated but its values do not transfer.
First Class:
public String[] log = new String[100];
public ArrayList llog= new ArrayList();
int arraypos= 0;
public void nativeKeyPressed(NativeKeyEvent e) {
if (e.getKeyCode() == NativeKeyEvent.VK_ESCAPE) {
GlobalScreen.unregisterNativeHook();
}
System.out.println(" " + NativeKeyEvent.getKeyText(e.getKeyCode()).toLowerCase() + " ");
llog.add(NativeKeyEvent.getKeyText(e.getKeyCode()).toString().toLowerCase());
System.out.println("list:" + llog.get(arraypos));
arraypos = arraypos + 1;
}
public ArrayList getStrokes (){
return this.llog;
}
Second Class:
public void TeslaTimer()
{
int delay = 10000; //1 sec = 1000
int period = 90000; // repeat every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
@Override
public void run()
{
GlobalKeyListener keyl = new GlobalKeyListener();
ArrayList keylog=keyl.getStrokes();
//TeslaLogger savetoFile = new TeslaLogger();
//savetoFile.TeslaLogger(keylog);
System.out.println("Ring Ring");
for(int i =0; i < keylog.size(); i++){
System.out.println(keylog.get(i));
}
}
}, delay, period);
}
The instance of
GlobalKeyListenerinTeslaTimeris not the same instance as the one you are adding to – the are different objects each with their own list.You must make the same instance of
GlobalKeyListeneravailable to yourrun()method, or perhaps use astaticvariable (which is like a global variable).Here’s the Singleton pattern in action that you could use to make it work:
then wherever you need to use it locally:
All code will then be using the same instance.