Use source 8 or higher to enable lambda expressions android studio

Содержание
  1. v5.0.0: error: lambda expressions and method references are not supported in -source 7 (use -source 8 or higher to enable) #330
  2. Comments
  3. davejlin commented Nov 12, 2021 •
  4. Version:
  5. Compile error:
  6. flutter doctor -v
  7. ggirotto commented Nov 12, 2021 •
  8. juliansteenbakker commented Nov 12, 2021
  9. juliansteenbakker commented Nov 12, 2021
  10. davejlin commented Nov 12, 2021 •
  11. ggirotto commented Nov 12, 2021
  12. nezoat commented Nov 12, 2021
  13. RobertHeim commented Nov 12, 2021
  14. nezoat commented Nov 12, 2021
  15. juliansteenbakker commented Nov 12, 2021
  16. nezoat commented Nov 12, 2021 •
  17. RedsAnDev commented Nov 13, 2021
  18. juliansteenbakker commented Nov 13, 2021
  19. jiangxiaoqiang commented Nov 14, 2021
  20. flutter-clutter commented Nov 14, 2021 •
  21. Cupidon277 commented Nov 14, 2021 •
  22. Обновление IntelliJ — > получить ошибку по лямбде
  23. 1 ответов
  24. Android studio: выражения lambda не поддерживаются в -7 (используйте источник 8 или выше для включения лямбда-выражений)
  25. ОТВЕТЫ
  26. Ответ 1
  27. Ответ 2
  28. Lambda выражения не поддерживаются-источник 1.7 (Android Studio)
  29. 2 ответа
  30. Похожие вопросы:
  31. Java 8 for Android: Cleaner Code With Lambda Expressions
  32. Java 8 for Android
  33. Preparing Your Development Environment
  34. Adding Java 8 Support to a New Project
  35. If You’re Migrating From Jack
  36. If You’re Migrating From Retrolambda
  37. Test Your Java 8 Support
  38. Why Are Lambda Expressions So Important?
  39. How Do I Create a Lambda Expression?
  40. The Argument
  41. The Expression Body
  42. Using Lambda Expressions in Your Android Apps
  43. Lambdas for Event Handling
  44. Lambdas for Multithreading
  45. Using Lambda Expressions in Your Real-Life Code
  46. Testing Lambda Expressions
  47. Conclusion

v5.0.0: error: lambda expressions and method references are not supported in -source 7 (use -source 8 or higher to enable) #330

Comments

davejlin commented Nov 12, 2021 •

I encountered a compiler error when trying to build with flutter_secure_storage v5.0.0 .
I was able to fix by adding compileOptions to specify Java v8 compatibility to your build.gradle :

Version:

Compile error:

I was able to get past the compiler errors by specifying the following compileOptions in the android block in:

flutter doctor -v

The text was updated successfully, but these errors were encountered:

ggirotto commented Nov 12, 2021 •

I’m facing the same problem. I couldn’t fix it using compileOptions .

juliansteenbakker commented Nov 12, 2021

Thanks for reporting, i have added your suggested fix and will release it asap.

juliansteenbakker commented Nov 12, 2021

I’m facing the same problem. I couldn’t fix it using compileOptions .

Can you try adding the compileOptions to your own project, and see if that works?

davejlin commented Nov 12, 2021 •

I’m facing the same problem. I couldn’t fix it using compileOptions .

Can you try adding the compileOptions to your own project, and see if that works?

@juliansteenbakker Thanks .
I tried that first, but it didn’t work (got the same compiler error).
Only when I added it to flutter_secure_storage ‘s did it compile successfully.

ggirotto commented Nov 12, 2021

@juliansteenbakker Thanks . I tried that first, but it didn’t work (got the same compiler error). Only when I added it to yours did it compile successfully.

Thanks for the clarification. I’ll be waiting for the release @juliansteenbakker

nezoat commented Nov 12, 2021

If you’re using a very old Gradle version, it will need to be updated.

In this file:
android/gradle/wrapper/gradle-wrapper.properties

