1

I have and android app (java) and currently have an activity that calls a different class (Class A). in Class A i have thread executer pools that are running every second that add values to a Queue. I want to get the values from this Queue to update a textview in my Android activity every second with queue.remove to get the value. How can I Update the textview on the UI thread with every second with values from this queue in class a?

2 Answers2

0

You have to pass your activity to that A class. after that call runOnUIThread() function on that passed variable like it's here is shown. https://stackoverflow.com/a/11140429/11475673
.The passed variable must be Activity class for the runOnUiThread function. And if you want to access the textview the variable must be your activity class type. P.S. make textfield public variable in your activity.

oto
  • 383
  • 4
  • 18
0

In addition to oto's answer, You can also use Handler/Looper:

import android.os.Handler;
import android.os.Looper;

public class UIActivity extends AppCompatActivity {
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        TextView textView = findViewById(R.id.text_view);
        // defines a handler object attached to a UI-thread
        handler = new ViewHandler(Looper.getMainLooper(), textView);
        ClassA classA = new ClassA(this);
    }

    public synchronized void handleState(int state, String message) {
        Message completeMessage = handler.obtainMessage(state, message);
        completeMessage.sendToTarget();
    }
}

ViewHandler.kt:

const val MESSAGE_CODE = 0
class ViewHandler(looper: Looper, private val textView: TextView): Handler(looper) {
    override fun handleMessage(inputMessage: Message) {
        val text: String = inputMessage.obj as String
        when (inputMessage.what) {
            MESSAGE_CODE -> textView.text = text // update TextView  
            // update other UI-elements
            ... 
        }  
    }
}

Update the TextView in ClassA:

public ClassA(UIActivity uiActivity) {
    ...
    // other thread
    queue.add(newValue) // invoke every second
    String oldValue = queue.remove() 
    uiActivity.handleState(MESSAGE_CODE, s);
}
alexrnov
  • 2,346
  • 3
  • 18
  • 34