Android Studio - Condition is always true? - android

This would be the first time I post a question since I couldn't find the answer to this. Something really weird is happening with my if/else statements. My code was working perfectly for the past week, but recently it kept on telling me that a statement is always true?
My code is the following:
int checking = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checking != 1) {
speaker.setChecked(true);
} else if (checking == 1) {
speaker.setChecked(false);
}
}
This says checking == 1 is always true which makes sense, but if I switch it around to:
if (checking == 1) {
speaker.setChecked(true);
} else if (checking != 1) {
speaker.setChecked(false);
}
This says that checking != 1 is always true as well. Can someone help?

It's just a logic of editor. In first if statement, you check checking == 1 and the second if statement, you negative the statement. The editor will understand the second if statement alway true
I think you should replace else if to else. Sorry my bad English.

The reason why you are seeing this warning is:
You have set int checking = 1 and you are either checking:
if (checking != 1) which is always true
Or checking == 1 which is also always true
Due to this other else if condition will not be executed at all.
The warning will be only removed if you try to change value of checking either at runtime or using some conditions at compile time.
If your intention is just to set the speaker.setChecked() you can do following:
speaker.setChecked(checking == 1)
Note: This will not remove the warning

Try this
int checking = 1;
boolean isChecked = false;
isChecked = ((checking == 1) ? true : false)
speaker.setChecked(isChecked)

Related

Android AccessibilityService performAction() method not working

I am developing an accessibility service for Android. The service calls an app, and that app has a RecyclerView. Then I want to click on an element of the RecyclerView with performAction(AccessibilityNodeInfo.ACTION_CLICK) but it is not working. I know there are a few similar questions but none of them works for me. Also I checked the official documentation for the class of the performAction method https://developer.android.com/reference/android/view/accessibility/AccessibilityNodeInfo
This is my code:
#Override
public void onAccessibilityEvent(Accessibility event){
AccessibilityNodeInfo source = event.getSource();
if(source != null){
List<AccessibilityNodeInfo> list = source.findAccessibilityNOdeInfosByText("mystring");
list.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
}
}
This is my configuration xml file:
<accessibility-srvice xmlns...
android:accessibilityFeedbackType = "feedbackGeneric"
android:AccessibilityFlags = "flagDefault"
android:canPerformGestures = "true"
android:canRetrieveWIndowCOntent = "true"
I think I misunderstood something, but i don't know what can be. Any help is appreciated.
The simple answer is that while finding the node by text is fine, that particular node was not the node with the desired onClick event. The solution is to call
list.get(0).getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK)
The clarifying discussion is below
I think .performAction(AccessibilityNodeInfo.ACTION_CLICK) is right, but there might be some other concerns. Sorry for posting as an answer but a comment is too small.
Are you sure the onAccessibilityEvent is being called? I don't think that is the right event, but I can't be sure. Maybe put a log in there to ensure it's calling the event when you expect it to be called.
Also, looking at the source might restrict your search, maybe instead of event.getSource() try using rootInActiveWindow (I use Kotlin so it might have a method, see https://developer.android.com/reference/android/accessibilityservice/AccessibilityService#getRootInActiveWindow(int))
EDIT: 28 March 2022
I have run this code on my own accessibility service and it does click the button. But it's very prone to overflow.
var ranOnce = false // prevent overflow
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
if (event == null) return
if (event.eventType == TYPE_WINDOW_STATE_CHANGED) return
if (event.source != null && !ranOnce) {
val nodeList = rootInActiveWindow.findAccessibilityNodeInfosByText("Menu")
//event.source.findAccessibilityNodeInfosByText("Menu") // <-- always nothing in list
Log.d("onAccessibilityEvent", "List of nodes: $nodeList")
if (nodeList.size > 0) {
android.util.Log.d("onAccessibilityEvent", "Node info: ${nodeList[0]}")
ranOnce = true
nodeList[0].performAction(AccessibilityNodeInfo.ACTION_CLICK) //<-- caused an infinite loop!
} else {
Log.d("onAccessibilityEvent", "No nodes found")
}
} else {
Log.d("onAccessibilityEvent", "event.source is null!")
}
}

"If-else" statement going down the wrong section in step debug

Hopefully a simple answer but I'm a little baffled. I'm expecting the code to go down the first if section below, but it always goes to the else.
When I get to line on a breakpoint >> if (url2!=null && !url2.isEmpty())
In the expressions window:
url2 IS "???/wp-content/uploads/2011/01/toonieJune10_091-640x334.jpg"
url2!=null IS true
!url2.isEmpty() IS true
However when debugging it always seems to hit the else, even though both conditions are true. I'm suspecting something is out of sync with my built code somehow as the step through debugging seems to give me inconsistencies.
I've tried cleaning the code and making some changes in the class and recompiling etc.
Help is much appreciated! Thanks!
public String getImageBannerUrl()
{
if (getPhotoFile1()!=null) return getPhotoFile1().getUrl();
String url2 = getRemoteImageUrl();
if (url2!=null && !url2.isEmpty())
{
return url2;
}
else
{
//Otherwise get default image based on category
return getImageCategoryUrl();
}
}
Try somthing like..
public String getImageBannerUrl()
{
if ((!getPhotoFile1().isEmpty()) && (!getPhotoFile1().matches(" "))) return getPhotoFile1().getUrl();
String url2 = getRemoteImageUrl();
if ((!url2.isEmpty()) && (!url2.matches(" ")))
{
return url2;
}
else
{
//Otherwise get default image based on category
return getImageCategoryUrl();
}
}
Note : here getPhotoFile1() must be returning String value..

