itaied
itaied

Reputation: 7107

TextView.setText outside of onCreate doesn't work

I'm writing an android app where I want to modify a text view. When I'm editing it in the onCreate() method it works fine, but I want to modify it when the user click on the screen. Now I know that the function for clicking on the screen is working, but the text doesn't get modified.

In the onCreate() method (works fine):

    main = (TextView) findViewById(R.id.textView1_hidden_buttons);
    main.append(" " + newString);

Tap screen listener:

class MyGestureListener extends GestureDetector.SimpleOnGestureListener {

    // Clicking on the screen increases counter taps
    @Override
    public boolean onDown(MotionEvent event) {
        synchronized (this) {
            if (busy)
                return true;
            busy = true;
        }

        main = (TextView) findViewById(R.id.textView1_hidden_buttons);
        main.setText("Waiting for other players");

        try {
            JSONObject json = new JSONObject();
            json.put("client", "ready");

            ConnectionHandler.send(json.toString());

            String serverResponse = ConnectionHandler.receive();

            Intent intent;
            intent = new Intent(MainActivity.this,
                    OrderedButtonsActivity.class);
...

The app is waiting on ConnectionHandler.receive(). After calling to modify the text, I call for a wait() method for the app, and after a while to another activity. For a short while (half a second or so) I could see the modified text. Why does it happen and how can I fix it so that the text get modifed after clicking the screen?

Upvotes: 1

Views: 1027

Answers (1)

Emmanuel
Emmanuel

Reputation: 13223

I see a couple of problems here:

1) You are trying to use findViewById() in a class that doesn't extends Activity (or any class that has a findViewById().

2) It seems from your question that you are causing the UI Thread to sleep. Please do not do this. It is bad user experience to freeze the UI Thread. Unicorns and kittens will die for every millisecond the UI Thread is frozen.

The reason why it works if you do it inside onCreate() is because Activity has a findViewById().

Upvotes: 3

Related Questions