Execute Button in seconds Android Studio - android-studio

Is there a way for a button to be executed in seconds without touching it.
The following code execute the button in one second but after i touch the button. My question is can this be achieved without touching the button?
View.OnClickListener mButtonStartListener = new View.OnClickListener() {
public void onClick(View v) {
try {
mHandler.removeCallbacks(hMyTimeTask);
// Parameters
// r The Runnable that will be executed.
// delayMillis The delay (in milliseconds) until the Runnable will be executed.
mHandler.postDelayed(hMyTimeTask, 1000); // delay 1 second
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private Runnable hMyTimeTask = new Runnable() {
public void run() {
nCounter++;
hTextView.setText("Hallo from thread counter: " + nCounter);
}
};
/**
*
*/
View.OnClickListener mButtonStopListener = new View.OnClickListener() {
public void onClick(View v) {
mHandler.removeCallbacks(hMyTimeTask);
}
};

You may simulate click event by following code
View.performClick();
originally posted at https://stackoverflow.com/a/4877526/5329101.

Try .onLoadCompleteListener instead of .onClickListener

Related

Binding Properties and using them during lengthy operations

In my JavaFX Application I want to disable a couple of Buttons during a refresh of the data from a database.
I am using the disableProperty of the Buttons I want to disable.
Here is the basic JavaFX Application, modefied to illustrate my point:
public class BindLengthy extends Application {
BooleanProperty disable = new SimpleBooleanProperty(false);
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.disableProperty().bind(disable);
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
disable.set(true);
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(BindLengthy.class.getName()).log(Level.SEVERE, null, ex);
}
btn.setText("Done");
}
});
//Do all the other stuff that needs to be done to launch the application
//Like adding btn to the scene and so on...
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
When executed, on the click the Button stays in the "fired" mode, waits for 5 Seconds and then changes text and disables. While I want the text to change later, I want to disableProperty Change to take effect immediately!
I tried putting the lengthy operation, represented by Thread.sleep(5000) into a task and start it on a new Thread(task), but then obviously the text is changes before the Thread awakens.
I can't put the btn.setText("Done")into the Threadas it wouldn't be executed on the JavaFX-Thread(which it needs to). So I tried joining the Thread, yet that gives the same result as not putting it into an extra Thread as well.
How can I force the diableProperty to register the new value before executing my long operation?
Use a Task and use its onSucceeded handler to update the UI:
public class BindLengthy extends Application {
BooleanProperty disable = new SimpleBooleanProperty(false);
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.disableProperty().bind(disable);
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
disable.set(true);
Task<String> task = new Task<String>() {
#Override
public String call() throws Exception {
Thread.sleep(5000);
return "Done" ;
}
});
task.setOnFailed(e ->
Logger.getLogger(BindLengthy.class.getName())
.log(Level.SEVERE, null, task.getException()));
task.setOnSucceeded(e -> {
btn.setText(task.getValue());
disable.set(false);
});
Thread t = new Thread(task);
t.setDaemon(true);
t.start();
}
});
//Do all the other stuff that needs to be done to launch the application
//Like adding btn to the scene and so on...
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}

Unable to hide Action Bar before starting another activity

I'm trying to first create an activity, then after 2 seconds, I want to hide the action bar and then after another 2 secs, I want to start another activity but this code - getActionBar().hide() isn't working. Here is my code -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
//final ActionBar actionbar = getActionBar();
Thread timer1 = new Thread() {
public void run(){
try{
sleep(2000);
} catch(InterruptedException e){
e.printStackTrace();
} finally{
getActionBar().hide();
}
}
};
timer1.start();
Thread timer2 = new Thread() {
public void run(){
try{
sleep(2000);
} catch(InterruptedException e){
e.printStackTrace();
} finally{
Intent intent = new Intent("app.lost_and_found_0.STARTINGPOINT");
startActivity(intent);
}
}
};
timer2.start();
}
Is there something wrong I'm doing wrong?
My application theme is set to Theme.Holo.Light in manifest file.
Use getSupportActionBar() instead of getActionBar(). As on the class, you need to extend ActionBarActivity.

Replace a TableView with a ProgressIndicator within VBox JavaFX

