'How to add our own images via java code to the image view that change continuously?

How to add our own image via java code to the image view. I use ImageUri to set the Image to Image View.

ImageView carView = root.findViewById(R.id.carview);
    if (car.registeredCarsArray.containsKey(logins)){
        String[] carImage = car.registeredCarsArray.get(logins).getCarImageArray();
        for (int i = 0; ; i++) {
            try {
                sleep (1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            carView.setImageURI(Uri.parse(carImage[i%4]));
        }
    }

here activity not starting.(because of infinite for-loop). So, I tried Thread instead of using this in oncreate() function.

new Thread(new Runnable() {
        @Override
        public void run() {
    ImageView carView = root.findViewById(R.id.carview);
    if (car.registeredCarsArray.containsKey(logins)){
        String[] carImage = car.registeredCarsArray.get(logins).getCarImageArray();
        for (int i = 0; ; i++) {
            try {
                sleep (1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            carView.setImageURI(Uri.parse(carImage[i%4]));
        }
    }
        }
    }).start();

then I got this error :(

E/AndroidRuntime: FATAL EXCEPTION: Thread-3
Process: com.example.cardock, PID: 3599
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
    at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:8191)
    at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1420)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source