Error message:
java.lang.NoClassDefFoundError: Failed resolution of: Ljava/time/LocalDate;
This error is caused by not finding the class in Android java.time.LocalDate
. The reason is that java.time
this package was introduced in Java 8. Usually, Android only supports some features of Java 7 and does not support new features of Java 8. Therefore, it cannot be directly used in Android. Use java.time
classes from packages ( IDEA before May 2021 or AS before August 2020 ).
There are two ways to solve this problem:
-
Use Android's own
java.util.Date
classes instead ofjava.time.LocalDate
classes. -
To use the new features of Java 8 in an Android project,
build.gradle
the following configuration needs to be added to the file:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
// ...
}
dependencies {
implementation 'com.android.tools:desugar_jdk_libs:1.1.5'
// ...
}
Then import the package into the code java.time
:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
Note: To use this method, you need to use Android Studio version 3.0 and above, and you need to run an operating system of Android 5.0 and above on the device.
The method used java.util.Date
instead java.time.LocalDate
is as follows:
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String parsedDateString = sdf.format(date);
txtDate.setText(parsedDateString);