Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rid of Suspicious call warning on Android Studio?

In my code I have an ArrayList<Buttons> field named mButtons. Each of these buttons invoke (in XML) the same onClick function onButtonClick. The function looks like this:

public void onButtonClick(View view) {
    int buttonIndex = mButtons.indexOf(view);
}

But Android Studio keeps warning me about a Suspicious call to 'ArrayList.indexOf'.

Ok, I tried to get rid by casting view to Button. Then the warning changed to Casting 'view' to 'Button' is redundant.

Well, I tried to change the function signature to receive a Button instead of a View. But now I have one warning on each Button declaration (XML): Method 'onButtonClick' on '...Activity' has incorrect signature.

I'm really considering just add the //noinspection SuspiciousMethodCalls since it seems there's no workaround for it.

I would appreciate if anyone knows how to get rid of it.

like image 646
gfpacheco Avatar asked May 03 '15 00:05

gfpacheco


2 Answers

You can cast to Button the line before.

Button button = (Button) view;
int buttonIndex = mButtons.indexOf(button);
like image 55
Paul Boddington Avatar answered Oct 15 '22 02:10

Paul Boddington


Just as an extra answer, you just need to wrap the call in an instanceof check

if (view instanceof Button) {
    buttonIndex = mButtons.indexOf(button);
}

Basically the suspicious call is saying "There's no guarantee this is a valid object to look for"

(Sorry for the slow reply, I hit this thread when looking for an answer and I figured that providing an alternative solution would be the best)

like image 4
Doug Edey Avatar answered Oct 15 '22 04:10

Doug Edey