android - ListView的setAdapter方法中的NullPointerException

标签 android listview android-adapter

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

enter image description here 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()

关于android - ListView的setAdapter方法中的NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35956140/

相关文章:

android - 在运行时将项目添加到 gridview 而不是替换以前的项目

java - 可点击的 BaseAdapter 行?

java - 如何在android中设备方向改变后保持listview项目的高亮

Android:数据绑定(bind)文本未更新

android - 在Android中一起列出音频和视频

listview - 如何在javafx中获得透明 ListView ?

java - 显示相同内容的 Android Studio 选项卡式 Activity

android - Gradle File中有问题(下面的错误消息)?

java - Android ListView 像 Twitter 列表一样滑动操作

android - 自定义适配器 : get item number of clicked item in inflated listview