Sunday 7 January 2018

android - Update TextView during long Thread process

itemprop="text">


Just to be clear, this
question is not about how to update a TextView from a Thread,
that's working fine. The problem is that even if I make multiple calls to update the
TextView throughout the Thread, the updates only appear after the Thread is done it's
work. Here's an example:



public class NDThread
extends Thread {

protected LogActionListener
log_listener;
private Handler handler = new
Handler();


public void run() {

logAction("starting");

// Do many things..

logAction("halfway");
// Many more things..

logAction("done");
}

public interface LogActionListener
{
public void onLogAction(String paramString);

}


public void logAction(final String str) {

if(log_listener != null) handler.post(new Runnable() {
@Override

public void run() {
log_listener.onLogAction(str);
}

});

}
}



And in my
main Activity, I implement LogActionListener to recieve the
Strings and update the TextView:



NDThread
thread = new
NDThread();
thread.setOnLogActionListener(this);
thread.run();

//
Elsewhere..
@Override
public void onLogAction(final String msg)
{

handler.post(new Runnable() {


@Override
public void run() {
textView.append(msg);

}


});
}



As you
can see, I've used Handlers in both the Thread and the Activity
because I wasn't really sure which was correct to use. However, the result is always a
blank TextView for the entirety of the Thread, then at the end it will print the 3
lines. What am I doing wrong?


itemprop="text">
class="normal">Answer



Avoid
Thread and Go For
AsyncTask



What you are
looking for is onProgressUpdate(Progress...) ,
publishProgress(Progress...)
of
AsyncTask



Google for their code
samples.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...