Update this line:
distributionUrl=https://services.gradle.org/distributions/gradle-7.3-all.zip

Then build, should be fixed.

RobertHeim commented Nov 12, 2021

@nezoat’s this does not work for us

In file android/gradle/wrapper/gradle-wrapper.properties changing

and then running

we still see the original error

nezoat commented Nov 12, 2021

In this case, you already had gradle 6, so your issue is something else, but to support Java 8/Lambda features, you need to have Android Gradle Plugin 3.0.0+, and to have that plugin version, you need Gradle 4.1+. To use Gradle 7+, you need to be using JDK 11+.

juliansteenbakker commented Nov 12, 2021

The fix is to add the following to your own app project:

nezoat commented Nov 12, 2021 •

Adding the compileOptions did not fix it for me, my issue was the Gradle 3 version I was using, which doesn’t support Java 8/Lambda.

RedsAnDev commented Nov 13, 2021

The fix is to add the following to your own app project:

I’m totally disagree with this solution. Even use minSDK as 26 in defaultConfig, the issue remains.

juliansteenbakker commented Nov 13, 2021

I have searched on several places on the internet and all point to the same solution. You also need to upgrade your gradle android plugin to a minimum of 3.0.0 according to this answer: https://stackoverflow.com/a/51229919

Please refer to the official documentation for more explanation: https://developer.android.com/studio/write/java8-support

jiangxiaoqiang commented Nov 14, 2021

I am facing the same problem but none of the suggestion would fix it.

flutter-clutter commented Nov 14, 2021 •

I have tried every suggestion in this issue. Nothing fixes the problem for me. No gradle update to latest version, no compileOptions (in the project that uses flutter_secure_storage ).

Only solution for me: using version 4.2.1 of flutter_secure_storage instead.

Cupidon277 commented Nov 14, 2021 •

Hello guys, I had the same issue and following this thread I fixed it doing the following:

Disclaimer: I started learning Flutter literally two days ago, don’t judge if I misused any of the steps below.

Long story short for the experts here, upgrade Gradle to 7+

Below is what I did to solve it

First I ran the ./gradlew —version command in the android directory of my project and got the following information:

Gradle 6.4 Kotlin: 1.5.31 Groovey: 3.0.9 JVM: 11.0.11

Then as juliansteenbakker mentioned I followed the provided link

And:
1- Installed gradle 7 by changing the gradle version to gradle-7.3-all.zip in the file android/gradle/wrapper/graddle-wrapper.properties
2- (I am not sure this helps but I have done it anyways?)
From terminal project root, ran the command flutter upgrade-packages then flutter clean then flutter pub get
3 — Changed the Gradle version in dependencies in the android/build.gradle file as mentioned in the previous link like this:
class path ‘com.android.tools.build:gradle:7.0.0’
4- From terminal changed directory to android and ran the command ./gradlew clean

Then i ran again the command ./gradlew —version from the android directory and got the output:

Источник

Обновление IntelliJ — > получить ошибку по лямбде

я обновил свою идею IntelliJ сегодня утром, и после этого я открываю свой проект, и внезапно я получаю ошибку в своих лямбда-выражениях.

сначала я получил это:

а затем я попытался изменить уровень Langugage проекта, а затем установить его по умолчанию. Теперь я понимаю:

Читайте также:  Андроид планшеты выбрать лучший

IntelliJ Варианты ProjectStructure:

Это моя лямбда: И я говорю это снова, прежде чем . обновленный IntellJ сработал:

1 ответов

вы configued свой проект уровень языка, вам также нужно настроить модуль уровень языка. Подробнее на настройка глобальных, проектных и модульных SDKs.

на Структура Проекта → Модуль tab ( ⌘ + ; on В macOS или Ctrl + Alt + Shift + S on Windows OS) и проверьте уровень языка вашего модуля там:

вам также может потребоваться изменить версия компилятора Java как хорошо. Перейти к настройки диалог ( ⌘ + , on В macOS или Ctrl + Alt + S on ОС Windows), перейти через Сборка, Выполнение, Развертывание → Компилятор → Java Compiler (или просто наберите javac в поле поиска сверху) и менять версию компилятора Java, как показано ниже:

