2

I'm calling findViewById and Android Studio (version 3.1, stable) prompts me to put an assertion:

enter image description here

When I select it, it adds the following line above the selected line:

assert v != null;

Great. I run the app, and the View v is null. However, assertion doesn't work and it jumps to the line below it in debugger:

enter image description here

How is this even possible? It was Android Studio's own suggestion, and I didn't change a thing. Its own recommendation/autogenerated code is not working. Am I missing something obvious?

11
  • 1
    Haven't worked with AS, so unfortunately I don't know why the linter suggests this. Personally, I never use assert (and here is a good discussion about some reasons why). Instead I prefer explicit (not disableable) validators such as Guava Preconditions (might not be available in Android). Commented Jul 10, 2018 at 0:37
  • 1
    1. Instead of assert statement, use something like if (v == null && BuildConfig.DEBUG) Log.e("your_tag", "your_message"); else { mapView = v.findViewById (R.id.MapView);} Commented Jul 10, 2018 at 5:17
  • 1
    2. If you know the parent activity of the MapView, you can just call findViewById on the layout root of the parent activity. In or after Creation of activity, (basically once onCreate is called), you can rest assured that the root layout of the parent activity will never be null. So you need not check for if(root !=null) mapView = root.findViewById(R.id.MapView); Commented Jul 10, 2018 at 5:18
  • 1
    3. You can have a look at ButterKnife and it can map all your required views with Java Objects at compile time, without you having to use findViewById at all. It reduces boilerplate and runtime code. So if your project is decently sized, you can maybe look at Butterknife. Commented Jul 10, 2018 at 5:18
  • 1
    @Raymond232 thank you, I'll look at ButterKnife, it sounds good. But my main point is that why AS recommends me to take some action that does absolutely nothing in default settings in the first place. Commented Jul 10, 2018 at 10:21

1 Answer 1

3

Apparently, (as stated in the comments) assertions are disabled by default but encouraged by Android Studio.

In this manner, the "problem" can be classified as a misleading UX issue rather than a technical problem.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.