I'm making an android app, where I want to update a label when the property maxDbRecorded
of the class Measure
changes. So I implemented a PropertyChangeListener in my Activity.
public class AndroidCalibrationTestActivity extends Activity implements PropertyChangeListener {
private Recorder recorder;
private Thread recorderThread;
private Measure measures;
private TextView numberOfMaxDecibels;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
numberOfMaxDecibels = (TextView)findViewById(R.id.txtNumberOfMaxDecibels);
measures = new Measure();
measures.addPropertyChangeListener(this);
recorderThread = new Thread((Runnable) Recorder.getInstance().runRecorder);
recorderThread.start();
}
public void propertyChange(PropertyChangeEvent event) {
numberOfMaxDecibels.setText(event.getNewValue() + "");
}
}
Now I want to set the value of maxDbRecorded
from within my thread. So that the textview numberOfMaxDecibels update.
public class Measure {
private double maxDbRecorded;
private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
public Measure() {
}
//Getters and setters
public double getMaxDbRecorded() {
return maxDbRecorded;
}
public void setMaxDbRecorded(double maxDbRecorded) {
double oldValue = this.maxDbRecorded;
this.maxDbRecorded = maxDbRecorded;
//Fires a property change event
pcs.firePropertyChange("maxDbRecorded", oldValue, maxDbRecorded);
}
//To let classes subscribe for property changed listener
public void addPropertyChangeListener(PropertyChangeListener listener){
pcs.addPropertyChangeListener("maxDbRecorded", listener);
}
}
In the class Recorder, I have my thread where I set maxDbRecorded
, but the PropertyChanged event does not get fired.
It does work if I set maxDbRecorded
directly from the Activity.
public class Recorder {
protected Measure m;
private Recorder() {
m = new Measure();
}
public static Recorder getInstance() {
if(instance == null){
instance = new Recorder();
}
return instance;
}
Runnable runRecorder = new Runnable() {
public void run() {
startRecording();
}
};
public void startRecording() {
//Here happens some recording stuff
double maxDB;
m.setMaxDbRecorded(maxDB);
}
}
I also tryed to make an object of Measure in my Activity and give this instance to the Recorder thread. This gives an error: $CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
You should use an android Handler class to post your call the the ui thread via it.
Check: http://www.vogella.com/articles/AndroidPerformance/article.html