首页 > 解决方案 > 在 ListView 中显示两个项目,在 null 对象引用上获取 setAdapter()

问题描述

我正在尝试使用两个单独的 TextView 项创建一个 ListView。我的 ListView 是 content_main.xml (R.id.list) 的一部分,而 TextViews 是 list_item.xml (R.id.textUp, R.id.text2) 的一部分。我得到的错误是ListView.setAdapter(android.widget.ListAdapter)' on a null object reference. 这就是在我的 java 代码中分配 hashmap 和 listView 的方式:

        private ListView list;
        private HashMap<String, String> associatedItem;

 protected void onCreate(Bundle savedInstanceState) {//LayoutInflater inflater
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_goal_text);
        list = findViewById(R.id.list);
        associatedItem = new HashMap<String, String>();
        ...

和处理程序:

 public void doneButtonHandler(View view) {

    int   day  = picker.getDayOfMonth();
    int   month= picker.getMonth();
    int   year = picker.getYear();
    Calendar calendar = Calendar.getInstance();
    calendar.set(year,month,day);

    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy", US);
    String formatedDate = sdf.format(calendar.getTime());

    associatedItem.put(formatedDate, strMssg);

    ArrayList<HashMap<String, String>> listItems = new ArrayList<HashMap<String, String>>();

    Iterator it = associatedItem.entrySet().iterator();
    while (it.hasNext())
    {
        HashMap<String, String> resultsMap = new HashMap<>(2);
        Map.Entry pair = (Map.Entry)it.next();
        resultsMap.put("First Line",formatedDate);
        resultsMap.put("Second Line",strMssg);//pair.getValue().toString()
        listItems.add(resultsMap);
    }

    SimpleAdapter adapter = new SimpleAdapter(this, listItems ,R.layout.list_item,
            new String[]{"First Line", "Second Line"},
            new int[]{R.id.textUp, R.id.text2});

    list.setAdapter(adapter);
}

错误日志:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
        at com.example.gryzhuk.goaltracker.AddGoal.doneButtonHandler(AddGoal.java:134)

activity_add_goal_text.xml :

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AddGoal"
    tools:layout_editor_absoluteY="81dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="28dp"
        android:layout_marginBottom="23dp"
        android:text="@string/enter_goal"
        android:textSize="20sp"

        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


    <Button
        android:onClick="nextButtonHandler"
        android:id="@+id/next_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="53dp"
        android:text="@string/next_button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/enteredGoalTxt"
        app:layout_constraintVertical_bias="1.0" />

    <EditText
        android:id="@+id/enteredGoalTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="126dp"
        android:ems="10"
        android:hint="Enter here"
        android:inputType="textShortMessage"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView android:id="@+id/textUp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/colorLineUp"
        android:textSize="21sp"
        android:textStyle="bold"
        />

    <TextView android:id="@+id/text2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:textColor="@color/colorLineBottom"
        android:textStyle="bold"
        />
</LinearLayout>

content_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">


    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:fab="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context="com.teamproblemsolver.fabsubmenu.MainActivity">

        <com.github.clans.fab.FloatingActionMenu
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="10dp"
            fab:menu_animationDelayPerItem="50"
            fab:menu_backgroundColor="@android:color/transparent"
            fab:menu_buttonSpacing="0dp"
            fab:menu_colorNormal="@color/colorPrimaryDark"
            fab:menu_colorPressed="#c784d3ed"
            fab:menu_colorRipple="#99FFFFFF"
            fab:menu_fab_hide_animation="@anim/hide_to_bottom"
            fab:menu_fab_show_animation="@anim/show_from_bottom"
            fab:menu_fab_size="normal"
            fab:menu_icon="@drawable/fab_add"
            fab:menu_openDirection="up"
            fab:menu_shadowColor="#66000000"
            fab:menu_shadowRadius="4dp"
            fab:menu_shadowXOffset="1dp"
            fab:menu_shadowYOffset="3dp"
            fab:menu_showShadow="true">


            <com.github.clans.fab.FloatingActionButton
                android:id="@+id/add_to_list"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_add_to_list"
                fab:fab_colorNormal="@color/colorPrimary"
                fab:fab_colorPressed="#c784d3ed"
                fab:fab_label="Add Goal"
                fab:fab_size="mini" />

        </com.github.clans.fab.FloatingActionMenu>

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />



    </RelativeLayout>


</android.support.constraint.ConstraintLayout>

标签: androidandroid-studiolistviewandroid-adaptersimpleadapter

解决方案


在您的视图中检查此行

associatedItem = new HashMap<String, String>();

这个在你的doneButtonHandler()方法中

ArrayList<HashMap<String, String>> listItems = new ArrayList<HashMap<String, String>>();

在你的adapter

SimpleAdapter adapter = new SimpleAdapter(this, listItems ,R.layout.list_item,
            new String[]{"First Line", "Second Line"},
            new int[]{R.id.textUp, R.id.text2});

那么listItems这里有什么?如果associatedItem没有项目。

还要确保这在您看来是膨胀的

 list = findViewById(R.id.list);

并检查您的第 134 行AddGoal.java并放置调试器,这将帮助您找到问题。

根据您更新的视图,问题出 list = findViewById(R.id.list);在您的活动中未膨胀,因此list引发为适配器设置的空对象引用错误list.setAdapter(adapter)。唯一的解决方案是更改您的实现方法,以编程方式扩展另一个视图或修改您的布局以在您的活动布局中使用列表视图。


推荐阅读