Android: changing Image with time interval - android

I am using ImageDownloader class to get images from server and getting these images links using an ArrayList. After downloading the Image I am setting the Image as background of the layout. All is working but I want to change these Images after a specific time interval and set as background different images. I have gone through many posts here but didn't get what I want. As I have all Images links in ArrayList, so how can I set a timer to change the images, coming from that ArrayList.It always show me the first Image at index zero even I have set a timer but the same Image is showing again? Please help me if someone has any code example and see my code what to change there?
final ImagesSerialized item;
final ImageView bgImage=(ImageView) findViewById(R.id.image);
ArrayList<ImagesSerialized> list;
control = (Controller) getApplicationContext();
list = (ArrayList<ImagesSerialized>) control.Table_Images.GetData();
for(int i=0; i<list.size(); i++)
{
item = list.get(i);
}
downloader = new ImageDownloader();
downloader.download(item.imageurl(), bgImage);

I do not know about ImageLoader component but scheduling a timer on a view is quite easy in Android.(Without any additional Object)
final ImageView bgImage=(ImageView) findViewById(R.id.image);
...
new Runnable() {
int updateInterval = 1000; //=one second
#Override
public void run() {
// Any code which goes here will be executed every 'updateInterval'
// change your background here
bgImage.postDelayed(this, updateInterval);
}
}.run();
You can change this template as you wish, suppose I want to stop this timer, for this purpose I have to add a stop method to my runnable(This stop method acts synchronized and do not cause inconsistency in timer inner codes):
Runnable myRunnable = new Runnable() {
int updateInterval = 1000; //=one second
boolean stop = false;
public void stop() {
this.stop = true;
}
#Override
public void run() {
// Any code which goes here will be executed every 'updateInterval'
// change your background here
if(!stop) {
bgImage.postDelayed(this, updateInterval);
}
}
}.run();
Now I can stop it by myRunnable.stop();
EDIT :
You should iterate your array of URLs and pass one of them to your downloader. It can be accomplished by this snippet code:
int arraySize = list.size();
new Runnable() {
int currentIndex = 0;
int updateInterval = 1000; //=one second
#Override
public void run() {
currentIndex += 1;
if(currentIndex == arraySize){
currentIndex = 0;
}
item = list.get(currentIndex);
downloader.download(item.imageurl(), bgImage);
bgImage.postDelayed(this, updateInterval);
}
}.run();

Set up your ImageView like this:
<ImageView
android:id="#+id/imgBackground"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:contentDescription="#string/app_name"
android:scaleType="fitXY" />
You can Use TimerTask to achieve this.
// Declaration and Initialization :
List<String> mImageUrl = new ArrayList<String>();
private ImageLoader mImageLoader = new ImageLoader(MainActivity.this);
Timer timer = new Timer(); // changed
int i = 0;
// Put this code in your onCreate :
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (i < mImageUrl.size()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mImageLoader.DisplayImage(mImageUrl.get(i), img);
i++;
}
});
} else {
i = 0;
}
}
}, 0, 2000);
The timer task will start in 0 seconds and it will change the background every 2 seconds. You can change this as like as you want.
Its working fine. I have tested.
You can read more about the timertask here.
You can also cancel the timer with the help of timer.cancel() HIH.

final ImagesSerialized item;
final ImageView bgImage=(ImageView) findViewById(R.id.image);
ArrayList<ImagesSerialized> list;
control = (Controller) getApplicationContext();
list = (ArrayList<ImagesSerialized>) control.Table_Images.GetData();
for(int i=0; i<list.size(); i++)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
item = list.get(i);
downloader = new ImageDownloader();
downloader.download(item.imageurl(), bgImage)
}
});
}

