How to access the methods in this class in Java - java

I have the following click listener in android:
this.startButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
flag.set(false);
Runnable myRunnable = new Runnable() {
int updateInterval = 4000; //=4 second
ImageView currentImage = (ImageView)findViewById(R.id.picture);
public void x(){//dosomething}
#Override
public void run() {
if(!flag.get()) {
currentImage.postDelayed(this, updateInterval);
picture.setImageResource(images[current_image_index]);
caption.setText(captions[current_image_index]);
current_image_index++;
current_image_index = current_image_index % images.length;
}
}
};
myRunnable.run();
}
}
);
However I have another onClickListener that need to call the method x() from myRunnable. However I seem to not be able to do so. The context here is that when startButton is clicked, it causes images to be changed every 4 seconds, but I have another button called nextButton that when clicked changes the image and must reset the update interval, otherwise the next image will change inconsistently when the nextButton is pressed, thanks!

The program would not run as expected. You are overriding a method inside an
overriden method. Better still create a separate method to handle that event and
then call it up in your eventListener. Hope this helps

Related

Android handler shortening delay?

I'm creating a button to stop a light sensor after grabbing two equal light values for a duration of 2 seconds using the handler's delay function. It works fine at first but when I press the button again, the delay seems to get shorter and shorter, and eventually doesn't happen at all.
stateLx.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onResume();
stateLx.setEnabled(false);
doub2x.setText(Double.toString(0));
doub1x.setText(Double.toString(0));
//Stabilization Handlers
m_handler = new Handler();
m_handlerTask = new Runnable() {
public void run() {
doub1 = movingValue[0];
doub1x.setText(Double.toString(doub1));
m_handler.postDelayed(this, 1000);
}
};
m2_handler = new Handler();
m2_handlerTask = new Runnable() {
public void run() {
doub2 = movingValue[0];
doub2x.setText(Double.toString(doub2));
m2_handler.postDelayed(this, 2000);
if (doub1 != doub2) {
instructions.setText("unequal");
} else {
instructions.setText("equal");
getInitialLightValue();
reCalculateInitial();
beerLambert(volValues, lxValuesNew);
}
}
};
//Handlers for stabilizer
m_handler.postDelayed(m_handlerTask, 1000);
m2_handler.postDelayed(m2_handlerTask, 3000);
lame.setText(Double.toString(absorbValues[0]));
stateLx.setEnabled(true);
}
});
I've tried putting the handlers both in and out of the onclick function, as well as including the onResume() function at the beginning of the button press, but I'm having no luck. Is there something wrong with my code?
You keep recreating your Handlers and Runnables. This is part of the problem, you should check to see if you are already polling before starting again.
Also, this is a side note -- but it's odd to call lifecycle methods, like onResume() yourself, since it calls up to the super.

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

Google Glass Immersion - OnClick not working inside a separate thread

My problem is pretty simple. I am creating a card based on the result of a HTTP query performed inside a separate thread. The card also has an onclick method and is defined inside a runOnUiThread() located inside the separate thread. However, when the device is tapped, the onclick event isn't fired.
Here is my code:
private void login() {
Runnable r = new Runnable() {
#Override
public void run() {
// irrelevant code
runOnUiThread(new Runnable() {
#Override
public void run() {
setContentView(buildError(code));
}
}
}
Thread t = new Thread(r);
t.start();
}
private View buildError(String code) {
CardBuilder card = new CardBuilder(this, CardBuilder.Layout.ALERT);
card.setIcon(R.drawable.ic_warning_150);
if (code.equals("1"))
card.setText("Incorrect credientals");
else
card.setText("Unexpected error");
card.setFootnote("Tap to try again");
View cView = card.getView();
cView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Event", "Clicked"); // This is what isn't triggering
}
});
cView.setFocusable(true);
cView.setFocusableInTouchMode(true);
return cView;
}
Even though the snippet of code contains an error (can't be compiled, missing ; at the Runnable statement), you were on the right track.
The View simply needs to request the focus in order to be clickable right away. Otherwise you'll have to move the focus manually.
cView.setFocusable(true);
cView.setFocusableInTouchMode(true);
cView.requestFocus();
Reference

onClickListener not get called second time Android

I'm doing paypal payment for that i have to run thread in onCreate() method which initializes Button with Paypal image i'm calling one function from it which validates above fields then fires an API, if user oes wrong Toast is appeared that " ... this filed not be blanck." but after this when i correct that field and again click on Btn then it does nothing.
Thread libraryInitializationThread = new Thread() {
public void run() {
initLibrary();
// The library is initialised so let's create our CheckoutButton
// and update the UI.
if (PayPal.getInstance().isLibraryInitialized()) {
runOnUiThread(new Runnable() {
public void run() {
/**
* Create our CheckoutButton and update the UI.
*/
PayPal pp = PayPal.getInstance();
/**
* Get the CheckoutButton. There are five
* differentsizes. The text on the button can either
* be of type TEXT_PAY or TEXT_DONATE.
**/
launchChainedPaymentBtn = pp.getCheckoutButton(
BuyDeal.this, PayPal.BUTTON_194x37,
CheckoutButton.TEXT_PAY);
/**
* You'll need to have an OnClickListener for the
* CheckoutButton. For this application, MPL_Example
* implements OnClickListener and we have the
* onClick() method below.
**/
launchChainedPaymentBtn
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// dealResponse
getDealResponseLogic();
}
});
//
BottomBtnsLinearLayout
.addView(launchChainedPaymentBtn);
Log.v("Btn added ", "SuccessFully...");
Flag = true;
}
});
//
//
BottomBtnsLinearLayout.addView(launchChainedPaymentBtn);
Log.v("Btn added ", "SuccessFully...");
// }
// });
Log.i("Lib. initialized", "now...");
/** Calling Thread to add Btn to It! **/
AddPayPalBtn.start();
} else {
Log.i("Cannot Initialize Payment Btn",
"setAPyment Btn..failed due to Lib. initialization..");
}
}
};
libraryInitializationThread.start();
I called above thread in onCreate() method of my activity.
code for dealResponseLogic() only deals with validation.
initLibrary(); It get PayPal instance make use of internet and then set some fields of that instance.
I know that i can call to that thread from that btn Listener code btn i'm looking for another way.
Please... any help will be appreciated...
Try this..
Create and Start the thread inside the onClick() method of the Button..
Eg:
Button b = (Button)findViewById(R.id.button_Start);
b.closeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Thread t = new Thread(new Runnable(){
public void run(){
// DO YOUR LONG TIME TAKING WORK HERE.......
}
});
t.start();
}
});
I think it's pretty easy. While using paypal you have to create button using paypal, so there is one method provided by paypal to update that button i.e. updateButton() you just want to call that method.
So, your button works fine everytime you click .

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