Источник

Android studio: выражения lambda не поддерживаются в -7 (используйте источник 8 или выше для включения лямбда-выражений)

С удовольствием узнаем, что java ввела Лямбда-выражения в java-версию 8.

Я работал в андроид-студии. И я заметил, что DialogInterface.OnClickListener() показывал подчеркивание и стал серым цветом, как показано ниже:

Итак, я сделал alter + enter в этой строке и нашел вариант для замены кода на Lambda Expressions, как показано ниже:

В результате получилось что-то ниже:

После запуска кода он показал мне эту ошибку:

Ошибка: (160, 69) ошибка: лямбда-выражения не поддерживаются в-источнике 1.7 (для включения лямбда-выражений используйте источник 8 или выше)

Но я уже использую java jdk1.8.0_31 . Есть ли что-то еще, мне нужно установить?

Может кто-нибудь помочь мне, пожалуйста.

ОТВЕТЫ

Ответ 1

Вы не можете скомпилировать источники Java 8 для Android, потому что Android SDK еще не поддерживает Java 8.

Но есть один способ использования Lambdas в вашем коде — RetroLambda. Это небольшой взлом, который позволяет вам использовать некоторые функции Java 8 в вашем проекте.

Ответ 2

Я не думаю, что разработка Android еще не готова для Java 8 . Android Studio поддерживает уровень компиляции Java 7 , установлен ли Java 7 или Java 8 . Итак, если вы хотите использовать новые функции Java 8 , я думаю, вам нужно подождать Android Studio для поддержки compile level Java 8 .

Источник

Lambda выражения не поддерживаются-источник 1.7 (Android Studio)

Я пытался запустить свой проект android в Android Studio,но не смог.

Я получаю эту ошибку:

Я использую JDK 1.8.

Есть идеи, почему это происходит? Любое решение.

PS: есть пара подобных вопросов в стеке, но ни один из них не решил эту проблему. Пожалуйста, поймите проблему, прежде чем помечать дубликат.

2 ответа

