Button doesn't work on a new thread

204 Views Asked by At

Previously I had error - something about some loop, I've seen info that it is necessary in that case to start a new thread for button, but still nothing happens, thought logs show no errors now.

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
    private static final int CAPTURE = 9003;
    Button button;
    Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.capture);
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(context, "BUTTON clicked", Toast.LENGTH_LONG).show();
                        Log.d("BUTTON","CLICKED");
                    }
                });
            }
        });
        Intent intent = new Intent(this, CaptureActivity.class);
        intent.putExtra(CaptureActivity.AutoFocus, true);
        startActivityForResult(intent, CAPTURE);
    }
}
1

There are 1 best solutions below

6
On

runOnUiThread mean you are telling the UI thread to execute the passed Runnable as instruction so it won't create a new thread.

Solution : I assume you this code is for demo purpose for threading and UI updation so one of best alternative is to AsyncTask

and remove runOnUiThread function , no need of it


You need to remove this code or move it inside run method

Intent intent = new Intent(this, CaptureActivity.class);
intent.putExtra(CaptureActivity.AutoFocus, true);
startActivityForResult(intent, CAPTURE);

Because you are currently in CaptureActivity not on MainActivity. OnCreate will directly take you to the CaptureActivity where you are expecting the code of MainActivity to run (probably they have same UI)