1

I want to call the function p() at regular intervals of time, i have used scheduledatfixedrate method for that. When i run the code i get "Viewroot Called From Wrong Thread Exception" as seen in the log. I added onuithread implementation to the function call to solve this but its of no use.

package com.example.flipper;

import java.io.IOException;

import java.util.Date;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;


import android.os.Bundle;
import android.app.Activity;
import android.app.WallpaperManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class MainActivity extends Activity {

    Button n,p,apply;
    ImageView ivmain;
    int imageId;
    int i = 0;
    TimerTask tt;
    Timer t = new Timer();
    TextView t1;
    View v;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        n = (Button)findViewById(R.id.button1);
        p = (Button)findViewById(R.id.button2);
        apply = (Button)findViewById(R.id.button3);
        ivmain = (ImageView)findViewById(R.id.imageView1);
        ivmain.setImageResource(R.drawable.bangalorelogo);
        t1 = (TextView)findViewById(R.id.textView1);
        MainActivity.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                p();
            }




        });


}

public void p ()

    {
        tt = new TimerTask(){
            public void run()
            {

        Random r = new Random();
        i = r.nextInt(3);
        switch(i)
        {
        case 0:
            ivmain.setImageResource(R.drawable.chennailogo);
            break;
        case 1:
            ivmain.setImageResource(R.drawable.ic_launcher);
            break;
        case 2:
            ivmain.setImageResource(R.drawable.cscaptain);
            break;
        case 3:
            ivmain.setImageResource(R.drawable.chennailogo1);
        default:
            ivmain.setImageResource(R.drawable.ic_launcher);
            break;

        }
        t1.setText(""+i);

            }
        };
        t.scheduleAtFixedRate(tt, 2000, 1000);
    }
BenMorel
  • 34,448
  • 50
  • 182
  • 322

1 Answers1

0

Your method p() is running on the UI thread. However, your Timer "t" has it's own thread, so the TimerTask "tt" isn't executing on the UI thread; it's executing in the TimerTask thread. To solve this, you can run p() off the UI thread and have your TimerTask tt execute a Runnable that runs on the UI thread:

tt = new TimerTask(){
            public void run()
            {new Runnable() { runOnUiThread(touchViews); } } }

Then put all your logic and view manipulation in the Runnable "touchViews."

Jim
  • 10,172
  • 1
  • 27
  • 36