button.setPressed(true) suddenly not working - java

I have been using an emulator with the following code to press a particular button
redBut.performClick();
redBut.setPressed(true);
redBut.invalidate();
redBut.setPressed(false);
redBut.invalidate();
Using Log statements, I know for sure this piece of code is being called, so it is not that the code is being skipped over.
On my emulator, the button appeared to be pressed as if a user pressed it. Now on a real android device, the process is running but the button is unchanged. What is the problem?

Write your code as follows-
redBut.performClick();
redBut.setPressed(true);
redBut.invalidate();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
redBut.setPressed(false);
redBut.invalidate();
}
}, 500);

Related

startActivity() silently fails if called from the background after you press the home button

If you press the home button on an Android device and then you call startActivity() it will silently fail and there doesn't seem to be a way to check when it fails. For example:
#Override
protected void onStop() {
super.onStop();
Handler hndlr = new Handler();
Runnable t = new Runnable() {
public void run() {
startActivity(new Intent(getApplicationContext(), SomeOtherActivity.class)); //this silently fails, no error, nothing
}
};
hndlr.postDelayed(t, 1000);
}
Is there a way to check if it fails to start the activity? I don't intend to start any activity in the background, I just need to know when it fails. Please note that this only happens when you press the home button, I'm actually not sure if this is just an Android bug (I'm testing on Android 11). Thanks!
You could just check that your app is in the foreground like this:
if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)){
startActivity(new Intent(getApplicationContext(), SomeOtherActivity.class));
}

How to allow a non-activity to display dialog on activity?

This question is very similar to questions that have been asked in the past but please bear with me as it is still a unique question. Basically, I have a class that gets application permissions, and if the user does not have internet running, then when the auto login screen comes, it is stuck in loading. So what I want to do is show a dialog message, and the user will click ok to close the app. For dialogs, I need the context, and I must run on the main thread. I have posted an image of the code because I want to show you that runOnUIThread is red. Here is the error I get form Android Studio
Cannot resolve method runOnUIThread.
Here is what I had
Problem: For some reason, runOnUIThread is not usable. Does anyone have a counter proposal, or a reason as to why I am having this problem?
Here is the code:
public void alert() {
new Thread()
{
public void run()
{
application.runOnUiThread(new Runnable() // application is the context of my current activity.
{
public void run() //I display my alert Dialog here.
{
AlertDialog build= new AlertDialog.Builder(application.getApplicationContext())
.setTitle("Error")
.setMessage("Sorry there seems to be a problem with the service. Please check to make sure you have a stable internet connection. ")
.setPositiveButton("Ok, I understand.", (dialog, which) -> System.exit(0))
.show();
build.setCancelable(false);
Button positive= build.getButton(DialogInterface.BUTTON_POSITIVE);
positive.setTextColor(application.getResources().getColor(R.color.buttonPrimaryColor));
positive.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
}
});
}
}.start();
Here is how I have made it work with a Toast in the past.
public void shortToast(String msg) {
Observable.just(msg)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(message -> {
Toast.makeText(application, message, Toast.LENGTH_SHORT).show();
});
}
// In the main method
shortToast("Sorry an error occured");
For some reason, runOnUIThread is not usable
The method that you are trying to invoke is runOnUiThread(). That is a method on Activity. Whatever application is, it is not an Activity.
Does anyone have a counter proposal
Move this code into an Activity. Generally, pop-ups (dialogs, snackbars, etc.) should be displayed by an Activity. And only an Activity can show a Dialog, such as an AlertDialog.
Try to use an activity to run on UI, not application

Horizontal Scroll View working unexpectedly

I am trying to create a calculator. I am working in the latest Android Studio. Like in calculators, all new tokes(numbers, operators) should be shown in the right and if the field is larger than the display, it should scroll to the latest token. I have already browsed and found a way to do the same.
The code for the same is:
private void scrollRight() {
horizontalScrollView = (HorizontalScrollView) findViewById(R.id.horizontalScrollView);
ViewTreeObserver viewTreeObserver = horizontalScrollView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
horizontalScrollView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
horizontalScrollView.scrollTo(entry.getWidth(), 0);
}
});
}
scrollRight is called by a onClick event which checks if a token is entered and calls this.
Everything is working perfectly, i.e. on every new token the scroll bar is scrolling to the end. But if I try to scroll to the beginning manually, it no longer works. After this every time a new token is pressed, the scroll bar first moves to the end and then back to the beginning.
The only option that remains is to restart the program. I tried debugging the OnGlobalLayout function but the debugger loses all frames while stepping out from the function, so it is difficult to know what exactly is making the scroll bar go to the beginning.
GIF to show the problem:
Please Help!
Try
horizontalScrollView.post(new Runnable() {
#Override
public void run() {
horizontalScrollView.fullScroll(View.FOCUS_RIGHT);
}
});
And call findViewById only once in onCreate.

