在Activity onCreate方法中,Kotlin视图变量意外地为null

时间:2017-06-05 15:33:53

标签: android android-studio kotlin kotlin-android-extensions

我有一个小型的Java Android Studio项目,我使用Android Studio 3.0 Canary 3中的Kotlin转换器将所有四个源文件转换为Kotlin。然后我做了一些小修改来编译它。我只有一个活动,其中包含以下代码:

package com.ebelinski.soundboard

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.AdapterView
import kotlinx.android.synthetic.main.activity_storyboard.gridview;

class StoryboardActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val itemManager = ItemManager(applicationContext)
        val items = itemManager.getItems().toTypedArray<Item>()

        setContentView(R.layout.activity_storyboard)
        val storyboardAdapter = StoryboardAdapter(this, items)
        gridview.adapter = storyboardAdapter

        gridview.onItemClickListener = AdapterView.OnItemClickListener { parent, v, position, id ->
            // todo
        }
    }

}

当我运行时,我收到以下错误:

06-05 10:25:42.758 5668-5668/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.ebelinski.soundboard, PID: 5668
                                                 java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter convertView
                                                     at com.ebelinski.soundboard.StoryboardAdapter.getView(StoryboardAdapter.kt)
                                                     at android.widget.AbsListView.obtainView(AbsListView.java:2363)
                                                     at android.widget.GridView.onMeasure(GridView.java:1065)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                     at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                     at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                     at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:393)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                     at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                     at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                     at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                     at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                     at com.android.internal.policy.DecorView.onMeasure(DecorView.java:689)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2275)
                                                     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1366)
                                                     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1619)
                                                     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6337)
                                                     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                     at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                     at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                     at android.os.Handler.handleCallback(Handler.java:751)
                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                     at android.os.Looper.loop(Looper.java:154)
                                                     at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

我不确定这里的问题是什么。显然gridview为空,但我不知道为什么。当我注释掉gridview.adaptergridview.onItemClickListener行时,至少程序不会崩溃。在使用kotlin-android-extensions之前,我收到了相同的错误消息,并将相关变量定义为val gridView = findViewById(R.id.gridview) as GridView

相应的XML文件包含以下内容:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_storyboard"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.ebelinski.soundboard.StoryboardActivity">

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:columnWidth="100dp"
        android:numColumns="auto_fit"
        android:verticalSpacing="24dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="spacingWidthUniform"
        />
</RelativeLayout>

我的原始Java代码适合这个类,但是:

package com.ebelinski.soundboard;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

public class StoryboardActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ItemManager itemManager = new ItemManager(getApplicationContext());
        final Item[] items = itemManager.getItems().toArray(new Item[itemManager.getItems().size()]);

        setContentView(R.layout.activity_storyboard);
        GridView gridView = (GridView)findViewById(R.id.gridview);
        StoryboardAdapter storyboardAdapter = new StoryboardAdapter(this, items);
        gridView.setAdapter(storyboardAdapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                // todo
            }
        });
    }

}

3 个答案:

答案 0 :(得分:0)

Kotlin使用安全呼叫运算符提供空检查。您可以在访问视图之前使用它。 Safe Calls。例如,

gridview?.adapter = storyboardAdapter

答案 1 :(得分:0)

您提供给StoryboardAdapter的null值似乎是异常。作为错误行,

Parameter specified as non-null is null

items为空。检查您的代码。并且尝试在数组初始化之前调用setContentView,因为我怀疑可能与applicationContext

有关系

答案 2 :(得分:-1)

我认为问题出现在kotlin-android-extensions中,你的代码看起来不错,只是尝试清理项目并更改网格视图ID。你也可以阅读关于配置kotlin-android-extensions的精彩文章,这是一个很酷的工具,你会忘记findViewById。另外请在稳定版的studio和android插件中试用它,并确保将其导入主gradle文件并应用于app gradle文件。