Code not reaching if statement

I have the following code:
public void click(View v)
{
Button b = (Button) v;
TextView viewEditText = (TextView) findViewById(R.id.functionTextView);
String editText = viewEditText.getText().toString();
if (b.getId() == R.id.backspace)
{
if (viewEditText.length() > 0)
{
if (editText.substring(editText.length() - 1, editText.length()) == ".")
{
periodTrue = false;
}
viewEditText.setText(viewEditText.getText().toString().substring(0, viewEditText.length() - 1));
}
}
}
In this code I check to see if the character being backspaced is a period, if the previous condition is true. It sets the variable periodTrue to false. This tells the app that another period can be added.
Everything works with the backspace key as normal, except it never makes it inside the if statement where the variable is set. It throws no errors and I have checked with
viewEditText.append(editText.subString(editText.length()-1, editText.length()); to verify that the returned character is ".".
I don't know why it's not working, and it throws no errors or warnings either, on compile or run time. So I've come to you to see if a different perspective can show what I'm obviously doing wrong.
if (editText.substring(editText.length() - 1, editText.length()) == ".")
This won't work as you're comparing the references of the two Strings, which will be different. (More in-depth explanation in this question: How do I compare strings in Java?)
Use the following instead:
if (".".equals(editText.substring(editText.length() - 1, editText.length())))

How to test for am or pm?

I am trying to test for am or pm in a if else statement..
if(am){
//Do something
else{
//Do something else
Ive tried
int am = cld.get(Calendar.AM_PM);
but the if else
wont take it as a parameter to test. Maybe because its not boolean.
How would i go about testing this?
You're correct that the if-else won't accept it because it is not boolean. Calendar.AM_PM only ever holds the value 0 or 1. A language like C would accept 0 or 1 as boolean; Java won't.
You want to do something more like this:
int am = cld.get(Calendar.AM_PM);
if (am == 0) {
// Do whatever for the AM
} else {
// Do whatever because it must be PM
}
Surely your if clause cannot accept integer as it is. You need something (comparison perhaps) to get boolean out of it.
if(am > 0)
{
//its PM
else { //its AM }
Calendar.AM_PM is an int. To evaluate it in an if statement, cast it to a boolean:
if((bool)am) {
//It's AM
} else {
//It's PM
}

Android Null Checker

I have a program that relates to a database. I start out my program by inserting a row using the following command.
long id = db.insertMajor(null, null, null, null);
it works perfect. I than alter the information but lets ignore that since for the time being I commented out all those lines. Now I want to check and see if it is null which is should be. If it is not null than I would like to check a checkbox. if it is null than I want to leave the box unchecked. So far I have this line to test.
String change = db.getMajorTitle(value).getString(1);
if (change.equals(null)) {
filled = false;
}
the filled boolean will check the box or not. If the database field is filled or not I always get a checkmark. Whats wrong?
UPDATE:
Since no one has figure it out I will post most of my code to try and help figure it out. I have also reset my emulator to ensure there is not problems with corrupted data.
chk1.setChecked(checker(1));
chk2.setChecked(checker(2));
chk3.setChecked(checker(3));
chk4.setChecked(checker(4));
}
boolean checker(int value){
DBAdapter db = new DBAdapter(this);
boolean filled = false;
db.open();
for (int i = 1; i <= 4; i++) {
String change = db.getMajorTitle(value).getString(1);
if (change == null) {
filled = false;
}else{
filled = true;
}
}
db.close();
return filled;
}
If someone copies this and it works can you please tell me what might be wrong with my emulator or eclipse or whatever. Thanks everyone for there input.
FINISHED:
I noticed that at another part in my program I changed null to "". I would like to thank everyone for being right and showing me different ways to code it.
You really don't need if statements for this.
filled = (change != null);
if (change.equals(null)) {
If change instance is not null, the above condition always returns false. Read Object equality constraints for more info.
If you want to check against null use
if( change == null) {
// change is null, update filled field
} else {
// change is not null, update filled field
}
If the database field is filled or not
I always get a checkmark. Whats wrong?
I guess that you would have initialized the filled field as true and never set it as false since your if condition always returns false or throws NullPointerException.
User ExceptionHandling mechanism. then you will succeed. Like
try {
if(change!=null)
{
//do ur work,if not null
}
else
{
// do some thing
}
}catch(NullPointerException e)
{
//do ur work,if null.
}

Categories

Resources