-4

I want to change the image dynamically with its link in a thread.

public class MainActivity extends AppCompatActivity {
public static final Integer[] images =
        {
                R.drawable.vr_final_icon,
                R.drawable.playnew
        };
public static final String[] Links =
        {
                "http://stackoverflow.com/questions/541487/implements-runnable-vs-extends-thread",
                "http://www.facebook.com",
        };
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
new Thread(new Runnable()
{
        @Override
        public void run()
        {
            try
            {
                Random r = new Random();
                int Low = 0;
                int High = images.length;
                final int Result = r.nextInt(High - Low) + Low;
                INCP(Result);
                Thread.sleep(6000);
                run();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        public void INCP(final int incp)
        {
            Drawable res = getResources().getDrawable(images[incp]);
            ImageView INCPimage = (ImageView) findViewById(R.id.INCP);
            INCPimage.setImageDrawable(res);

            INCPimage.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v)
                {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.addCategory(Intent.CATEGORY_BROWSABLE);
                    intent.setData(Uri.parse(Links[incp]));
                    startActivity(intent);
                }
            });
        }
    }).start();
}

}

But it gives me error that

Only the original thread that created a view hierarchy can touch its views.

How can i solve it ! I want image to change dynamically with its link on run time.

Muhammad wajih
  • 53
  • 1
  • 10

1 Answers1

0

Only main thread can touch views. Change code like this;

Random r = new Random();
            int Low = 0;
            int High = images.length;
            final int Result = r.nextInt(High - Low) + Low;
            runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       INCP(Result);
                    }
                });
            Thread.sleep(6000);
            run();
EmreSURK
  • 419
  • 3
  • 13