Я пытаюсь скомпилировать проект maven, то есть Java 8 (JDK 1.8), и когда я запускаю следующую команду: mvn clean compile Компиляция выдает следующую ошибку Сбой компиляции [ERROR] /C:/App.java:[16,35] lambda выражения не поддерживаются в исходном коде 1.5 [ERROR] (используйте-source 8 или выше.

Android не может быть построен на JDK 1.8 ; И выражение Lambda не может быть использовано в JDK ниже 1.8.

Решение состоит в том, чтобы вернуться к JDK 1.7 и избежать использования знака Lambda. Вместо использования:

Мы должны использовать это:

Похоже, вам нужно передать : -source 8 компилятору в качестве аргумента.

Похожие вопросы:

При попытке использовать выражения lambda я получил некоторые ошибки сборки Gradle: Ошибка: (41, 100) ошибка: lambda выражения не поддерживаются в исходном коде 1.7 (используйте-source 8 или выше.

Рад узнать, что java ввел Lambda выражений в java версии 8. Я работал в 40-м. И я заметил, что DialogInterface.OnClickListener() показывает подчеркивание и становится серым, как показано ниже: Итак.

Когда я пишу выражение lambda в Android studio, оно иногда превращается в обычный анонимный класс, и я не могу его вернуть. Как я могу помешать IDE сделать это? И в чем же причина? Если я нажму на.

Я получаю ошибку lamba выражения не поддерживаются на уровне языка 7 в android studio, который я использую. Кто-нибудь знает, как я мог бы исправить эту проблему. FloatingActionButton fab =.

Источник

Java 8 for Android: Cleaner Code With Lambda Expressions

Lambda expressions can help you remove boilerplate code from your projects and process huge amounts of data with ease. See how with this in-depth look at the Java 8 features you can start using in your Android projects today.

Java 8 for Android

Java 8, which debuted way back in March 2014, was a big step forward for the programming language, introducing a list of features that promised to make coding in Java easier and more concise than ever before.

Unfortunately, Android developers wouldn’t feel the benefits of these features for a while, as Google experimented with bringing Java 8 to the Android platform via Jack (Java Android Compiler Kit) before deprecating Jack in favour of supporting Java 8 natively in Android Studio.

Now, with the release of Android Studio 3.0, we finally have a version of the Android toolchain that has built-in support for some of Java 8’s most important features.

In this series, I’m going to show you how to remove a ton of boilerplate code from your projects, process huge amounts of data with ease, and even embrace a more functional style in your Java programing with Java 8. We’ll be taking an in-depth look at the Java 8 features that you can start using today.

By the time you’ve completed this series, you’ll be ready to use all of the following Java 8 features in your Android projects:

  • lambda expressions
  • method references
  • default methods
  • static interface methods
  • type annotations
  • repeating annotations
  • functional interfaces
  • the Stream API

In this first post, we’re going to look at the feature that generated the most buzz when Java 8 was first released, and that has the potential to make the most difference to Android developers: lambda expressions.

Preparing Your Development Environment

Before you can start using any Java 8 features, you need to make sure that your development environment is set up to support this version of Java.

If you don’t already have Java 8 installed, then you’ll need to download the latest JDK8 and update Android Studio’s JDK path so that it’s pointing at the JDK8 package:

  • Launch Android Studio.
  • Select File > Project Structure… from the Android Studio toolbar.
  • Update the JDK Location field so that it’s pointing at your newly downloaded JDK8 package.

If you’re not sure what version of Java you have installed, then you can check by opening a Terminal window (if you’re a Mac user), or a Command Prompt (if you’re on Windows) and then running the following command:

If it returns build 1.8 or higher, then you’re good to go!

You’ll also need to have Android Studio 3.0 Preview 1 or higher installed, although to reduce your chances of encountering bugs and other strange behaviour, it’s recommended that you install the latest version of Android Studio 3.0—whether that’s a beta or preview or, ideally, a stable version of Android Studio 3.0 (which wasn’t yet available at the time of writing).

Next, you’ll need to make some changes to your project’s build.gradle files. Usually, you’ll just need to add a few lines of code specifying that this project should generate Java 8 bytecode. However, if you’ve previously experimented with Java 8 features using the Jack compiler or the popular Retrolambda project, then you’ll need to disable these tools before your project can use the new-and-improved Java 8 support provided by Android’s default toolchain.

In the following sections, I’ll show you how to enable Java 8 support, and how to disable Retrolambda and Jack, if required.

Adding Java 8 Support to a New Project

Assuming that you haven’t previously enabled Jack or added Retrolambda as a project dependency, the first step is opening your project-level build.gradle file and making sure that you’re using version 3.0.0-alpha1 (or higher) of the Gradle for Android plugin:

Next, open every module-level build.gradle file where you want to use Java 8 features, and set the language level of the source code and the version of the generated Java bytecode to JavaVersion.VERSION_1_8 :

If You’re Migrating From Jack

The Jack compiler may be deprecated, but as long as it’s enabled, your project is going to use the Java 8 support provided by Jack, rather than the support provided by Android’s default toolchain.

Using a deprecated tool is never a good idea, but there are some additional reasons why you should migrate from the Jack compiler, if you haven’t already.

Firstly, Jack may support a subset of Java 8 features, but unlike the default toolchain it doesn’t support third-party libraries that use these features, so by using Jack you’re immediately limiting your options when it comes to third-party libraries.

Secondly, the Jack compiler takes Java code and converts it directly into dex, without producing any intermediate bytecode. As long as Jack is enabled, you’ll be unable to use any of the tools that rely on this intermediate output, such as annotation processors and bytecode analyzers.

To disable the Jack compiler, open your module-level build.gradle file and remove the jackOptions section, but make sure you leave the compileOptions block intact:

If You’re Migrating From Retrolambda

Similar to Jack, Retrolambda doesn’t support third-party libraries that use Java 8 language features. If your project is set up to use the Retrolambda plugin, then you should remove this plugin so that your project can revert to the default toolchain.

Open your project-level build.gradle file and remove Retrolambda as a project dependency:

Then, remove the Retrolambda plugin from each of your module-level build.gradle files:

Test Your Java 8 Support

The easiest way of verifying that your project can now support Java 8 is to write a quick lambda expression and see whether your project still compiles.

Add a button to your user interface (or use a button that already exists) and then implement an onClickListener for this button, using a lambda expression. Don’t worry if the following code doesn’t make much sense now—it will by the end of this article!

Check that your project still compiles, either by selecting Sync from the banner that appears, or by selecting Tools > Android > Sync Project with Gradle Files from the Android Studio toolbar.

If Android Studio doesn’t throw any errors, then you’re ready to start using all the features we listed at the start of this article, including lambda expressions!

Why Are Lambda Expressions So Important?

Lambda expressions were easily Java 8’s biggest new feature, and can have a huge impact on the amount of boilerplate code you need to write when creating pretty much any Android app.

Essentially, a lambda expression represents a function that doesn’t belong to any class, and that you can pass around with ease and then execute on demand.

This feature removes a long-standing frustration many Android developers have experienced with Java: as an object-oriented language, passing around blocks of code has always felt more difficult than it should be. For example, if you wanted to create a new thread and then pass some code to that thread, then you’d typically have to instantiate a thread with an anonymous implementation of the Runnable interface—that’s a lot of work just to pass some code! By providing an easy way of passing a function to a method, lambda expressions have the potential to simplify some of the most common tasks that you’ll perform as an Android developer.

Lambda expressions will also be a welcome addition for any Java developers who want to take a more functional approach to their programming. Prior to Java 8, coding in a functional style would inevitably require you to write lots of boilerplate code, but now that you can pass functions around using lambda expressions, writing your Java code in a less object-oriented way doesn’t have to involve writing a ton of anonymous classes.

How Do I Create a Lambda Expression?

You create a lambda expression using the following syntax:

The arrow operator is pretty self-explanatory, but the rules for how you should structure the lambda’s argument and expression can vary depending on what you’re trying to achieve, so let’s explore these two elements in more detail.

The Argument

The argument is one or more parameters, which are almost always enclosed in parentheses. Even if your lambda expression doesn’t have any parameters, you’ll still need to supply empty parentheses, for example:

The exception to this rule is when your method has a single parameter with its type inferred, in which case you can omit the parentheses:

You can use multiple parameters in your argument, by separating each parameter with a comma:

Type inference is possible in lambdas, so you can generally omit the data type from your argument. However, if the compiler cannot infer the data type, then you’ll need to add the type in front of your parameter(s):

The Expression Body

The expression body is the code that you want to execute, which can be a single expression or multiple lines of code. If you want to execute multiple lines, then you’ll need to create a statement block by surrounding this section of your code with curly braces:

If your expression returns a value, then it must be returned with a return statement, for example:

Using Lambda Expressions in Your Android Apps

Now we have an overview of the various ways that you can structure a lambda expression, let’s take a look at some of the most common scenarios where you can use lambda expressions in your Android development work.

Lambdas for Event Handling

Your typical Android app has to be able to respond to a wide range of user input events, and lambda expressions can make this event handling much more straightforward.

In the following code, we’re using an anonymous class to create an instance of onClickListener with an overridden onClick method. Chances are, you’ve written this kind of code countless times.

By rewriting the above code with a lambda expression, we can remove all of the following:

  • the class instantiation: new View.OnClickListener()
  • the access modifier, method name, and type: public void onClick(View view)
  • and the parameter types, so you don’t have to write View view

This means that we can implement exactly the same functionality, using a single line:

Lambdas for Multithreading

Multithreading is another common scenario where lambda expressions can help you write cleaner code. By default, Android has a single UI (user interface) thread that’s responsible for handling all user interaction, dispatching events to the appropriate UI widgets, and modifying the user interface. As soon as you block this UI thread with any long-running or intensive operations, your application is going to become unresponsive, and may even trigger Android’s ANR (Application Not Responding) dialog. So creating additional threads and assigning code to run on those threads is often an essential part of Android development.

Prior to Java 8, assigning code to run on an additional thread required you to create an anonymous class that implements the Runnable interface:

Alternatively, you could instantiate a new thread with an anonymous implementation of the Runnable interface:

Replacing this anonymous class with a lambda expression can make this frequently performed task much more concise:

Finally, if you’re using the RxJava or RxAndroid library, then you can use lambda expressions to help you create observables.

Here, we’re creating a simple Observable that emits the hello world string to all of its Observers :

Using a lambda expression allows you to replace all of that Action1 code with a single line:

Using Lambda Expressions in Your Real-Life Code

After reading all the theory behind a new feature, the next challenge is getting into the habit of actually using this new feature. This can be particularly tough with something like lambdas, which are designed to be used instead of familiar boilerplate code, as there’s always the temptation to simply fall back on what you know.

Android Studio has a few features that can help give you that final push to replace familiar-but-clunky code with shiny new lambda expressions.

The first feature is Android Studio’s intent actions menu, which can auto-convert any compatible anonymous class into the equivalent lambda expression. This is perfect if you’re ever unsure about how to write a particular piece of code in a lambda format: simply write it as usual, and then use the intent action menu’s auto-convert feature.

To auto-convert an anonymous class into a lambda expression:

  • Hover your cursor over the anonymous class, and Android Studio should display a tooltip informing you that it can convert this section of code into a lambda expression.
  • Press your Mac’s Alt/Option-Enter keys, or use the Alt-Enter shortcut if you’re a Windows or Linux user.
  • Select the Replace with lambda option from the context menu.

Alternatively, you can use Android Studio’s Inspection tool to flag every anonymous class that you could potentially replace with a lambda expression, across your entire project. You can then either rewrite each anonymous class manually or let Android Studio’s auto-convert feature show you how it’s done.

To highlight every anonymous class that Android Studio could potentially replace with a lambda expression:

  • Select Analyze > Run Inspection by Name from the Android Studio toolbar.
  • In the popup that appears, start typing Anonymous type can be replaced with lambda, and then select this option when it appears in the dropdown menu.

  • In the subsequent window, select Whole project to flag every anonymous class across your project. Alternatively, you can specify individual modules or files where Android Studio should run this inspection.
  • Click OK.
  • Select Analyze > Inspect Code from the Android Studio toolbar.

The Inspection Results pane should now appear and display a list of all the anonymous classes that you can replace with a lambda expression. To take a closer look at an anonymous class, simply double-click that class in the Inspection Results window, and Android Studio will open the file and take you to the exact line that contains this particular anonymous class.

To replace the currently selected anonymous class with a lambda expression, give the Replace with lambda button a click.

If Android Studio doesn’t open the Inspection Results window automatically, then you can launch it manually by selecting View > Tool Windows > Inspection Results from the Android Studio toolbar. If Inspection Results doesn’t appear in the Tool Windows sub-menu, then you may need to select Analyze > Inspect Code… from the Android Studio toolbar first.

Testing Lambda Expressions

Despite the many benefits that lambda expressions have to offer, there’s one major drawback that you should be aware of before adding them to your code. Since lambdas don’t have a name, you can’t call them directly from your test code, so adding a large number of lambdas to your project can make it more difficult to test.

Ideally, your lambda expressions should be too simple to break, so being unable to unit test them shouldn’t be too big of an issue. However, if you do need to test a lambda, then you can always treat it like a private method and unit test the outcome, rather than the lambda itself. Alternatively, you could refactor the lambda expression into its own method, so you can reference it directly and therefore test it as normal.

Conclusion

In this first post on Java 8 language features, we looked at how to set up your Android projects to support Java 8, and how to cut down on boilerplate code by replacing anonymous classes with lambda expressions.

In the next post, I’ll be showing you how to trim even more code from your Android projects by combining lambda expressions with method references, and how you can enhance your interfaces with default and static interface methods.

In the meantime, check out some of our other posts about Android app development!

Источник

Оцените статью