I m trying to load images in an image switcher from Http server. I didnot find any function like setImageBitmap. So I tried using setImageURI() , but its not getting loaded.
I am tring to switch image after every 3 sec. This is the code. When i m running the codes image is not getting loaded. And app is also getting crased.
String arr[]={"http://192.168.1.7/photos/dummy/1.jpg","http://192.168.1.7/photos/dummy/2.jpg","http://192.168.1.7/photos/dummy/3.jpg"}
dailyWear = (ImageSwitcher) getActivity().findViewById(R.id.imageDailyWear);
dailyWear.setFactory(new ViewSwitcher.ViewFactory() {
#Override
public View makeView() {
ImageView myView = new ImageView(getActivity());
myView.setScaleType(ImageView.ScaleType.FIT_XY);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
return myView;
}
});
dailyWear.setInAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.slide_in_left));
dailyWear.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.slide_out_right));
final Handler handler = new Handler();
final Runnable r = new Runnable() {
int i=0;
public void run() {
weddingWear.setImageURI(Uri.parse(arr[i));
i++;
if (i >= arr.length()-1)
i = 0;
handler.postDelayed(this, 3000);
}
};
handler.postDelayed(r, 1000);
what you can do is first get these images and store it in arraylist of bitmap that you can switch these images
private Context mContext;
private int index = 0;
private final int interval = 3000;
private final int DURATION=1500;
public void animate_Images_In_Top_View_After_Every_Three_Seconds(
ImageSwitcher imageSwitcher, final ArrayList<Bitmap> _Images_List) {
android.view.animation.Animation aniIn = AnimationUtils.loadAnimation(mContext,
android.R.anim.fade_in);
aniIn.setDuration(DURATION);
android.view.animation.Animation aniOut = AnimationUtils.loadAnimation(mContext,
android.R.anim.fade_out);
aniOut.setDuration(DURATION);
final ImageSwitcher _ImageSwitcher = imageSwitcher;
_ImageSwitcher.setInAnimation(aniIn);
_ImageSwitcher.setOutAnimation(aniOut);
_ImageSwitcher.setFactory((android.widget.ViewSwitcher.ViewFactory) mContext);
_ImageSwitcher.setImageDrawable(new BitmapDrawable(_Images_List.get(index)));
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
index++;
index = index % _Images_List.size();
// Log.d("Intro Screen", "Change Image " + index);
_ImageSwitcher.setImageDrawable(new BitmapDrawable(_Images_List.get(index)));
handler.postDelayed(this, interval);
}
};
handler.postDelayed(runnable, interval);
}
and i am using fade in and out animation you can set to your own need.
Related
In one activity of my app, there are an imagview and a textview that are changing every 3 seconds.
I first set this up with a handler and thread runnable. It works fine, but when I use removeCallbacks with the pause button, it will not pause in the middle of the Thread. It completes the Thread runnable before pausing. I need it to pause when the button is clicked no matter where it is in the runnable.
I thought about using an asynctask but I'm not sure how this would work.
I know there has to be a way to do this, as you can pause almost any game you download. Does anyone have any suggestions on the best/easiest way to do this?
Thanks so much!! :)
public class Workout extends AppCompatActivity {
private String[] messages = {"1", "2", "3", "4", "5"};
final Handler handler = new Handler();
private int nextIndex;
String mDrawableName[] = {"bodypart70", "equipment70", "settings70", "time70", "bodypart70"};
private int nextImage;
ImageView image;
private ProgressBar progressBar;
private int progressStatus = 0;
Runnable r = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workout);
image = (ImageView) findViewById(R.id.exerciseImage);
final TextView text = (TextView)findViewById(R.id.textView4);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
//changing
r = new Runnable(){
#Override
public void run(){
if (messages.length > nextIndex) {
//change textview
text.setText(messages[nextIndex++]);
//change image
int resID = getResources().getIdentifier(mDrawableName[nextImage++] , "drawable", getPackageName());
image.setImageResource(resID);
//restart progress bar
progressStatus = 0;
progress();
//do it after 3 seconds
handler.postDelayed(this, 3000);
}
}
};
handler.postDelayed(r, 0);
}
public void progress(){
new Thread(new Runnable() {
public void run() {
long timerEnd = System.currentTimeMillis() + 3 * 1000;
while (timerEnd > System.currentTimeMillis()) {
progressStatus = 3 - (int) (timerEnd - System.currentTimeMillis()) / 1000;
// Update the progress bar
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
}
});
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Log.w("App", "Progress thread cannot sleep");
}
}
}
}).start();
}
public void pauseWorkout(View view){
handler.removeCallbacks(r);
}
public void resumeWorkout(View view){
handler.postDelayed(r, 0);
}
}
It looks like the while-loop in your progress() function is still working after you press your pause button.
Try the following: Create a global boolean that indicates you're in a paused or resuming state. Put it at the top of your code:
boolean resume = true;
Update your while condition in progress()
while (resume && timerEnd > System.currentTimeMillis()) {
Update your workout functions:
public void pauseWorkout(View view){
handler.removeCallbacks(r);
resume = false;
}
public void resumeWorkout(View view){
handler.postDelayed(r, 0);
resume = true;
}
My first attempt at both building a game and using multithreading is going mostly well, but I'm stuck at the moment.
It's a simple Whack a mole clone, so I've got a 3x4 grid of mole ImageViews declared in a layout.xml, then I'm using setContentView(R.layout.layout) to put it up, then a separate thread to make one of them appear for a second, then disappear. Here's my Activity's onCreate():
public class WAM_Activity extends Activity {
private static final int MAKE_VISIBLE = 1;
private static final int MAKE_INVISIBLE = 0;
private ImageView[] mole = new ImageView[11];
private ImageView currentMole;
private int[] moleId = {R.id.mole1, R.id.mole3, R.id.mole4, R.id.mole5, R.id.mole6, R.id.mole7, R.id.mole8, R.id.mole9, R.id.mole10, R.id.mole11, R.id.mole12};
private boolean running = true;
private int randomInt = 0;
private Random rand = new Random();
private Handler handler;
//private WAM_Thread wamthread = new WAM_Thread();
private Context cont = this;
private static Handler h;
Message msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wam_view_layout);
//add ImageViews declared in R.layout.wam_view_layout to ImageView objects
for (int i = 0; i < 11; i++) {
mole[i] = (ImageView) findViewById(moleId[i]);
mole[i].setVisibility(View.INVISIBLE);
mole[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(cont, "You clicked one!", Toast.LENGTH_SHORT).show();
}
});
}
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch(msg.what) {
case MAKE_VISIBLE:
currentMole = (ImageView) msg.obj;
currentMole.setVisibility(View.VISIBLE);
break;
case MAKE_INVISIBLE:
currentMole = (ImageView) msg.obj;
currentMole.setVisibility(View.INVISIBLE);
}
}
};
Runnable runnable = new Runnable() {
public void run() {
while (running) {
randomInt = rand.nextInt(11);
msg = handler.obtainMessage();
msg.obj = mole[randomInt];
msg.what = MAKE_VISIBLE;
handler.sendMessage(msg);
handler.postDelayed(new Runnable() {
#Override
public void run() {
msg = handler.obtainMessage();
msg.obj = mole[randomInt];
msg.what = MAKE_INVISIBLE;
}
}, 1000);
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
All the moles are declared invisible by default in the layout xml file, so this code should be making one of them visible, wait a second, then make him invisible again and then make another visible and repeat. Instead, it's making them all visible all the time. They still respond to taps, but that's it.
Anyone see what I'm doing wrong? I've been struggling with this since last night but I'm really close to getting it right.
Two things:
at the end of your runnable, add a Thread.sleep(1000) so that the background thread pauses after making one thing visible
inside your postDelayed runnable, you're not calling handler.sendMessage
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) {
}}};
}
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);
}
}
}
I am using an ImageSwitcher with a TouchListener to change images from an array. Its working fine but i want it to switch images every x seconds or so, so that I can add imageSwitcher.setImageResource(imageList[curIndex]); to it.
Any suggestions?
Try this,
imageSwitcher.postDelayed(new Runnable() {
int i = 0;
public void run() {
imageSwitcher.setImageResource(
i++ % 2 == 0 ?
R.drawable.image1 :
R.drawable.mage2);
imageSwitcher.postDelayed(this, 1000);
}
}, 1000);
I think it is possible via TimerTask and Timer. please Try this code. I think It help you.
private Handler mHandler;
private Runnable mUpdateResults;
private Timer timerAnimate;
private TimerTask timerTask;
mHandler = new Handler();
mUpdateResults = new Runnable() {
public void run() {
AnimateandSlideShow();
}
};
int delay = 0;
int period = 15000;
timerAnimate = new Timer();
timerTask = new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
};
timerAnimate.scheduleAtFixedRate(timerTask, delay, period);
Public void AnimateandSlideShow()
{
imageSwitcher.setImageResource(imageList[curIndex]);
///Here You need To handle curIndex position.
}