ListView的setAdapter方法中的NullPointerException

时间:2016-03-12 09:54:54

标签: android listview android-adapter

我的代码工作正常,但我担心android studio在检查以下活动代码中注释(//下一行)旁边的代码时发出的警告。它说它可能会产生空指针异常。我无法弄清楚背后的原因。我经历了一些与同一问题相关的其他答案,但找不到确切的原因。这是android studio的消息快照。

enter image description here 活动代码

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>

1 个答案:

答案 0 :(得分:1)

我不确定,但您可以尝试以下代码

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()