java.lang.NoClassDefFoundError: Failed resolution of: Ljava/time/LocalDate in Android; the cause and solution of the error

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.timethis 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.timeclasses from packages ( IDEA before May 2021 or AS before August 2020 ).

There are two ways to solve this problem:

  1. Use Android's own java.util.Dateclasses instead of java.time.LocalDateclasses.

  2. To use the new features of Java 8 in an Android project, build.gradlethe 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.Dateinstead java.time.LocalDateis as follows:

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String parsedDateString = sdf.format(date);
txtDate.setText(parsedDateString);

Guess you like

Origin blog.csdn.net/wh445306/article/details/130169579