ListView的setAdapter方法中的NullPointerException

NullPointerException in setAdapter method of ListView

我的代码工作正常,但我担心 android studio 在检查代码时给出的警告 [=21] =] 代码。它说它可能会产生空指针异常。我无法弄清楚背后的原因。我浏览了与同一问题相关的其他一些答案,但找不到确切原因。这是 android studio 的消息快照。

Activity代码

package com.example.kedee.mistu.services;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.example.kedee.mistu.R;

public class Test extends AppCompatActivity {
    private String[] catNames= {"A","E","T","E","S","F","M","P","S","E","C","H","M","Others"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        ListView listView=(ListView)findViewById(R.id.test_listView);
        //next line
        listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,catNames));
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }
}

布局代码

<?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: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.example.kedee.mistu.services.Test">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/test_listView"
        android:dividerHeight="2dp"
        >

    </ListView>

</RelativeLayout>

我不确定,但你可以试试下面的代码

if(listView!=null)
{
     listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,catNames));
       listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}

尝试使用

ActivityName.this or getApplicationContext()