I have a TableView associated with some data, and once i hit a run button i perform some processing on that data. Each row of data is handled in a seperate thread, and while those threads are running i want a ProgressInducator to replace the table within its vbox.
In the attached code:
If I stop where is says "WORKS IF STOP HERE" - table is replaced with pi.
If I continue waiting for the threads to join - no replacing.
What am I missing?
runButton.setOnAction(
new EventHandler<ActionEvent>() {
#Override
public void handle(final ActionEvent e) {
List<Thread> threadList = new ArrayList<Thread>();
int threadCounter = 0;
final ProgressIndicator pi = new ProgressIndicator(threadCounter);
vbox.getChildren().clear();
vbox.getChildren().addAll(pi);
for (ProductInTable product : data) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try
{
product.calculate();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
});
threadList.add(thread);
thread.start();
}
int x = threadList.size();
/** WORKS IF STOP HERE **/
// wait for all threads to end
for (Thread t : threadList) {
try {
t.join();
threadCounter++;
pi.setProgress(threadCounter / x);
} catch (InterruptedException interE) {
interE.printStackTrace();
}
}
/** DOESNT WORKS IF STOP HERE **/
Thread.join() blocks execution until the thread is completed. Since you are calling this on the FX Application Thread, you block that thread until all your worker threads finish. This means the UI is unable to update until those threads are complete.
A better approach is probably to represent each computation with a task, and update a counter of complete tasks back on the FX Application Thread using setOnSucceeded. Something like:
runButton.setOnAction(
new EventHandler<ActionEvent>() {
#Override
public void handle(final ActionEvent e) {
final ProgressIndicator pi = new ProgressIndicator(threadCounter);
vbox.getChildren().clear();
vbox.getChildren().addAll(pi);
final int numTasks = data.size();
// only access from FX Application thread:
final IntegerProperty completedTaskCount = new SimpleIntegerProperty(0);
pi.progressProperty().bind(completedTaskCount.divide(1.0*numTasks));
completedTaskCount.addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> obs, Number oldValue, Number newValue) {
if (newValue.intValue() >= numTasks) {
// hide progress indicator and show table..
}
}
});
for (final ProductInTable product : data) {
Task<Void> task = new Task<Void>() {
#Override
public Void call() {
try
{
product.calculate();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null ;
}
});
task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
completedTaskCount.set(completedTaskCount.get()+1);
}
});
new Thread(task).start();
}
}
});
If you potentially have a large number of items here, you should use some kind of ExecutorService instead to avoid creating too many threads:
ExecutorService exec = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors()); // for example...
and then replace
new Thread(task).start();
with
exec.submit(task);

onClick and setImagResource [Android] API 10

I'm trying to understand why it's occuring me the following problem.
I have an ImageView and i set an image to it, then i setup a onClickListener to it, so when you click to image it change the image (to a new image) by image01.setImageResource(R.drawable.newImage). After that i call a method where i check a condition, if it is true i change the image again to the default one.
But I can't see the change because it change immediately. I also insert a sleep to make it slower.
(By default in the xml code i setted the image to oldImage)
Ok... maybe it's not clear.. so let's see the CODE:
private void myMethod(){
ImageView image01 = (ImageView) findViewById(R.id.image01);
image01.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//When you click on image it change!
image01.setImageResource(R.drawable.newImage);
checkImg(image01);
}
});
}
private void checkGame(ImageView img){
try{
Thread.sleep(1000);
if(condition)
img.setImageResource(R.drawable.oldImage);
}catch (Exception e) {
e.printStackTrace();
}
}
I saw immediately the oldImage. What's the problem?
Is it possible that the view change are not applied in myMethod() until all methods inside it will terminate?
Thanks in advance
Using Thread.sleep() method, you are actually making wait to main UI thread. The main UI thread's methods are not synchronized. Be aware of that.
Please go through the developers.android site for using of threads painlessly... before seeing the your useful code.
private void myMethod(){
ImageView image01 = (ImageView) findViewById(R.id.image01);
image01.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//When you click on image it change!
image01.setImageResource(R.drawable.newImage);
checkGame(image01);
}
});
}
private void checkGame(ImageView img){
try{
// Thread.sleep(1000);
if(condition)
image01.postDelayed(new Runnable() {
#Override
public void run() {
image01.setImageResource(R.drawable.oldImage);
}
}, 2000);
}catch (Exception e) {
e.printStackTrace();
}
}

How to enable a button after 5 seconds

everyone! I need to make a Button disabled for 5 seconds, and the caption of the button must be "Skip" plus the time the button will stay disabled.
I have made a class CTimer that extends Thread, and defined the run method with run(Button). The run method receives the Button which Caption will be modified and is as follows:
public void run(Button skip){
for ( int i=5; i<0; i--)
{
skip.setText("Skip (" + i + ")");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
skip.setEnabled(true);
}
The problem is that the code does not work, any thouhts, anyone?
I have tried the following code & it works fine for me:
public class Main_TestProject extends Activity
{
private Button b;
private int index = 5;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button) findViewById(R.id.my_button);
b.setEnabled(false);
hHandler.sendEmptyMessage(0);
}
private Handler hHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if(index > 0)
{
try
{
b.setText("Skip (" + String.valueOf(index) + ")");
index--;
Thread.sleep(1000);
hHandler.sendEmptyMessage(0);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
b.setEnabled(true);
}
}
};
}

Resources