Send function to new thread - java

On Android when I am mapping an address on a Mapview I have to wait for that action to return and then my user is given control back so I was wondering how can I send that function of to another thread?
mapLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mapCurrentAddress(); //Send this function to new thread
}
});
How can this be done? And how will the new thread respond when it's done?

Android provides the AsyncTask class to do that. Read http://developer.android.com/reference/android/os/AsyncTask.html

You can use an AsyncTask to do this work in the background. Check this example

Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
p_dialog = ProgressDialog.show((activity_name).this, "", "Loading Image...");
new Thread(new Runnable() {
public void run() {
function();
}
}).start();
}

Related

How to detect taps on a button whilst a delay caused by postDelayed Handler

I want to solve a problem that I have been trying to do so the last couple of days but I dont have that much experience and I couldnt find the solution enywhere else.
Anyway,
In my app I have a button in wich I have implemented the onClickClistener in order to respond to touch and inside that I have added a Handler which adds a delay and after that some code is being executed. My problem is that i want to detect any tap of the button whilst the delay is happening and the postDelyed function doesn't allow me to do so. How can I actually do that?
I've posted my code that is related on that.
Thanks in advance!
P.S(I dont mind not using this postDelayed thing.)
Button button = findViewById(R.id.myButtonId);
button.setOnClickListener(new View.OnClickListener){
#Override
public void onClick(View v) {
.......
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do some thing after the delay
}
}, randomDelay);
//Do other things
}
});
boolean previousTapDetected;
...
button.setOnClickListener(new View.OnClickListener){
#Override
public void onClick(View v) {
.......
if(previousTapDetected) {
//We got a tap during the delay
}
Handler handler = new Handler();
previousTapDetected = true;
handler.postDelayed(new Runnable() {
#Override
public void run() {
previousTapDetected = false;
//Do some thing after the delay
}
}, randomDelay);
//Do other things
}
});

Display a Shuffle of button text and backgrounds

I have a button in xml. On button press I wish to rapidly change the background and Text on that button.
I normally would use a code like this for the final result:
String rndm[] = {"A","B","C","D"};
{rnd = rndm[(int) (Math.random() * rndm.length)];}
{Button btn = (Button) findViewById(R.id.button1);
btn.setText(String.valueOf(rnd));
btn.setTextColor(Color.parseColor("#000000"));}
Before that is called though I would like perhaps a second or two of a "shuffling" effect.
I have tried using java.util.timer like this:
#Override
public void onClick(View v) {
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
String rndm[] = {"A","B","C","D"};
{rnd = rndm[(int) (Math.random() * rndm.length)];}
{Button btn = (Button) findViewById(R.id.button1);
btn.setText(String.valueOf(rnd));
btn.setTextColor(Color.parseColor("#000000"));}
}}}, 100 );
Then making a few of these with different backgrounds to fire one after the other. I just can't seem to get the hang of it.
I may need a whole new method to do what I want to do, but I am not sure what the best wat to accomplish what I need is.
You should use Handler and make sure that the code that you want to run is in the runnable method :-)
Try something like this from your Activity
Handler handler = new Handler();
....
#Override
public void onClick(View v) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
// set your button color here, no need to use runOnUiThread()
// as this run() method is executed on Main thread
}
}, 100);
}

How to start and stop 2 or more progressbar?

Hello stackoverflow citizen!
I want start and stop 2 progressBars on 1 activity.
I think oll progressBars must start in new thread and join with others.
For 1 progressBar i am write this code.
startBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
handler.post(runnable);
}
});
stopBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
handler.removeCallbacks(runnable);
}
});
}
int prolength=0;
Runnable runnable=new Runnable() {
#Override
public void run() {
prolength = inProgressBar.getProgress() + 1;
inProgressBar.setProgress(prolength);
timeTextView.setText(String.valueOf(prolength));
if (prolength < 100) {
handler.postDelayed(runnable, 1000);
}
else {
inProgressBar.setProgress(0);
timeTextView.setText(String.valueOf(0));
handler.post(runnable);
}
}
};
Thank you advance for help!
I suggest you to use sendMessage Api instead of post Api.
You can pass some information using Message object in your case (contentProgressBar1 or 2 or3 view) and refactor you implementation to this design..
Make sure to cleanup handler in activity life cycle else you will introduce memory leak and unwanted bugs.

