This my java code how I implemented.
new Thread(new Runnable() {
public void run() {
int count=0;
while (true) {
if(count>5)
count=0;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(""+e);
}
ImageView image = (ImageView) findViewById(R.id.slider);
image.setImageResource(pics[count]);
count++;
}
}
}).start();
I have created a separate Thread to change the images dynamically
Thats because you're trying to set a picture from thread different than UI thread. And you're only allowed to change the UI from the UI thread.
final ImageView image = (ImageView) findViewById(R.id.slider);
image.post(new Runnable() {
#Override
public void run() {
image.setImageResource(pics[count]);
});
This will post your changes into the UI thread's queue.
You can achieve it using the Handler's postDelayed method
public class MyRunnable implements Runnable {
private ImageView imageView;
private boolean exit = false;
public MyRunnable(ImageView n) {
imageView = n;
}
private void setExit() {
exit = true;
}
#Override
public void run() {
if (exit) {
imageView.removeCallbacks(null);
imageView = null;
return;
}
imageView.setImageResource(pics[count++%5]);
imageView.postDelayed(this, 1000);
}
}
Declare a member:
MyRunnable mRunnable = null;
onResume
ImageView image = (ImageView) findViewById(R.id.slider);
image.postDelayed(mRunnable = new MyRunnable(image), 1000);
and onPause call
mRunnable.setExit();
Or you could put your image in Drawable and then use
ImageView.setImageResource (int resId)
Didn't tried but should work fine
Related
How to make a picture that would be updated every 30 seconds ?
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Picasso.with(this).load("http://i.imgur.com/DvpvklR.png").memoryPolicy(MemoryPolicy.NO_CACHE).networkPolicy(NetworkPolicy.NO_CACHE).into(imageView);
You are going to want to use something like a thread to do this.
For example, below your image view:
Runnable imageUpdater = new Runnable() {
#Override
public void run() {
while (true) {
try {
sleep(30000); // 30 seconds in milliseconds
} catch(InterruptedException e) {
// Someone called thread.interrupt() and tried
// to stop the thread executing
return;
}
// Here load the image in the same way as above:
// But you will need to go onto the UI thread first.
image.post(new Runnable() {
public void run() {
Picasso.with(YourActivity.this).load( "http://i.imgur.com/DvpvklR.png").memoryPolicy(MemoryPolicy.NO_CACHE).networkPolicy(NetworkPolicy.NO_CACHE).into(imageView);
}
});
}
}
};
Then you just start the runnable:
Handler handler = new Handler();
handler.post(imageUpdater);
String[] imageLink = {http://i.imgur.com/DvpvklR.png,
http://i.imgur.com/DvpvklR.png, http://i.imgur.com/DvpvklR.png};
int position = 0;
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(runnable);
}
}, 30 * 1000, 30*1000);
Runnable runnable = new Runnable() {
#Override
public void run() {
Picasso.with(this).load(imageLink[position%imageLink.length]).memoryPolicy(MemoryPolicy.NO_CACHE).networkPolicy(NetworkPolicy.NO_CACHE).into(imageView);
position++;
}
};
Hope the above code will help you :)
Hi i'm running an animation and after 2 seconds i want to stop it and close the whole application.
This is my animation:
public void onImageButtonOkClick(View view) {
setContentView(R.layout.success);
final ImageView mAnimLogo = (ImageView) findViewById(R.id.loading_image);
final AnimationDrawable mAnimation = (AnimationDrawable) mAnimLogo.getDrawable();
mAnimLogo.post(new Runnable() {
#Override
public void run() {
mAnimLogo.setVisibility(View.VISIBLE);
mAnimation.start();
}
});
}
and i tried to use finish() after a timer was called - the application closed, but without any animations.
Any Suggestions?
Edit:
public void delay() {
Timer timer = new Timer();
try {
synchronized(timer){
timer.wait(2000);
getParent().finish();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i solved this problem by using a recursive function to check the animation
private void checkAnimation(AnimationDrawable animationDrawable){
final AnimationDrawable animation = animationDrawable;
int timeBetweenChecks = 300;
Handler h = new Handler();
h.postDelayed(new Runnable(){
public void run(){
if (animation.getCurrent() != animation.getFrame(animation.getNumberOfFrames() - 1)){
checkAnimation(animation);
} else{
finish();
}
}
}, timeBetweenChecks);
};
My goal is when the user tap start button, letters "o" "n" "o" "m" and so forth will appear at the center of the screen. "o" will appear first then after a few seconds will be replaced by "n" then "o" and so forth.
note: for brevity, i just make the guessword = onomatopoeia, first. In reality, guessword will changes every time i tap the start bottom.
this is the code:
private String guessword = "onomatopoeia";
private TextView showchar;
private int n = guessword.length();
private char letArray[]= guessword.toCharArray();;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
addStartListener();
}
public void addStartListener(){
Button start = (Button) findViewById(R.id.start);
showchar = (TextView) findViewById (R.id.charView);
start.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Thread thread = new Thread()
{
#Override
public void run() {
try {
for(int i = 0 ; i < n ; i++) {
sleep(1000);
showchar.setText(letArray[i]);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
});
}
thanks for the help
I decided to implement runonuithread but still it crashes:
this is the updated version:
private String guessword = "onomatopoeia";
private TextView showchar;
private int n = guessword.length();
private char letArray[]= guessword.toCharArray();
private Handler handler;
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
handler = new Handler();
showchar = (TextView) findViewById (R.id.charView);
}
public void startGame(View view){
new Thread() {
public void run() {
while(i++ < n) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
showchar.setText(letArray[i]);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
use this code for setting the text in your textview
runOnUiThread(new Runnable() {
#Override
public void run() {
showchar.setText(letArray[i]);
}
});
You are updating ui from a thread which is not possible.
showchar.setText(letArray[i]);
UI must be updated ui thread.
All you are doing is repeatedly setting value to TextView you can use Handler with a delay for this purpose.
You could use runOnUiThread also but i don't see the need for a thread for what you are doing.
Use a Handler. You can find an example #
Android Thread for a timer
I write a Splash Screeen to run at the boot time of application
public class SplashScreen extends Activity {
ImageView imgView;
int[] imgID = new int[]{R.drawable.frame0, R.drawable.frame1, R.drawable.frame2, R.drawable.frame3,
R.drawable.frame4, R.drawable.frame5, R.drawable.frame6};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
imgView = (ImageView) findViewById(R.id.imgSplash);
new Thread(new WelcomeScreen()).start();
}
private class WelcomeScreen implements Runnable {
#Override
public void run() {
try {
for (int i = 0; i < imgID.length; i++)
{
imgView.setImageResource(imgID[i]);
sleep(500);
}
} catch (InterruptedException e) {
}finally {
Intent intent = new Intent(SplashScreen.this,LoginActivity.class);
startActivity(intent);
finish();
}
}
}
}
It getting error "Sorry the application has stopped unexpectedly" . I don't know why . Somebody can help me ????
you can not set the resource for yuor ImageView inside a thread different from the UI Thread.
you can use runOnUiThread. It takes as paramter a runnable, and post it in the UI Thread queue. There, the UI thead takes it and update your ImageView. All in all your runnable will become:
private class WelcomeScreen implements Runnable {
#Override
public void run() {
try {
for (int i = 0; i < imgID.length; i++)
{
final int resuorceId = imgID[i];
runOnUiThread(new Runnable() {
#Override
public void run() {
imgView.setImageResource(resuorceId);
}
});
sleep(500);
}
} catch (InterruptedException e) {
}finally {
Intent intent = new Intent(SplashScreen.this,LoginActivity.class);
startActivity(intent);
finish();
}
}
You can not access your views from Thread.
You will need to put your code imgView.setImageResource(imgID[i]); in runOnUiThread
use like:
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
imgView.setImageResource(imgID[i]);
}
});
Thanks
You can not change something in UI from non-UI thread so replace this you code:
imgView.setImageResource(imgID[i]);
to:
runOnUiThread(new Runnable() {
#Override
public void run() {
imgView.setImageResource(imgID[i]);
}
});
//try code this way...
public class SplashScreen extends Activity {
private Intent launchIntent;
private Thread splashThread; //used for perform splash screen operation
private int splashTime = 10000, sleepTime = 50; //used for threading operation
private boolean active = true; //used for touch event
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen); //Set splashscreen.xml here
try {
splashThread = new Thread() { // Creating Thread for splash the screen
#Override
public void run() { // run method implemented to perform threading operation
try {
int waitTime = 0; //counter for threading
do {
sleep(sleepTime); //delay for specific time
if (active)
waitTime += 100;
//write your image code here that display your no. of images
} while (active && (waitTime < splashTime)); //Check touch condition and counter
} catch (Exception e) {
// to handle runtime error of run method
Validation.displayToastMessage(SplashScreen.this, e.toString()); //Call static method of class ToastMessage
}
finish(); //finish current activity
startJustCoupleActivityScreen(); //Call below defined function
}
};
splashThread.start(); //start thread here
} catch (Exception e) {
message("SplashScreen : "+ e.toString()); //Call static method of class ToastMessage
}
}
public void startJustCoupleActivityScreen() {
launchIntent=new Intent(SplashScreen.this,JustCoupleActivity.class); //call Next Screen
startActivity(launchIntent); //start new activity
}
#Override
public boolean onTouchEvent(MotionEvent event) { //onTouch Event
//on touch it immediate skip splash screen
if(event.getAction()==MotionEvent.ACTION_DOWN) active=false; //Check Touch happened or not
return true;
}
public void message(String msg)
{
Validation.displayToastMessage(SplashScreen.this, msg); //display Error Message
}
}
I would like to make an animation, I have 10 images of a ball and I want to do:
Image1 visible, all the other images hidden
Image2 visible all the other images hidden
...
Image10 visible all the other images hidden
Should I do that in one animation (how?) or should I create a java method showImage(String pathimage) which would show the image located at pathimage and hide the others? Could I put any idea of time delay with using
handler.postDelayed(new Runnable() {
public void run() { }
}
EDIT, here is my code
The problem is that run() is always called in what seems to be an infinite loop. But I don't see where is my error
GAMEACTIVITY
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
ImageView image2 = (ImageView) findViewById(R.id.imageView3);
image2.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
myAsyncRunnable mar = new myAsyncRunnable(GameActivity.this);
mar.execute(null);
PhotoTask photoTask = new PhotoTask(camera,surfaceCamera,isPreview,holder,GameActivity.this);
photoTask.execute(null);
Log.w("GAMEACTIVITY","PHOTOTASK");
return false;
}
});
}
My Async Task
public class myAsyncRunnable extends AsyncTask<Void, Boolean, Void> {
GameActivity gameactivity;
#Override
protected Void doInBackground(Void... params) {
pull();
return null;
}
public myAsyncRunnable(GameActivity gameactivity) {
super();
this.gameactivity = gameactivity;
}
public void pull() {
final ImageView image3 = (ImageView) gameactivity.findViewById(R.id.imageView3);
final int drawables[] = new int[] {R.drawable.pull2,R.drawable.pull3,R.drawable.pull4,R.drawable.pull5,R.drawable.pull6,R.drawable.pull7};
Runnable runnable = new Runnable() {
#Override
public void run() {
for (int i=0;i<drawables.length;i++) {
image3.setImageResource(drawables[i]);
gameactivity.handler.postDelayed(this, 500);
Log.w("asyncrunnable","run"+i);
}
}
};
gameactivity.handler.post(runnable);
}
}
You should not create 10 ImageViews to do such animation.
Only one ImageView should suffice! Use a handler to update the Image using any flavor of setImage every x milliseconds or so.
Initialize the images in an array and the current image in an integer :
int drawables[] = new int[] {R.drawable.image1, R.drawable.image2, ...};
int mCurrent = 0;
Then initialize your updater:
Runnable runnable = new Runnable() {
#Override
public void run() {
if(mCurrent>=drawables.length)mCurrent=0;
imageView.setImageResource(drawables[mCurrent]);
mHandler.postDelayed(this, 3000); //every 3 seconds
}
};
Finally when you want to start, just post the runnable:
mHandler.post(runnable);
Your code is wrong:
Try this pull function (although i do not really approve the whole code style but no time to fix that)
public void pull() {
final ImageView image3 = (ImageView) gameactivity.findViewById(R.id.imageView3);
final int drawables[] = new int[] {R.drawable.pull2,R.drawable.pull3,R.drawable.pull4,R.drawable.pull5,R.drawable.pull6,R.drawable.pull7};
for (int i=0;i<drawables.length;i++) {
final int j = i;
Runnable runnable = new Runnable() {
#Override
public void run() {
image3.setImageResource(drawables[j]);
}
};
gameactivity.handler.postDelayed(this, 500 * i);
Log.w("asyncrunnable","run"+i);
}
}
}