Try this way hope this will help you for more improvement of your code...
you need "Aquery(AndroidQuery)" jar from this reference :
https://code.google.com/p/android-query/downloads/detail?name=android-query-full.0.24.3.jar
2.now add this jar on your project lib folder and add to build path or as library.
3.now it's time for code using "Aquery(AndroidQuery)" to download images from server(here is my demo code you can modified as per your requirement).
"activity_main.xml"
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imgFromServer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"/>
<ProgressBar
android:id="#+id/pbrImageLoader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</FrameLayout>
</LinearLayout>
"MyActivity.java"
public class MyActivity extends Activity{
private ImageView imgFromServer;
private ProgressBar pbrImageLoader;
private AQuery aQuery;
private int currentIndex;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgFromServer = (ImageView) findViewById(R.id.imgFromServer);
pbrImageLoader = (ProgressBar) findViewById(R.id.pbrImageLoader);
aQuery = new AQuery(this);
currentIndex=0;
final ArrayList<String> imageUrlListFromServer = new ArrayList<String>();
imageUrlListFromServer.add("http://www.mayoff.com/5-01cablecarDCP01934.jpg");
imageUrlListFromServer.add("http://www.allindiaflorist.com/imgs/arrangemen4.jpg");
imageUrlListFromServer.add("http://www.hdwallshub.com/files/submissions/cookie_monster_hd_wallpaper_1405239014.jpg");
imageUrlListFromServer.add("http://images4.fanpop.com/image/photos/17200000/Tangled-offical-wallpapers-tangled-17286338-1680-1050.jpg");
imageUrlListFromServer.add("http://wakpaper.com/large/Moons_wallpapers_4.jpg");
final Timer timer = new Timer();
downloadImagesFromServer(imageUrlListFromServer, 0, new ImageDownloadedListener() {
#Override
public void onDownloadFinish() {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
imgFromServer.setImageBitmap(aQuery.getCachedImage(imageUrlListFromServer.get(currentIndex)));
if(currentIndex == imageUrlListFromServer.size()-1){
currentIndex=0;
}else{
currentIndex++;
}
}
});
}
},0,2000);
}
});
}
private void downloadImagesFromServer(final ArrayList<String> imageUrlList,final int index,final ImageDownloadedListener listener){
aQuery.progress(pbrImageLoader).ajax(imageUrlList.get(index), Bitmap.class, 0, new AjaxCallback<Bitmap>() {
#Override
public void callback(String url, Bitmap object, AjaxStatus status) {
super.callback(url, object, status);
if ((imageUrlList.size() - 1) == index) {
listener.onDownloadFinish();
} else {
downloadImagesFromServer(imageUrlList, index + 1, listener);
}
}
});
}
interface ImageDownloadedListener{
public void onDownloadFinish();
}
}
Note : "Aquery(AndroidQuery)" also cache images on local so it not get same images from server if it already downloaded.

try this code.the images was saved in drawable. please do insert a imageview in xml code. noted that the time interval for the following code is 1 sec.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
public ImageView iv;
public static Integer[] mThumbIds = {
R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4};
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.imageView);
i=0;
t.start();
}
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv.setImageResource(mThumbIds[i]);
i++;
if(i >= mThumbIds.length){
i = 0;
}}});}}
catch (InterruptedException e) {
}}};
}

Related

How to schedule different images to change in design background

I'm currently working on a weather project in Android Studio where I want to schedule image changes in my design background every 5 seconds, I have all the image resources in my #drawable directory. I watched a basic tutorial where they explained some things in the demo but it only helped a little and didn't quite suit me, I'm still confused because I'm getting a lot of errors but I've currently tried these few codes:
HomeActivity.java:
public class HomeActivity extends AppCompatActivity {
public static int count=0;
int[] drawablearray=new int[]{R.drawable.burj_khalifa,R.drawable.central_bank_of_nigeria,R.drawable.eiffel_tower,R.drawable.hong_kong,R.drawable.statue_of_liberty};
Timer _t;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
imageView = findViewById(R.id.imageView);
ImageView = (ConstraintLayout) findViewById(R.id.lnMain);
_t = new Timer();
_t.scheduleAtFixedRate(new TimerTask); {
public void run(); {
runOnUiThread(new Runnable() { // run on ui thread
#Override
public void run() {
if (count < drawablearray.length) {
lnMain.setBackgroundDrawable(drawablearray[count]);
count = (count + 1) % drawablearray.length;
}
}
});
}
}, 5000, 5000);
}
}
Any Idea on how to Organize it to suit the design?
final Handler h = new Handler();
Runnable r = new Runnable() {
public void run() {
Home.this.getWindow.setBackgroundDrawableResource(drawableArray[count]);
cout += (count + 1) % drawableArray.length;
h.postDelayed(this, 5000);
}
};
final Runnable r = new Runnable() {
public void run() {
imageView.setBackgroundDrawableResource(drawablearray[count]);
count += (count+1)%(drawablearray.length);
handler.postDelayed(this, 5000);
}
};
And the call is like this:
handler.postDelayed(r,0);
This will call the runnable to execute and handle.postDelayed will run the method every 5000 millsec.
I already fixed the error by using constraintlayout in place of imageview and inmain. I also got id for the layout:
constraintLayout = findViewById(R.id.layout);
constraintLayout.setBackgroundResource(R.drawable.burj_khalifa);
_t = new Timer();
_t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() { // run on ui thread
#Override
public void run() {
if (count < drawable.length) {
constraintLayout.setBackgroundResource(drawable[count]);
count = (count + 1) % drawable.length;
}
}
});
}
}, 5000, 5000);
}
}