Why my thread doesn't work?

I make an app that can count down. But it doesn't work and it just shows 100 in textview.
Here is my code:
public class MainActivity extends Activity {
private TextView textView;
private Button start;
Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView1);
start = (Button) findViewById(R.id.button1);
start.setOnClickListener(onStart);
thread = new Thread( //it's my thread
new Runnable() {
#Override
public void run() {
for (int i = 99; i > 0; i--) {
Log.i("Where am I?", "I'm in for loop .");
try {
textView.setText(String.valueOf(i));
} catch (Exception e) {
Log.e("Exception.getCause", String.valueOf(e.getCause()), e.getCause());
}
Log.i("INDEX", String.valueOf(i));
}
}
});
}
private View.OnClickListener onStart = new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Where am I?", "I in View.OnClickListener .");
thread.start();
}
};
}
Update your TextView using runOnUiThread as below...
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(String.valueOf(i));
}
});
Update:
For delay in count you can use Handler as below. Create an object of Handler and create a Thread.
private Handler mTimerHandler = new Handler();
private Runnable mTimerExecutor = new Runnable() {
#Override
public void run() {
//add your code here which should execute after the specified delay
}
};
Then pass that thread inside postDelayed() method Handler with the time which should be delayed to execute the thread as below...
mTimerHandler.postDelayed(mTimerExecutor, 1000);
And if you want to cancel the thread to execute, use removeCallbacks() method as below...
mTimerHandler.removeCallbacks(mTimerExecutor);
Catching for Exception inside the Thread is kind of misleading. As matter of fact, textView.setText(String.valueOf(i)); executed in a Thread different from the UI Thread should make you app crashes for CalledFromTheWrongThreadException. You should use an Handler to execute that line in the UI Thread's context
textView.setText(String.valueOf(i));
has to be used in UI thread only.
textView.setText(String.valueOf(i));
This is UI action, You can handle UI action only in a main thread.
You can send a message to the handle of activity.
You cannot use Thread class to interact with UI you should use AsyncTask or Handler classes.
Sample tutorial: http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html
Use AsyncTask instead.
Checkout:
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

Android: Updating UI with a Button?

So I have some simple code but it seems to not be working.. any suggestions?
I just want an image to show after a button is pressed then become invisible after 2 seconds.
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
firstImage.setVisibility(ImageView.VISIBLE);
// delay of some sort
firstImage.setVisibility(ImageView.INVISIBLE);
}
}
The image never shows, it always stays invisible, should I be implementing this in another way? I've tried handlers.. but it didn't work, unless I did it wrong.
Never make your UI thread sleep!
Do this:
final Handler handler = new Handler();
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
firstImage.setVisibility(ImageView.VISIBLE);
handler.postDelayed(new Runnable(){
public void run(){
firstImage.setVisibility(ImageView.INVISIBLE);
}
}, DELAY);
}
}
Where you would set DELAY as 2000 (ms).
Well, you will need to add a delay between the two lines. Use a thread or a timer to do this.
Start a thread on click of a button. In the run method, change the ImageView's visibility to VISIBLE, then put the thread to sleep for n secs, and then change then make it invisible.
To call the imageView's setvisibility method, you will need a hanlder here.
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
image.setVisibiliy(VISIBLE);
Thread.sleep(200);
image.setVisibility(INVISIBLE);
}
});
I know this question has already been answered, but I thought I would add an answer for people who like me, stumbled across this looking for a similar result where the delay was caused by a process rather than a "sleep"
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
firstImage.setVisibility(ImageView.VISIBLE);
// Run the operation on a new thread
new Thread(new Runnable(){
public void run(){
myMethod();
returnVisibility();
}
}).start();
}
}
private void myMethod() {
// Perform the operation you wish to do before restoring visibility
}
private void returnVisibility() {
// Restore visibility to the object being run on the main UI thread.
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
firstImage.setVisibility(ImageView.INVISIBLE);
}
});
}

Categories