【问题标题】:Try_catch block not supported android studio language level 8?Try_catch 块不支持 android studio 语言级别 8?
【发布时间】:2021-02-13 20:02:34
【问题描述】:

我正在 Android Studio 中制作应用:

public class MainActivity extends AppCompatActivity {

    SharedPreferences sharedPreferences;
    EditText noteTitleField, noteContentField;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sharedPreferences = getSharedPreferences("NoteAppPrefs", Context.MODE_PRIVATE);
        String setValueInPrefs = sharedPreferences.getString("alreadyLaunched", null);
        try (setValueInPrefs.equals("0")) {
            Log.d("debugging", "App running for first time... launching setup");
            setupForFirstTime();
        } catch (NullPointerException e) {
            noteContentField = findViewById(R.id.noteContentTextBox);
            noteTitleField = findViewById(R.id.noteTitleTextBox);
            Toast.makeText(MainActivity.this, R.string.welcomeMessage, Toast.LENGTH_LONG);
        }
    }
}

但是,我收到“语言级别 8 不支持资源引用”。

我检查了一些类似intellij feature (...) not supported at this language level. I can't compile 的线程以找出错误可能来自哪里,但我检查了 Project JDK 版本和 Android Studio JRE,它们在“java 版本 1.8”上匹配

【问题讨论】:

  • 永远不要捕获 nullpointerexceptions 而是检查 null。

标签: java android


【解决方案1】:

线

try (setValueInPrefs.equals("0")) {

无效。在Java 8代码中括号内的代码必须是赋值语句(VariableDeclaratorId = Expression)和

资源规范中声明的变量类型必须是 AutoCloseable 的子类型,否则会出现编译时错误。

Java 9放宽了赋值语句的部分(现在也可以是变量或字段),但仍然

在资源规范中声明或引用为资源的变量的类型必须是 AutoCloseable 的子类型,否则会发生编译时错误。

您正在使用setValueInPrefs.equals("0") 作为表达式,这会产生一个布尔值并且boolean 不是 AutoCloseable 的子类型。

要修复它,您应该将 try 块替换为

    if (setValueInPrefs != null) {
        if (setValueInPrefs.equals("0")) {
            Log.d("debugging", "App running for first time... launching setup");
            setupForFirstTime();
        }
    } else {
        noteContentField = findViewById(R.id.noteContentTextBox);
        noteTitleField = findViewById(R.id.noteTitleTextBox);
        Toast.makeText(MainActivity.this, R.string.welcomeMessage, Toast.LENGTH_LONG);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-17
    • 2014-08-09
    • 2017-10-15
    • 2015-05-26
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 2016-02-29
    相关资源
    最近更新 更多