I have a this code somewhere in my Android project:
public boolean isLoadInProgress(boolean privateLoad, boolean publicLoad) {
if (privateLoad && privateLoadInProgress) {
return true;
}
if (publicLoad && publicLoadInProgress) {
return true;
}
return false;
}
I get a lint warning at the second if statement: 'if' statement could be simplified. That's obviously because I could write as well:
return publicLoad && publicLoadInProgress;
However, I would like to keep it this way for readability. I know that there is some inline comment annotation for switching off the lint warning at that place, but I can't find it in the Android Lint documentation. Can you tell me what this annotation/comment was?
The simple code comment for disabling the warning is:
//noinspection SimplifiableIfStatement
This on top of the if-statement should switch off the warning only at that place.
In the example, this would be:
public boolean isLoadInProgress(boolean privateLoad, boolean publicLoad) {
if (privateLoad && privateLoadInProgress) {
return true;
}
//noinspection SimplifiableIfStatement
if (publicLoad && publicLoadInProgress) {
return true;
}
return false;
}
You can add #SuppressWarnings("SimplifiableIfStatement") above your method.
It's not an Android Lint error. You can use:
#SuppressWarnings("RedundantIfStatement")
public static boolean isLoadInProgress(boolean privateLoad, boolean publicLoad) {
if (privateLoad && privateLoadInProgress) {
return true;
}
if (publicLoad && publicLoadInProgress) {
return true;
}
return false;
}
At the highlighted if, you can use the alt-enter shortcut to open the context menu and select Simplify > Suppress for method (keeping the scope as small as possible).
Sure:
In .java files, you can suppress issues with the #SuppressLint
annotations. You supply the lint issue id as the argument to the
annotations.
Example:
#SuppressLint("AndroidWarningId")
public boolean isLoadInProgress(boolean privateLoad, boolean publicLoad) {
if (privateLoad && privateLoadInProgress) {
return true;
}
if (publicLoad && publicLoadInProgress) {
return true;
}
return false;
}
Just replace the AndroidWarningId with the corresponding warning, you can find those in here
Although I would suggest simplifying it this way:
public boolean isLoadInProgress(boolean privateLoad, boolean publicLoad) {
if (privateLoad && privateLoadInProgress
|| publicLoad && publicLoadInProgress) {
return true;
}
return false;
}
Its still readable and uses less space (kind of ugly though, but better than a supresslint).
You can also suppress more than one issue using a comma separated list:
#SuppressLint({"NewApi","StringFormatInvalid"})
Cheers!
Related
I want to check that Rectangle was tapped. This mehod does the job and it works almost how I want:
private bool CheckRectangleTouch(Rectangle target)
{
var touchCollection = TouchPanel.GetState();
if (touchCollection.Count > 0)
{
foreach (var touch in touchCollection)
{
if (target.Contains(touch.Position))
{
return true;
}
}
}
return false;
}
Problem I have is that after I've tapped rectangle it keeps returning true until I release it (it can register 10-30 times for one tap) and I want it to return true just once - for the first touch.
I've tried this (replace code inside foreach):
var isFirstTouch = !touch.TryGetPreviousLocation(out _);
if (target.Contains(touch.Position) && isFirstTouch)
{
return true;
}
And this (bad one, I don't really want it to register after release):
if (target.Contains(touch.Position) && touch.State == TouchLocationState.Released)
{
return true;
}
But nothing is does it. Either logic is not consistent or doesn't work at all.
So how do I check for tap?
Update: this works but it's very hacky, has delay and gives me random phantom taps:
try
{
var tap = TouchPanel.ReadGesture(); // falls each time when no input
return tap.GestureType == GestureType.Tap && target.Contains(tap.Position);
}
catch { }
return false;
Here's what I ended up doing:
I have singleton to hold my game state (many different props updated as needed). I added to it:
public TouchCollection TouchCollection { get; set; }
Prop to hold TouchPanel.GetState result. I fill it in Games Update method once per frame, as #craftworkgames suggested:
State.TouchCollection = TouchPanel.GetState();
Also I added this prop to my game state:
public bool TouchActive { get; set; }
And this is the method to check for rectangle tap. It returns true only for the first contact in tap:
private bool CheckRectangleTap(Rectangle target)
{
if (State.TouchCollection.Count == 0)
{ // if no input
return State.TouchActive = false;
}
var targetTouched = false;
foreach (var touch in State.TouchCollection)
{
if (target.Contains(touch.Position))
{
targetTouched = true;
}
}
if (targetTouched && !State.TouchActive)
{ // if target is touched and it's first contact
return State.TouchActive = true;
}
return false;
}
It doesn't seem ideal but it works for my case.
http://imgur.com/DzTRV2D
In android application i have code like below
private boolean isSpinnerNotChoose(Spinner spinner)
{
if(spinner.getSelectedItem().toString().equals(""))
{
return false;
}
return true;
}
But after many tries even if condition is completed it firstly enter on return false and later anyway debbugger goes on return true (If something stays after brackets its skipped but return true always is done. In link is image how its look after if is completed.
Anyone can answer me for that situation ?
Thanks in advance :)
Better use a boolean and return the boolean once.
The boolean is initially set to true.
It will remain true, if no match happens.
If there's a match, it will change to false.
Then the boolean will be returned (true if no match happens, false if there's a match).
No ghost responses.
I also added a trim(), to cut away the eventual trailing spaces.
Try:
private boolean isSpinnerNotChoose(Spinner spinner)
{
boolean myValue = true; // default return value
if(spinner.getSelectedItem().toString().trim().equals(""))
{
myValue = false;
}
return myValue; // return once and for all
}
I have this code in the ActionBarSherlock
#Override
public boolean onRequestSendAccessibilityEvent(View child, AccessibilityEvent event)
{
if (super.onRequestSendAccessibilityEvent(child, event)) {
// Add a record for ourselves as well.
AccessibilityEvent record = AccessibilityEvent.obtain();
onInitializeAccessibilityEvent(record);
// Populate with the text of the requesting child.
child.dispatchPopulateAccessibilityEvent(record);
event.appendRecord(record);
return true;
}
return false;
}
#Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setScrollable(isScrollableForAccessibility());
View selectedView = getSelectedView();
if (selectedView != null) {
info.setEnabled(selectedView.isEnabled());
}
}
#Override
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(event);
event.setScrollable(isScrollableForAccessibility());
View selectedView = getSelectedView();
if (selectedView != null) {
event.setEnabled(selectedView.isEnabled());
}
event.setCurrentItemIndex(getSelectedItemPosition());
event.setFromIndex(getFirstVisiblePosition());
event.setToIndex(getLastVisiblePosition());
event.setItemCount(getCount());
}
And I get compile errors on super.onInitializeAccessibilityEvent(event); and a few other methods.
Would anyone know why this happens?
Thanks!
The complaint is that your android:minSdkVersion is set to 8, and that code is referring to classes, methods, or fields that were not added until API Level 14.
If you are attempting to modify ActionBarSherlock and compile it yourself, you can either add the appropriate code to deal with this (checking Build.VERSION.SDK_INT) and add the #TargetApi() annotation to stop Lint from complaining.
I am trying to create a random (50/50) chance of a case A or case B happen in android and I need it to be as simple and as resource efficient as possible. I've looked through stackoverflow but all I find for random boolean is in C++?
Would appreciate if someone could give me a suggestion as to how to do this, whether with boolean or with strings/integers (since I was told that booleans is a primitive).
I tried the following
public static boolean getRandomBoolean() {
return Math.random() < 0.5; }
boolean atrg = getRandomBoolean();
if (atrg = true)
{ Toast.makeText(cxt, "TRUE", Toast.LENGTH_SHORT).show(); }
else if (atrg = false)
{ Toast.makeText(cxt, "FALSE", Toast.LENGTH_SHORT).show(); }
But in nearly every case, I tested (>20x), its TRUE?. This is likely a stupid question but is getRandomBoolean a boolean or an int/double? Sorry, I'm very new to android, as you probably guessed.
Your random generator is fine, but your toast displaying the result is not.
The problem is in the if-statement where you use a single equals sign (=) which is an assignment. The result of this assignment will be true and thus it will never show the "FALSE" toast.
Try this instead.
boolean atrg = getRandomBoolean();
if (atrg) {
Toast.makeText(cxt, "TRUE", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(cxt, "FALSE", Toast.LENGTH_SHORT).show();
}
This is not how you check boolean in if. = is the assignment operator and == is used for comparison. You should check like:
if(atrg == true)
or in case of boolean it is simply:
if(atrg)
Your statement:
if(atrg = true)
assigns atrg with true and you never get a false case.
Just use Math.random(), it will return a value between 0 and 1.. Example below:
public static boolean getRandomBoolean() {
return Math.random() < 0.5;
}
public static void main(String[] args) {
System.out.println(getRandomBoolean());
}
I can't for the life of me fix this. It is returning an error on else. I tried everything on all the other threads that had the same problem, but it didn't work.
#Override
public boolean onOptionsItemSelected(MenuItem item) { //this method is used for handling menu items' events
// Handle item selection
switch (item.getItemId()) {
case R.id.goBack:
if(myWebView.canGoBack()) {
myWebView.goBack();
}
return true;
else
return super.onOptionsItemSelected(item);{
}
}
}
Eclipse is complaining because the else statement does not follow an if statement -- there's a return true in between (which by the way prevents any code after it from being executed). Fixing your indentation and code formatting helps discover (and also prevent) simple mistakes like this.
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.goBack:
if (myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
}
return super.onOptionsItemSelected(item);
}
The error is because in java (and most-likely any programming language that defines if...else blocks such as c#, c, c++, etc.) the else block (if present) must come right after an if block or an else if statement definition any other statement between the if and else is illegal. However, you have a return statement right before the else block which is illegal and useless because any code blocks after a return statement becomes "unreachable"
You can change your code to...
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.goBack:
if (myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
break;
default:
return super.onOptionsItemSelected(item);
}
}