Juliette Evans Juliette Evans - 14 days ago 7
Android Question

The method and the constructor seems to be acting on two different passed in/stored variables

In my adapter, I'm having trouble understanding how a specific variable is able to reference the correct one.

I'm trying to make my adapter work with couchbase lite's live query. I had my adapter looking like this:

LiveQuery query;
Context context;

public MyAdapter(Context context, LiveQuery query) {
this.query= query;
this.context = context;

query.addChangeListener(new LiveQuery.ChangeListener() {
@Override
public void changed(LiveQuery.ChangeEvent event) {
((Activity) MyAdapter.this.context).runOnUiThread(new Runnable() {
@Override
public void run() {
enumerator = event.getRows();
notifyDataSetChanged();
}
});
}
});

query.start();
}


There's a method that stop the liveQuery when I need to:

public void invalidate() {
if (query != null) {
query.stop();
}
}


I'm following this example from their website, but I'm having a hard time understand this:

As far as I understand, the query in this part:

// Let's call this query #1, this is the live query in this instance
this.query


is different from the query in this part:

// And call this query #2, this is the live query that was
// passed-in from the method argument
query.addChangeListener(...
query.start();


So how come you are able to do this:

public void invalidate() {
if (query != null) { // This is query #1, right?
query.stop();
}
}


I thought the liveQuery that you added change listener and started in the constructor is query #2, yet the query in invalidate() is query #1. How can this work?

When we did this at the very beginning:

this.query = query;


No change listener has been added yet and no live query has been started yet, so I didn't think it could work. Where did I get it wrong?

Answer

the constructor assigns the parameter reference to the instance variable, making the parameter and the instance variable aliases of the object. anything done to one is accessible via the other; they are not different objects, only different references to the same object. if you wish to explore this a bit further, i recommend that you change the parameter name to pQuery (or something similar) and resolve the compilation errors that will cause. then you will not be liable to confuse which 'query' is which. remember that reference variables are a two step concept, there is the variable itself and the object that it refers to; these are unlike primitives (but are somewhat easy to confuse).

Comments