57

I'm not new to Android and I'm well used to the version handling and how to condition it, but when I see this it troubles me...

// Check if we're running on Android 5.0 or higher
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    // Call some material design APIs here
} else {
    // Implement this feature without material design
}

On any device pre lollipop this line would crash the app because the Build.VERSION_CODES.LOLLIPOP field does not exists... so why is this in the recommended solution in the documentation?

I'm really wondering what am I missing?

5

4 Answers 4

60

Well in that case use this

// Check if we're running on Android 5.0 or higher
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    // Call some material design APIs here
} else {
    // Implement this feature without material design
}

Build.VERSION_CODES.LOLLIPOP = 21

3
  • 2
    @Alexander Zhak answer is coreect... there is no point in the numeric value unless you compile to a lower version and want to handle higher versions
    – TacB0sS
    Dec 23, 2014 at 16:41
  • is it same as? @RequiresApi(Build.VERSION_CODES.LOLLIPOP) Dec 4, 2018 at 10:12
  • @AsifMushtaq: See this stackoverflow.com/questions/40007365/…
    – Rohit5k2
    Dec 4, 2018 at 14:56
29

Well, you must compile your project with the latest SDK version. Your constants are replaced with corresponding integer values during compilation. No matter what version of Android you run the application on - integers are the same

0
16

Try this one

 if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
       // Marshmallow+
   }else{
        //below Marshmallow
}

Note: Build.VERSION_CODES.LOLLIPOP_MR1==22

    Build.VERSION_CODES.M==23
0

Bit a late to answer, but, today I encountered with the same issue on Android Studio 3.4.1

So the workaround is:

Upgrade to the latest Android SDK.

And,

After Marshmallow/Android 6 Build.VERSION_CODES.xxx full names are replaced with initials and some other variations.

So, now for Marshmallow, it will be: Build.VERSION_CODES.M

And for Nougat: Build.VERSION_CODES.N

And so on.

Read more about the build version codes here: Android Developer Reference

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.