I would like the user to press a button.
When the onClickListener for the button is called, I would like to display a spinner until the webpage is fetched.
I don't want to use a AsyncTask because it can only be run once and more than likely the user will click the button more than once after the first url results are retreived.
So how would I go about doing this with this onClickListener?
findIT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
item = game.getText().toString();
getUserPreference();
itemLookup.loadUrl(url);
}
});
You can still use AsyncTask<>, you just have to create a new one each time.
public void onClick(View v) {
new DoWhateverTask().execute();
}
Otherwise you can do it yourself using Handlers. Assuming you already have Handlers defined for the UI and a worker thread:
public void onClick(View v) {
showProgress();
workerThreadHandler.Post(new Runnable() {
public void run() {
doNetworkStuff(); // Which will post progress to the UI thread if needed.
mainThreadHandler.Post(new Runnable() {
public void run() {
hideProgress();
}
});
}
});
}
Personally, I think AsyncTask is a nicer solution.
Related
public class MainActivity extends Activity {
ImageView img;
MediaPlayer failure;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bButton= (Button)findViewById(R.id.blueBtn);
img = (ImageView)findViewById(R.id.image);
img.setVisibility(View.VISIBLE);
failure= MediaPlayer.create(this,R.raw.failure_sound);
bButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
img.setVisibility(View.VISIBLE);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
failure.start();
}
});
}
well thats my code.
I just want to make that when I press the button it'll show the image
then wait 1000 miliseconds, and then make a sound.
BUT(!) unfortunaltly when I press that button: the process waits 1000 ms, and then make the sound and shows the img.
help plz!!!
Replace your onClick handler:
public void onClick(View v){
img.setVisibility(View.VISIBLE);
v.postDelayed(new Runnable() {
public void run() { failure.start(); }
},1000);
}
With Thread.sleep(10000); you are causing the main thread to freeze and thus the UI cannot be updated for that amount of time.
If you want to wait for a certain amount of time to do something, you may use a Handler instead, so the UI can be updated in the meantime:
public void onClick(View v){
img.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
public void run() {
failure.start();
}
}, 1000);
}
You're putting your UI thread to sleep, which causes your app to freeze and the image not showing up.
A better approach for this is to use a handler, which will execute code after a delay and will not freeze your UI.
A quick adaption of your clickListener would be:
bButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
img.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
failure.start();
}
}, 1000);
});
}
btnSwitch2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnSwitch2.setImageResource(R.drawable.on);
myVib.vibrate(50);
strobeFlash();
}
});
}
private void strobeFlash(){
for(int i=0; i<10;++i){
turnOnFlash2();
turnOffFlash2();
}
}
The code above executes when a button is pressed, I would like to change the picture of the image button. However, when the button is pressed, the for loop executes first then the line above it
btnSwitch2.setImageResource(R.drawable.on);
executes. Is there something I'm doing that's causing the loop to execute completely first?
Actually for loop execution is faster the then changing the image resource. You can add a postDelay() between the UI update and the for loop execution.
It will solve the issue.
btnSwitch2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnSwitch2.setImageResource(R.drawable.on);
myVib.vibrate(50);
handler=new Handler();
Runnable r=new Runnable() {
public void run() {
strobeFlash();
}
};
handler.postDelayed(r, 3000);
}
});
}
private void strobeFlash(){
for(int i=0; i<10;++i){
turnOnFlash2();
turnOffFlash2();
}
}
I'm creating a simple app that will stream the internet radio station. So when the user clicks the play button I want to show a progress bar (loading circle) until the stream is being played.
I have two Runnables, one to show the progress bar, other to load audio stream and play. This is a progress bar Runnable:
private Runnable showProgressBar = new Runnable() {
#Override
public void run() {
progBar.setVisibility(View.VISIBLE);
}
};
Than on button click:
buttonPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Handler show_progress_h = new Handler();
show_progress_h.post(showProgressBar);
Handler play_h = new Handler();
play_h.post(startPlayingThread);
}
});
But... the progress bar loads much to late. It loads when the radio is almost loaded, so you only see it for a blink. Is it possible to show it immediately after the button was clicked? I have no idea what is slowing it down. Should I use something else instead of Handler?
Oh and btw... I also tried both with no handlers, but the response is the same.
The problem is you are posting long running task on UI thread immidiatly after showing progressbar:
buttonPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Handler show_progress_h = new Handler();
show_progress_h.post(showProgressBar);
Handler play_h = new Handler();
play_h.post(startPlayingThread);//<< issue is here
}
});
Instead do something similar to this:
buttonPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Handler show_progress_h = new Handler();
show_progress_h.post(showProgressBar);
new AsyncTask<Void, Void, Void>(){
#Override
protected void doInBackground(Void v){
// perform long runningtask here that you are performing in
//startPlayingThread
}
}.execute();
}
});
For more detail check this tutorial: http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html#concurrency_asynchtask
You can use new Thread(your_runnable).start() as an alternative, and try debugging it.
So I have an activity which runs a simple snakes and ladders game, and I want to allow the player to click a button and move, which would subsequently be followed by the computer moving. My problem is, that once the player moves, the computer immediately makes its move.
Instead I want the activity to wait before the computer makes its move. I've looked around a lot and found that waiting involves using a thread, but I have failed to implement it without my app crashing
My attempt at declaring a thread:
final Runnable runnable = new Runnable() {
#Override
public void run()
{
while (true)
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
Thread thread= new Thread(runnable);
My onClick() method for the button:
Button rollButton = (Button) (findViewById(R.id.rollButton));
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//executes only if current player is a human
if(GAME_BOARD.getCurrentPlayer().isHuman()) {
GAME_BOARD.rollDie(); // rolls the die
showDie(GAME_BOARD); // displays die on screen
GAME_BOARD.move(); // moves the player and sets next player as current player
playerTurn.setText(GAME_BOARD.getCurrentPlayer().getName() +"'s turn");// sets TextView to display who's player's turn it is
thread.start();
if(!GAME_BOARD.getCurrentPlayer().isHuman()) {
GAME_BOARD.rollDie();
showDie(GAME_BOARD);
GAME_BOARD.move();
playerTurn.setText(GAME_BOARD.getCurrentPlayer().getName() +"'s turn");
}
}
}
});
So again, my question is, how do I make it so that before the second if statement executes, the activity waits, say 4 seconds?
you can use an Handler.postDeleayed. You have to provide a Runnable to execut and the delay period in milliseconds. The Runnable will be executed on the UI Thread
You can use Handle to post your task defined in runnable after some delay
use this
Inside Activity define
Handler hand = new Handler();
and define your task in runnable like this
Runnable run = new Runnable() {
#Override
public void run() {
**your Task here.......**
}
};
In on click event
btnStartShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
hand.postDelayed(run,3000); // For delay three seconds
}
});
also remove all pending messages by calling following sentence at appropriate place
hand.removeCallbacksAndMessages(null);
Use a CountDownTimer:
CountDownTimer timer = new CountDownTimer(4000, 1000) {
#Override
public void onFinish() {
*function containing the second statement*
}
#Override
public void onTick(long millisLeft) {
// not ticking
}
};
and in the onClick method in the click listener use:
timer.start();
Try the following,
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Runnable runnable = new Runnable() {
#Override
public void run() {
// whatever you would like to implement when or after clicking rollButton
}
};
rollButton.postDelayed(runnable, 5000); //Delay for 5 seconds to show the result
}
I want to make a view disappear (to be gone) when the user pushes a button.
I can make it inside the onCreate() method (main UI thread) by doing:
findViewById(R.id.llLoadingGallery).setVisibility(View.GONE);
However, I want to be able to do the same thing inside another thread (out of the main UI thread). I tried to put the above live in my thread and it didn't work.
Thank you in advance!
## EDIT ####
To make myself more clear, I want to do something like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.teste_aba_3);
botao_tab_musica.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
...
findViewById(R.id.llLoadingGallery).setVisibility(View.GONE);
}
});
}
However, that DOESN'T work! How can I fix this?
theres a neat method called runOnUiThread
runOnUiThread(new Runnable() {
#Override
public void run() {
findViewById(R.id.llLoadingGallery).setVisibility(View.GONE);
}
});
edit: with your code
botao_tab_musica.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
runOnUiThread(new Runnable() {
#Override
public void run() {
findViewById(R.id.llLoadingGallery).setVisibility(View.GONE);
}
});
}
});
I'd suggest either using View.post(Runnable), View.postDelayed(Runnable, long), a Handler, or an AsyncTask to do this for you.
There are some good examples on how to post to the UI thread in these scenarios:
http://developer.android.com/resources/articles/painless-threading.html
I think one possibility is to pass a reference to your activity to that other thread so that your thread can access the findViewById method.
try this
findViewById(R.id.llLoadingGallery).post(new Runnable()
{
#Override
public void run()
{
findViewById(R.id.llLoadingGallery).setVisibility(View.GONE);
}
});
or create AsyncTask