I've created a Handler
that can be accessed from anywhere within the activity and also written a method to make it easier to call the handler:
private Handler textFromBGThread = new Handler() {
@Override
public void handleMessage (Message msg) {
// Get the string from the msg
String outputString = msg.getData().getString("Output");
// Find the TextView
TextView Output = (TextView)findViewById(R.id.ConsoleOutputView);
// Display the output
Log.i("TextOutput","About to display message: " + outputString);
Output.setText(Output.getText() + outputString);
Log.i("TextOutput","Message displayed");
}
};
private void TextOutputWrapper (String outputText) {
Message msg = new Message();
Bundle bndle = new Bundle();
bndle.putString("Output", "\n" + outputText);
msg.setData(bndle);
textFromBGThread.handleMessage(msg);
}
So then this can be called from a background thread simply with:
TextOutputWrapper("Attemping to connect...");
This will work 1+ times, however, the actual visual change will cause a CalledFromWrongThreadException
to be thrown. Being new to Java & Android, I'm stuck on why this is happening.
I have noticed that the crash tends to happen when there's a slightly longer time period between calls & that if the calls to TextOutputWrapper(String)
are happening very quickly after one another, then it works. For example, this:
int i = 0;
while (i < 200) {
TextOutputWrapper(String.valueOf(i));
i++;
}
works fine.
Having looked at LogCat, it seems that the garbage collector frees up some resources and then the next time TextOutputWrapper(String)
is called, it crashes (when Output.SetText(String)
is called, to be precise), although I'm not exactly sure why that would cause this error.