为什么在安卓的 ListFragment 中使用 adapter.add 会导致崩溃?

huangapple 未分类评论49阅读模式
英文:

Why does adapter.add crash in android ListFragment

问题

我现在开始学习Android编程但在一个ListFragment中遇到了问题我在网上找到了一些关于相同问题的帖子但是没有一个能够帮助我找到/理解我代码中的问题

我创建了一个Android底部导航活动并修改了仪表板Fragment目标是在列表中有一个按钮当按钮被点击时应该打开键盘然后输入一个新的字符串并将其添加到列表中在以下代码中我尝试实现一个按钮当点击它时总是添加相同的字符串因为我还在学习阶段稍后会处理键盘部分

代码总是能够编译通过但当点击按钮并执行adapter.add命令时应用程序会崩溃当我在onCreateView中的setListAdapter之后直接添加adapter.add时也会崩溃

以下是我使用的文件

DashboardFragment.java

package com.example.aktiehq.workout.ui.dashboard;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;

import androidx.fragment.app.ListFragment;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.aktiehq.workout.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

public class DashboardFragment extends ListFragment {

    String[] values = new String[] { "Message1", "Message2", "Message3" };
    public ArrayAdapter<String> adapter;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_dashboard, container,
                false);

        adapter = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);

        FloatingActionButton button = rootView.findViewById(R.id.addListElement);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter.add("test");
                adapter.notifyDataSetChanged();
            }
        });

        return rootView;
    }
}

fragment_dashboard.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".ui.dashboard.DashboardFragment">

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/addListElement"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="64dp"
        android:clickable="true"
        android:src="@android:drawable/ic_input_add"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <ListView
        android:id="@android:id/list"
        android:layout_width="409dp"
        android:layout_height="609dp"
        tools:layout_editor_absoluteX="1dp"
        tools:layout_editor_absoluteY="1dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

点击按钮后的错误信息:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.aktiehq.workout, PID: 18355
    java.lang.UnsupportedOperationException
        at java.util.AbstractList.add(AbstractList.java:404)
        at java.util.AbstractList.add(AbstractList.java:425)
        at android.widget.ArrayAdapter.add(ArrayAdapter.java:194)
        at com.example.aktiehq.workout.ui.dashboard.DashboardFragment$1.onClick(DashboardFragment.java:45)
        at android.view.View.performClick(View.java:5198)
        at android.view.View$PerformClick.run(View.java:21147)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

请问有人可以帮助我解释和修复这个问题吗?

非常感谢您的帮助,

Frank


<details>
<summary>英文:</summary>

I am starting to learn coding for android now and have a Problem in a ListFragment. I found threads with the same problem but none of them helped be finding / understanding the problem in my code.

I created an Android bottom navigation activity and modified the Dashboard Fragment. The Goal is to have a list with a button and when it is clicked a keyboard should open, a new string be entered and added to the list. In the following code I tried to implement a button that adds always the same string when it is clicked since I am still learning, I will work on the keyboard part later.

The code always compiles without problem but crashes when the button is clicked and the adapter.add command is executed. It also crashes when I add the adapter.add directly after the setListAdapter in onCreateView.

These are the files I use:

DashboardFragment.java

    package com.example.aktiehq.workout.ui.dashboard;
    
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.TextView;
    
    import androidx.fragment.app.ListFragment;
    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    import androidx.fragment.app.Fragment;
    import androidx.lifecycle.Observer;
    import androidx.lifecycle.ViewModelProviders;
    
    import com.example.aktiehq.workout.R;
    import com.google.android.material.floatingactionbutton.FloatingActionButton;
    
    public class DashboardFragment extends ListFragment {
    
        //private DashboardViewModel dashboardViewModel;
        String[] values = new String[] { &quot;Message1&quot;, &quot;Message2&quot;, &quot;Message3&quot; };
        public ArrayAdapter&lt;String&gt; adapter;
    
        public View onCreateView(@NonNull LayoutInflater inflater,
                                 ViewGroup container, Bundle savedInstanceState) {
    
                View rootView = inflater.inflate(R.layout.fragment_dashboard, container,
                        false);
    
    
                adapter = new ArrayAdapter&lt;String&gt;(getActivity(),
                        android.R.layout.simple_list_item_1, values);
                setListAdapter(adapter);
    
                FloatingActionButton button = (FloatingActionButton) rootView.findViewById(R.id.addListElement);
                //b.setOnClickListener((View.OnClickListener) this);
                button.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        adapter.add(&quot;test&quot;);
                        adapter.notifyDataSetChanged();
                    }
                });
            return rootView;
    
        }
    
    }

fragment_dashboard.xml

    &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
    &lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
        xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
        xmlns:tools=&quot;http://schemas.android.com/tools&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        tools:context=&quot;.ui.dashboard.DashboardFragment&quot;&gt;
    
        &lt;com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id=&quot;@+id/addListElement&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_marginEnd=&quot;16dp&quot;
            android:layout_marginBottom=&quot;64dp&quot;
            android:clickable=&quot;true&quot;
            android:src=&quot;@android:drawable/ic_input_add&quot;
            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
            app:layout_constraintEnd_toEndOf=&quot;parent&quot; /&gt;
    
        &lt;ListView
            android:id=&quot;@android:id/list&quot;
            android:layout_width=&quot;409dp&quot;
            android:layout_height=&quot;609dp&quot;
            tools:layout_editor_absoluteX=&quot;1dp&quot;
            tools:layout_editor_absoluteY=&quot;1dp&quot; /&gt;
    
    &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

Error when I click the button:

    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.example.aktiehq.workout, PID: 18355
        java.lang.UnsupportedOperationException
            at java.util.AbstractList.add(AbstractList.java:404)
            at java.util.AbstractList.add(AbstractList.java:425)
            at android.widget.ArrayAdapter.add(ArrayAdapter.java:194)
            at com.example.aktiehq.workout.ui.dashboard.DashboardFragment$1.onClick(DashboardFragment.java:45)
            at android.view.View.performClick(View.java:5198)
            at android.view.View$PerformClick.run(View.java:21147)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Can anyone please help me explaining and fixing the problem?

Thank you very much in advance,

Frank

</details>


huangapple
  • 本文由 发表于 2020年5月2日 14:42:58
  • 转载请务必保留本文链接:https://java.coder-hub.com/61555472.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定