I have a class that generates the phone location and it updates a TextView every time a new location has retrieved.
We will name this class as Track.
The Track class contains a sendLocation object which is a Thread.
The sendLocation contatins a Track object and it checks every x time if the TextView has changed(the Track class got a method that returns the TextView string), how?
It save the last address in a string and compares between the last address and the Text View address every x time, if they are diffrent it sends this string to my db.
I do that to avoid duplicates.
My question is, how come it keeps sending same addresses to my db?I mean comparing strings is pretty simple.
Here is some code:
if(!t1.getAddress().equals(lastAddress))
{
lastAddress = t1.getAddress();
//send last address to the db
//sleep for a while
}
t1 is a Track instance.
And here is the getAddress method in Track:
public String getAddress()
{
return this.mAddress.getText().toString();
}
What’s is wrong?it’s a simple string comparing!!
You are probably having a race codition. The variable that saves
lastAddressis still not updated with the latest value when you’re comparing.In a multithread program different threads saves copies of the same shared variable for efficiency. This copy will be updated from time to time, but does not guarantee that all of your threads will see the same value every time they access it. For that, you have to use
synchronizedin the blocks where you update/read the variable, or set it to bevolatile, making all threads points to the same value of variable instead of having a copy of its own.EDIT:
A good link to understand more about what may be happening to you: Threading Stories: Volatile and Synchronized