Imri Persiado
Imri Persiado

Reputation: 1889

Comparing between strings goes wrong

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!!

Upvotes: 1

Views: 107

Answers (4)

Caesar Ralf
Caesar Ralf

Reputation: 2233

You are probably having a race codition. The variable that saves lastAddress is 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 synchronized in the blocks where you update/read the variable, or set it to be volatile, 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

Upvotes: 1

Talha
Talha

Reputation: 12719

After lastAddress = t1.getAddress(); if lastAddress is the same value,

you have a problem with this line,

!t1.getAddress().equals(lastAddress)) so you should debug this line

watch

lastAddress

t1.getAddress()

Upvotes: 0

Farzad
Farzad

Reputation: 1142

I am not sure how much this applies to Andriod development but in regular Java world when you have a problem like this it means your thread has a local copy of the variable and that's when you start defining members as volatile. In your case I am not convinced the reference to track object gets updated but you can try and see if defining that reference as volatile will do any help.

Upvotes: 1

Marek Sebera
Marek Sebera

Reputation: 40621

Two possible solutions

  • Using UNIQUE on column in your DB (so it won't contain duplicated data)
  • Debugging the code line ...equals(..., and find out if the strings aren't really different

Upvotes: 2

Related Questions