I have a problem that I want to paste images on ImageView in Android and that images are periodically changed after some interval. Means one by one images shown in ImageView. I am doing this with the help of Thread in java but I got some problem that Thread is not attached and something. Please review my code given below and tell me the exact error and how to remove that error or give me some diffrent way for doing this.
package com.ex.thread;
import com.ex.thread.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
public class thread extends Activity implements Runnable{
/** Called when the activity is first created. */
public static Integer[] mThumbIds = {
R.drawable.al1,R.drawable.al2,R.drawable.al3,R.drawable.al4,
};
Thread th;
ImageView iv;
public void run()
{
for(int i=0;i<3;i++)
{
iv.setImageResource(mThumbIds[i]);
System.out.println("Sanat Pandey");
try{
Thread.sleep(3000);
}catch(Exception e)
{
System.out.println(e);
}
}
}
public void create()
{
Thread th = new Thread(new thread());
th.start();
try{
Thread.sleep(3000);
}catch(Exception e)
{
System.out.println(e);
}
}
@Override
public void onCreate(Bundle savedInstace)
{
super.onCreate(savedInstace);
setContentView(R.layout.main);
create();
}
}
In this blog you will learn how to make Button click ImageView change the Image in Android is Below. First of all create New Project and give the Name And MainACtivity name all that. Now open the MainActivity. // Inflate the menu; this adds items to the action bar if it is present.
You can't use things in the UI thread from a background one. So this call:
iv.setImageResource(mThumbIds[i]);
Has to be done in the main thread. In fact you probably don't need a background thread at all to get the effect you're looking for. You can make that just an activity, no need to implement runnable. and then do something like this:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv = (ImageView) findViewById(R.id.yourImageViewID);
int i = 0;
Runnable r = Runnable(){
public void run(){
iv.setImageResource(mThumbIds[i]);
i++;
if(i >= mThumbIds.length){
i = 0;
}
iv.postDelayed(r, 3000); //set to go off again in 3 seconds.
}
};
iv.postDelayed(r,3000); // set first time for 3 seconds
Try this..It works out well...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);``
//
//
int []imageArray={R.drawable.img1,R.drawable.img2,R.drawable.img3};
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
int i=0;
public void run() {
imageView.setImageResource(imageArray[i]);
i++;
if(i>imageArray.length-1)
{
i=0;
}
handler.postDelayed(this, 50); //for interval...
}
};
handler.postDelayed(runnable, 2000); //for initial delay..
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With