0

I want to write a code with threads to make a concurrent app. when I click on "Main Thread" button the "doHeavyWork" method starts and show a toast to user when it's finish!

but when I want to use threads and click on "Single Thread" button, the "doHeavyWork" method starts, but at last the program stops and crash.

what is my problem?

I use a physical phone to debug.

these is my code:

package khosravi.mehdi.course.app.thread_test;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;


public class MyTestThreadActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.btnMainThread).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                doHeavyWork();
            }
        });

        findViewById(R.id.btnSingleThread).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Thread thread = new Thread(new Runnable() {

                    @Override
                    public void run() {
                        doHeavyWork();
                    }
                });
                thread.start();
            }
        });

    }


    public void doHeavyWork() {
        String str = "";
        for (int i = 0; i < 7000; i++) {
            str += i;
            Log.i("LOG", "i:" + i);
        }
        Toast.makeText(MyTestThreadActivity.this, "Heavy Work is finish !", Toast.LENGTH_SHORT).show();
    }

}
depperm
  • 10,606
  • 4
  • 43
  • 67
Fakhrane Nassiry
  • 615
  • 1
  • 5
  • 7

1 Answers1

0

Try this code in your activity to run the display-related stuff back on the UI thread.

MyTestThreadActivity.this.runOnUiThread(new Runnable() {

    public void run() {
        Toast.makeText(MainActivity.this, "This is Toast!!!", Toast.LENGTH_SHORT).show();

    }
});
Barett
  • 5,826
  • 6
  • 51
  • 55
br00
  • 1,391
  • 11
  • 21