Weldeborn
Weldeborn

Reputation: 114

Whats wrong with my Thread()-code?

I have a question regarding an Android application. I want to, later on, create a game and i am currently trying out classes and functions that I need to understand. At the moment im trying to get a grip of how to use threads in a good way, but my application is "force closing" when i touch the button.

For this test application, all have on the screen is one TextView and one button. The button is calling threadStart() when pressed. (onClick in xml) And what i want it to do is to create a thread which increases the variable value by 1 and then report to the UI thread which then update the textview with the new value.

Can someone see what i am doing wrong with this small pice of code?


package com.weldeborn.tc;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

public class ThreadCounter extends Activity {

    TextView txtCounter1;

    int value=0;
    final Handler mHandler = new Handler();
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            updateResult();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        txtCounter1 = (TextView) findViewById(R.id.counter1);

    }

    protected void threadStart() {
        Thread t = new Thread() {
            public void run() {
                doSomething();
                mHandler.post(mUpdateResults);
            }
        };
        t.start();
    }

    private void doSomething() {
        value = value+1;
    }

    private void updateResult() {
        txtCounter1.setText(value);
    }
}

My code is based on an example from Android Developer: The Common Tasks and how to do them section under the "Handling Expensive Operations in the UI Thread" heading.

I am thankful for any help.

Upvotes: 0

Views: 409

Answers (2)

Robby Pond
Robby Pond

Reputation: 73484

if threadStart is your onClick the signature needs to be

public void threadStart(View v)

Upvotes: 0

Alex
Alex

Reputation: 653

setText doesn't work correctly when you pass an integer, directly. Try converting it to String before:

txtCounter1.setText(String.valueOf(value));

Also, check this answer about the usage of threads that need to update the UI.

Upvotes: 1

Related Questions