Prevent Ad from triggering multiple times

When I run this code on a real device the ad-banner pops up endless times. How should i modifiy this code to run it just once?
This code is from a game. Every time the player gets hit by something he loses 1 shield.
private void showBanner() {
adView.setVisibility(View.VISIBLE);
adView.loadAd(new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build());
}
if (player.getShieldStrength() == 0){
runOnUiThread(new Runnable() {
#Override
public void run() {
showBanner();
}
});
}
This my logcat:
Aborting last ad request since another ad request is already in progress.
The current request object will still be cached for future refreshes.
...
This runnable is triggered by the run method. showBanner is part of update-method
#Override
public void run() {
while (playing) {
update();
draw();
control(); }}
You are confused.
A banner ad is not like an interstitial. It does not pop-up.
When you request a banner ad you are requesting ads to fill that AdView until you tell it to stop or you hide it. It will show new ads on the refresh cycle you have configured in the Admob dashboard. It will not show a single ad.
If you really only want a banner ad to be shown until the next game, then call adView.setVisible(VIEW.INVISIBLE) or adView.setVisible(VIEW.GONE)
And please don't repost existing questions Ad pops up multiple times

Display a sting on android screen on a timer event

I am writing n android app as part of my thesis and need to display/update/append data onto an android screen during a timer event - as follows:
(please excuse possible incorrect terminology and feel free to correct it)
I have a few classes in the app, however am trying to interact between "BlueActivity" and "BuzzActivity".
"BlueActivity" controls blue tooth. It turns on/off blue tooth,makes a connection and controls the socket.
"BuzzActivity" has a button "BUZZME": onClick, BuzzActivity passes (behind the sceens) into "BlueActivity" which sends a packet to the paired device (devDuino, who then radios out to a wearable device. the wearable device radios a reply of data readings back to devDuino). The paired device then replies this data back to "BlueActivity" which is read in through the socket listening on a timer. The data is in the format of a string and is called "retstr". The timer is started in "BlueActivity's" OnCreate() method.
I need to get "retstr" from "BlueActivity" into "BuzzActivity" and updating on the screen.
I have tried .setText and failed in the sense of App crashing. From research i hear about needing a handler to "dynamically" update the view?
Can some one please clarify this.
Code segments as follows:
BlueActivity:
.........//stuff here
//final String TAG = "On create";
new Timer().schedule(new TimerTask() {
#Override
public void run() {
//Log.i(TAG, "In timer running");
String retstr;
retstr = mConnectThread.listen(); //Method to get my data from bluetooth packet
//String text = String.valueOf(retstr); //failed attempts
//BuzzActivity.DivingData.setText(text);
Log.i(TAG, "retstr"); //Works like a charm to print out to log cat
}
}, 1000, 1000);
mConnectThread = new ConnectThread(mmDevice);
mConnectThread.start();
}
BuzzActivity
.......//blueConnecter is called from the .xmlfile controling the buzz button "on click method"
public void blueConnecter(View view){
DivingData = (TextView) findViewById(R.id.DivingDataTextField);
BlueActivity.visible(view);
}
Thanks for any help in advance.
Emma.
Is there a stack trace in the logcat output? You'll probably find that you are trying to update the UI thread from another thread. If that is the case, you need to update that view with runOnUiThread(). Here's an example:
runOnUiThread(new Runnable() {
public void run() {
DivingData.setText(newText);
}
});

Categories

Resources