I’m trying to create a simple thread that started from a Button but something went wrong.
Here is the code:
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
SendInfo si = new SendInfo();
si.start();
error.setText(si.getError());
}
});
And here is the the thread code:
package com.example.android.location;
public class SendInfo extends Thread
{
private String error;
public void run()
{
this.error = "working";
}
public String getError(){
return this.error;
}
}
For some reason the error instance in the first code block stays empty.
You have a race.
After the
start()call either:1) your code continues and
getErrorreturns null and AFTER that the thread runs.or
2) the thread runs AND finishes and
getErrorwill return “working”.In your case 1) is happening.
Update: actually in theory during option 2 you might not get “working” anyway as the return value. This is due to memory/thread visibility. Synchronizing access to the error variable or in this case just declaring that field volatile fixes that (but not your original problem).