Image view image need to change periodically in android

I have an image view. So in the image view i want to change the images after a certain time period. Images are coming from an array list. Now when the no of images are 3 or more than 3, it is working perfect. But when it is 2, my logic is not working. Second image is visible for a moment and then again changed to first image here is my code:
r = new Runnable(){
int i = 0;
public void run(){
iv.setImageBitmap(alBmps.get(i));
i++;
if(i >= alBmps.size()){
i = 0;
}
iv.postDelayed(r, 5000); //set to go off again in 5 seconds.
}
};
iv.postDelayed(r, 1000);
Can any one help me what changes i need on the above code?
Thanks.
Try this
declare variables
static int i=0;
private Timer myTimer;
in your onCreate or on button click where you want to call and start the methods
myTimer = new Timer();
myTimer.schedule(new TimerTask()
{
#Override
public void run()
{
TimerMethod();
}
}, 500, 5000);
add these methods to your class
private void TimerMethod()
{
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable()
{
public void run()
{
if(i<alBmps.size())
{
iv.setImageBitmap(alBmps.get(i));
}
else
{
i=0;
iv.setImageBitmap(alBmps.get(i));
}
i++;
}
};

Alternate image in a imageview of screen

I have two images in my drawable folder and I desire to alternate the two images in my view every x time.
I try to use a Asynctask but don't work and I can't found the solution.
My xml Code
<ImageView
android:id="#+id/imageload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="64dp"
android:adjustViewBounds="false"
android:baselineAlignBottom="false"
android:contentDescription="#string/imatge"
android:cropToPadding="false"
android:fitsSystemWindows="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:src="#drawable/hdtitol2" />
I call the class with:
new ModifyImage().execute(null,null,null);
The main class contains de class with async code
public class ModifyImage extends AsyncTask<Void, Void, Void> {
ImageView img= (ImageView)findViewById(R.id.imageload);
#Override
protected void onPreExecute(){
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
int i = 0;
boolean opt = true;
boolean exit = false;
while(!exit){
if(i == 1000){
i = 0;
if(!opt){
img.setImageResource(R.drawable.blackhdtitol2);
opt =true;
}else{
opt = false;
img.setImageResource(R.drawable.hdtitol2);
}
}
i++;
}
return null;
}
#Override
protected void onPostExecute(Void i){
}
}
Do this,
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Integer tag = (Integer) img.getTag();
if(tag == R.drawable.blackhdtitol2){
img.setImageResource(R.drawable.blackhdtitol2);
img.setTag(R.drawable.blackhdtitol2);
}else{
img.setImageResource(R.drawable.hdtitol2);
img.setTag(R.drawable.hdtitol2);
}
}
}, 60*1000);
In the end I found a possible solution descarting all de java code that I had about this problem.
The solution that I found is to create a new class
public class RepeatingThread implements Runnable {
private final Handler mHandler = new Handler();
public RepeatingThread() {
}
#Override
public void run() {
final ImageView img = (ImageView) findViewById(R.id.imageload);
if(img.getVisibility() == View.INVISIBLE ){
img.setVisibility(View.VISIBLE);
}else{
img.setVisibility(View.INVISIBLE);
}
mHandler.postDelayed(this, 1000);
}
}
And the code in the function on create:
final Thread t = new Thread(new RepeatingThread());
t.start();

Make android screen change color once per second

