T-he-game T-he-game - 9 days ago 6
Android Question

Variable changed after initialization not reflected in interface

Sorry about the bad title. I really cant think of anyway to word this interesting issue.

I have a rather large class going on, and in that class I have an interface (lets call it foo).

foo is set by the user after the class has finished its intialization. (i.e. someClass.setFoo(randomInterface).

At the top of the class I have a few premade interfaces for this exact reason, and the user will pick one for the particular instance. Lets use the above example.

in my someClass.setFoo I'll have something like this

public final void setFoo(MyInterface interface){
foo = interface;
}


and MyInterface interface will have a call in it, say executeFoo.

interface MyInterface{
void executeFoo();
}


Finally I have my randomFoo interface.

MyInterface randomFoo = new MyInterface(){
@Override
void executeFoo(){
Log.d("Some Stuff here?","Maybe?");
}
}


My issue is when I call the MyInterface.executeFoo() method later (after the user has set the interface correctly, assume for this sake they have), I never see this log popup.

I can't for the life of me figure out why, and I've gone so far as to clean the build (android studio), uninstall it and start over, still to get nothing.

If i by pass the set and just set foo to be randomFoo before the initialization, it works just fine.

So I suppose I am confused on why this is not working, and if I am just misunderstanding something about java.

Below is a brief overview of the class I am working with (Using the example stated above).

In my parent class to this, assume there is a call that goes like so

// ... other parent stuff
SomeClass someClass = new SomeClass();
someClass.setFoo(SomeClass.randomFoo);
someClass.executeFoo();
// ... some random parent stuff after


The SomeClass

public class SomeClass{
public final static MyInterface randomFoo = new MyInterface(){
@Override
public void executeFoo(){
Log.d("Some Stuff here?","Maybe?");
}
};

public final static MyInterface randomFoo1 = new MyInterface(){
@Override
public void executeFoo(){
Log.d("RandomFoo1","RandomFoo1");
}
};

private MyInterface foo;

public SomeClass(){
init();
}

private final void init(){
// This does nothing of relevance here
}

public final void setFoo(MyInterface newFoo){
foo = newFoo;
}

public final void executeFoo(){
foo.executeFoo();
}

interface MyInterface{
void executeFoo();
}
}

Answer

The issue turns out that in the parent class, I was calling someFoo.setFoo multiple times, setting foo to different MyInterfaces. I fixed that and it works just fine.