【问题标题】:Ordering data in a list view在列表视图中排序数据
【发布时间】:2020-07-12 10:33:49
【问题描述】:

我尝试从 ListView 上的 Firebase 数据库中检索数据,但数据没有显示在顶部,而不是数据库中的第一个数据。

this is from firebase

this is a screenshot from the app

我希望应用在列表顶部显示最新的文本。这是我使用的代码,

        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ArrayAdapter<String> myAdapter= new ArrayAdapter<String>
                (MainActivity.this,android.R.layout.simple_list_item_1,myArray);

        mListView = (ListView)findViewById(R.id.listView);
        mListView.setAdapter(myAdapter);
        mListView.animate();
        mRef= FirebaseDatabase.getInstance().getReference();
        mRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            String value=dataSnapshot.getValue(String.class);
            myArray.add( "- "+ value);
            myAdapter.notifyDataSetChanged();
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                myAdapter.notifyDataSetChanged();
            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }
}

【问题讨论】:

    标签: java android listview arraylist


    【解决方案1】:

    我怀疑myArrayList,而不是顾名思义的实际数组。话虽这么说,一个快速的解决方案是颠倒该列表的顺序。你可以使用Collections.reverse()

    @Override
    public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
     String value=dataSnapshot.getValue(String.class);
     int index = Integer.parseInt(dataSnapshot.getKey());
     myArray.add(index,"- "+ value);
     // Reverse the order of that list
     Collections.reverse(myArray);
     myAdapter.notifyDataSetChanged();
    }
    

    【讨论】:

    • 您是否意识到,每次从 firebase 向列表中添加一个新孩子时,您都在反转 mArray?
    • 当然,这就是我添加快速解决方案的原因。我从来没有说对的。从看起来这家伙只是想测试 firebase 数据库是如何工作的。
    【解决方案2】:

    尝试将 android:stackFromBottom="false" 添加到 Xml 文件中的 ListView

    【讨论】:

      【解决方案3】:

      只需替换这一行 - myArray.add( "- "+ value); 与此行 - myArray.add(0, "- "+ value);。这将使您的项目被添加到您的数组列表的顶部位置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多