I am a beginner to android, with some java under my belt. I have completed the make my first app tutorial only.
Next I want to make an app to use simple 2D graphics
To start, I want to find a way of flashing the screen between two colors (red and green) in an infinite loop
wait int seconds;
make screen red;
wait int seconds;
make screen green;
loop forever;
Could anyone please point me to a tutorial(s) or source code(s) that may help?
Many Thanks
How about you make a layout which fills the screen, lets call it llayout.
put this in the code:
static final int[] COLORS = {0xff0000, 0x00ff00};
static final int WAITTIME = 1000;
int currentColor = 0;
public void onCreate(Bundle b) {
setContentView(R.layout.mylayout);
final LinearLayout llayout = (LinearLayout) findViewById(R.id.llayout);
new Thread() {
public void run() {
while(true) {
Thread.sleep(WAITTIME);
currentColor++;
if (currentColor > COLORS.length)
currentColor = 0;
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
llayout.setBackgroundColor(COLORS[currentColor]);
}
});
}
}
}.start();
}
This should work. Using this code, you can add additional colors to the array COLORS.
Thanks for the input,
This code seems to work OK
package biz.consett.mydraw;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
/* Flash the screen between red and green each second */
public class MainActivity extends Activity {
final static int INTERVAL = 1000; // 1000=1sec
private static View myView = null;
boolean whichColor = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myView = (View) findViewById(R.id.my_view);
myView.setBackgroundColor(Color.RED);// set initial colour
new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(INTERVAL);
}
catch (InterruptedException e) {
e.printStackTrace();
}
updateColor();
whichColor = !whichColor;
}
}
}).start();
}
private void updateColor() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (whichColor)
myView.setBackgroundColor(Color.RED);
else
myView.setBackgroundColor(Color.GREEN);
}
});
}
}
Layout, activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<View
android:id="#+id/my_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</View>
</RelativeLayout>
You already got a lot of solutions but just adding my own...
You will need a timer
#Override
protected void onCreate(Bundle bundle)
{
...
Timer timer = new Timer();
TimerTask updateColor = new SwitchColorTask();
timer.scheduleAtFixedRate(updateColor, 100, 100);
...
}
A timer task.
private boolean colorSwitched;
class SwitchColorTask extends TimerTask {
public void run() {
LinearLayout main = (LinearLayout)findViewById(R.id.main);
if(colorSwitched){
main.setBackgroundColor (Color.GREEN)
}
else{
main.setBackgroundColor (Color.RED)
}
colorSwitched=!colorSwitched
}
}
Taken from this post and edited for your case:
private int m_interval = 1000; // 1 second by default, can be changed later
private Handler m_handler;
private Layout mYourMainLayout //dont know what type of layout you use
private boolean which;
#Override
protected void onCreate(Bundle bundle)
{
...
mYourMainLayout = (Layout) this.findViewById(R.id.yourMainLayout);
m_handler = new Handler();
}
Runnable m_colorChanger = new Runnable()
{
#Override
public void run() {
if(which){
mYourMainLayout.setBackgroundColor(Color.GREEN)
}
else {
mYourMainLayout.setBackgroundColor(Color.RED)
}
which=!which
m_handler.postDelayed( m_colorChanger, m_interval);
}
};
This code implements the array of colors and works fine - many thanks.
(uses same manifest and layout)
package biz.consett.mydraw;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
/*
* Simple use of Android Thread
* Flash the screen between an array of colours at an interval
*
*/
public class MainActivity extends Activity
static final int[] COLORS =
{AColor.RED, AColor.BLUE, AColor.GREEN};// colour array
// Colour Red Green Blue
// Index [0] [1] [2]
private int currentColor = 0;
private View MYVIEW = null;
//boolean whichColor = true;
final int interval = 100; // 0.6 second static final?
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MYVIEW = (View) findViewById(R.id.my_view);
MYVIEW.setBackgroundColor(Color.RED);// set initial colour
new Thread(new Runnable()
{
// #Override
public void run()
{
while (true)
{
try
{
Thread.sleep(interval); // sleep for interval
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
updateColor();
} // end of while true loop
}// end of run
}).start(); // end of runnable
} // end of onCreate bundle
private void updateColor()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
if (currentColor > COLORS.length - 1)
{
currentColor = 0;
}
MYVIEW.setBackgroundColor(COLORS[currentColor]);
currentColor++;
}// end of run
});
}
}// -------------END OF MainActivity extends Activity-----------------------
package biz.consett.mydraw;
public class AColor
{
final static int RED = 0xFFFF0000; // hex alpha_R_G_B
final static int GREEN = 0xFF00FF00;
final static int BLUE = 0xFF0000FF;
final static int PURPLE = 0xFFAA00AA;
}

Animation, delay

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);
}
}
}

Categories

Resources