Vladimir Vladimir - 3 months ago 11
Java Question

android java read/write textview from different threads simultaneously

I have a TextView which is being regularly updated from a background thread.

When I try to read it with

myView.getText()
from inside the UI thread it is a matter of chance to get its content between two updates. Otherwise I just get null.

Is it possible to use something like synchronized or volatile on a TextView (or any UI element) to make sure than it cannot be accessed from two threads at the same time ?

EDIT (Solution): Following the direction from @ridsatrio I created the following class:

import android.widget.TextView;

public class SyncTextView {
TextView syncView;

SyncTextView(TextView view) {
this.syncView = view;
}

public synchronized CharSequence getText () {
return syncView.getText();
}

public synchronized void setText (CharSequence text) {
syncView.setText(text);
}
}

Answer

On the top of my head, you can perhaps define a synchronized method to access your desired View. Something along the lines of:

public void synchronized TextView getTextViewSynchronizedly() {
    // ..return your view here.
}

Once you got this defined, be sure to only allow other components to access your TextView through this method.

Comments