-1

Error only when i use editText.setText(sbz); What to do? Without Thread, setText works good

public void onstart(View view) {
    setContentView(R.layout.activity_main);
    EditText editText = (EditText)findViewById(R.id.result);
    Toast.makeText(this, "LOG FINISH!", Toast.LENGTH_SHORT).show();
    String str = new String((String) textView1.getText());
    StringBuilder sbz = new StringBuilder();
    new Thread(() -> {
        int x = 0;
        while(x<100) {
            x++;
            sbz.append(str);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        editText.setText(sbz);
    }).start();
RD1706
  • 11
  • 3
  • [How to update views from a non UI thread in android](https://stackoverflow.com/questions/12716850/android-update-textview-in-thread-and-runnable). – ADM Mar 31 '22 at 11:22

2 Answers2

0

Try stringBuffer instead of stringbuilder. Stringbuilder is not syncronized.

Eduard A
  • 370
  • 3
  • 9
0

editText.setText from your Thread is trying to modify an android view from a background thread, this is a forbidden action. You should only modify android views from the UI/Main thread. In your example, you can try posting it to the UI thread

public void onstart(View view) {
    setContentView(R.layout.activity_main);
    EditText editText = (EditText)findViewById(R.id.result);
    Toast.makeText(this, "LOG FINISH!", Toast.LENGTH_SHORT).show();
    String str = new String((String) textView1.getText());
    StringBuilder sbz = new StringBuilder();
    new Thread(() -> {
        int x = 0;
        while(x<100) {
            x++;
            sbz.append(str);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

          editText.post(() -> {
              editText.setText(sbz)
          });

    }).start();
Rafsanjani
  • 4,352
  • 1
  • 14
  • 21