【问题标题】:Listview shows only first result from array listListview 仅显示数组列表的第一个结果
【发布时间】:2019-12-22 16:13:18
【问题描述】:

我有下面的代码,它显示了数组列表的结果,但是,它只显示了测试结果,我将相同的结果附加到文本视图进行测试,发现我从查询方法得到的结果确实包含不止一个,它们出现在文本视图中,但列表视图只显示第一个。 请在下面找到代码以及所附图片。

//searchactivity.class//

package com.example.boc.search;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.boc.Interface.IMainActivity;
import com.example.boc.R;
import com.example.boc.main.phone_nombers_Activity;
import com.example.boc.models.Note;
import com.example.boc.models.Search;
import com.google.android.gms.tasks.OnCompleteListener;

import android.widget.ArrayAdapter;

import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;

import java.util.ArrayList;

public class searchActivity extends phone_nombers_Activity implements
        View.OnClickListener,
        IMainActivity
{

    private DocumentSnapshot documentSnapshot;
    ListView listView;
    public TextView resultTxt , userinput ;
    private ArrayList<Search> mSearch = new ArrayList<>();


    public FirebaseFirestore db = FirebaseFirestore.getInstance();
    public Note note ;
    public LinearLayout layout ;

    private ArrayList<Note> mNotes = new ArrayList<>();

    private DocumentReference noteRef = db.collection("notes").document();
    private CollectionReference notesCollectionRef = db.collection("notes");
    private RecyclerView mRecyclerView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_search );
        final ListView listView = findViewById( R.id.listview4 );
        final EditText userinput = findViewById( R.id.userInputtxt );
        final Button   findbutton = findViewById( R.id.findBtn );
        final TextView resultTxt = findViewById( R.id.resultTxt );
        mRecyclerView = findViewById(R.id.recycler_view);





        FirebaseFirestore db = FirebaseFirestore.getInstance();

        CollectionReference notesCollectionRef = db
                .collection("notes");

        Query notesQuery = null;
        if(documentSnapshot != null){
            notesQuery = notesCollectionRef;

        }
        else{
            notesQuery = notesCollectionRef
                    .orderBy("timestamp", Query.Direction.ASCENDING);
        }


        notesQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if(task.isSuccessful()){
                    String data = "";

                    for(final QueryDocumentSnapshot document: task.getResult()){
                        Note note = document.toObject(Note.class);

                        mNotes.add(note);
                        if( userinput !=null ) {
                            findbutton.setOnClickListener( new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    final String userinputString = userinput.getText().toString();

                                    Note match = null;
                                    String matcheddata ="";
                                    for (Note note : mNotes) {
                                        if (note.getTitle().contains(userinputString)) {
                                            match = note;
                                            String matchedtitle = match.getTitle();
                                            String matchedcontent = match.getContent();
                                            matcheddata += "هاتف:" + matchedcontent + "\nالاسم:" + matchedtitle + "\n\n";


                                    }
                                    if (match != null) {
                                         ArrayList<String> namesList = new ArrayList<>();
                                        resultTxt.setText( matcheddata );
                                        namesList.clear();
                                        ArrayAdapter<String>adapter = new ArrayAdapter<>( getApplicationContext(), android.R.layout.simple_selectable_list_item, namesList );
                                        adapter.notifyDataSetChanged();
                                        listView.setAdapter(adapter);
                                        namesList.add(matcheddata);





                                        // Found a match








                                        //previewResultTextview.setOnClickListener( new View.OnClickListener() {
                                         //   @Override
                                          //  public void onClick(View v) {
                                           //     String content = previewResultTextview.getText().toString();
                                            //    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", contenttoparse, null));
                                            //    startActivity(intent);

                                          //  }
                                       // } );


                                    }





                                    }
                                }

                            } );


                        }
                        else {
                            userinput.setError( "اسم الملف مطلوب" );

                        }





                    }
                }
            }
        });


    }




    @Override
    public void onStart () {

        super.onStart();

    }
}

//searchactivity.xml//

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".search.searchActivity">

    <EditText
        android:id="@+id/userInputtxt2"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_marginStart="8dp"
        android:paddingTop="50dp"
        android:textColor="@color/Black"
        android:textSize="18sp" />

    <EditText
        android:id="@+id/userInputtxt"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_marginStart="8dp"
        android:paddingTop="50dp"
        android:textColor="@color/Black"
        android:textSize="18sp" />

    <Button
        android:id="@+id/findBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="320dp"
        android:layout_marginEnd="3dp"
        android:text="find"
        android:textSize="10sp" />

    <ListView
        android:id="@+id/listview4"
        android:layout_width="398dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="55dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp">
    </ListView>

    <TextView
        android:id="@+id/resultTxt"
        android:layout_width="match_parent"
        android:layout_height="203dp"
        android:layout_marginTop="450dp"

        android:background="@color/transparentGrey"
        android:text="TextView" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

【问题讨论】:

    标签: java android-studio listview arraylist


    【解决方案1】:

    我认为是适配器通知问题。

    • 您正在向适配器提供 0 大小列表,并立即通知适配器。

    • 我认为添加到列表后应该通知适配器。 您可以在调用适配器类之前将数据添加到列表中。

    示例

    notesQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if(task.isSuccessful()){
                    String data = "";
    
                    for(final QueryDocumentSnapshot document: task.getResult()){
                        Note note = document.toObject(Note.class);
    
                        mNotes.add(note);
                        if( userinput !=null ) {
                            findbutton.setOnClickListener( new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    final String userinputString = userinput.getText().toString();
    
                                    Note match = null;
                                    String matcheddata ="";
                                    for (Note note : mNotes) {
                                        if (note.getTitle().contains(userinputString)) {
                                            match = note;
                                            String matchedtitle = match.getTitle();
                                            String matchedcontent = match.getContent();
                                            matcheddata += "هاتف:" + matchedcontent + "\nالاسم:" + matchedtitle + "\n\n";
                                        }
                                    }
                                    if (match != null) {
                                        ArrayList<String> namesList = new ArrayList<>();
                                        resultTxt.setText( matcheddata );
                                        namesList.clear();
                                        namesList.add(matcheddata);
                                        ArrayAdapter<String>adapter = new ArrayAdapter<>( getApplicationContext(), android.R.layout.simple_selectable_list_item, namesList );
                                        listView.setAdapter(adapter);
                                    }
                                }
                            } );
                        }
                        else {
                            userinput.setError( "اسم الملف مطلوب" );
                        }
                    }
                }
            }
        });
    
    • 只需更改上述功能并尝试。

    【讨论】:

    • 感谢您的重播,我尝试了您的建议,但没有奏效,仍然只在列表视图中显示一个结果,而在 textview 端显示所有结果。
    • 哎呀,这是一个很大的错误。我认为它将在列表视图中显示最后一个结果。只需检查一下。
    【解决方案2】:
    if (match != null) {
        ArrayList<String> namesList = new ArrayList<>();
        resultTxt.setText( matcheddata );
        // namesList.clear(); // You don't need to clear it as you just created it above
        namesList.add(matcheddata);
        ArrayAdapter<String> adapter = new ArrayAdapter<>( getApplicationContext(), android.R.layout.simple_selectable_list_item, namesList );
        listView.setAdapter(adapter);
    }
    

    您好 Amer Anajjem,您能否尝试在创建适配器之前准备 namesList 并使用最新的 namesList 来创建适配器。

    编辑:

    我发现问题是:matcheddata是一个字符串。当您致电namesList.add(matcheddata); 时,您只在列表中添加了一项。结果,您在列表视图中只有 1 个项目。为了证明这一点,您可以尝试以下方法:

    if (match != null) {
        ArrayList<String> namesList = new ArrayList<>();
        resultTxt.setText( matcheddata );
        namesList.clear();
        namesList.add(matcheddata);
        namesList.add(matcheddata);
        ArrayAdapter<String> adapter = new ArrayAdapter<>( getApplicationContext(), android.R.layout.simple_selectable_list_item, namesList );
        listView.setAdapter(adapter);
    }
    

    您应该在列表视图中看到 2 个重复项。

    编辑 2:

    你可以试试这个,但我没有测试。

    package com.example.boc.search;
    
    import androidx.annotation.NonNull;
    import androidx.recyclerview.widget.RecyclerView;
    
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.LinearLayout;
    import android.widget.ListView;
    import android.widget.TextView;
    
    import com.example.boc.Interface.IMainActivity;
    import com.example.boc.R;
    import com.example.boc.main.phone_nombers_Activity;
    import com.example.boc.models.Note;
    import com.example.boc.models.Search;
    import com.google.android.gms.tasks.OnCompleteListener;
    
    import android.widget.ArrayAdapter;
    
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.firestore.CollectionReference;
    import com.google.firebase.firestore.DocumentReference;
    import com.google.firebase.firestore.DocumentSnapshot;
    import com.google.firebase.firestore.FirebaseFirestore;
    import com.google.firebase.firestore.Query;
    import com.google.firebase.firestore.QueryDocumentSnapshot;
    import com.google.firebase.firestore.QuerySnapshot;
    
    import java.util.ArrayList;
    
    public class searchActivity extends phone_nombers_Activity implements
            View.OnClickListener,
            IMainActivity
    {
    
        private DocumentSnapshot documentSnapshot;
        ListView listView;
        public TextView resultTxt , userinput ;
        private ArrayList<Search> mSearch = new ArrayList<>();
    
    
        public FirebaseFirestore db = FirebaseFirestore.getInstance();
        public Note note ;
        public LinearLayout layout ;
    
        private ArrayList<Note> mNotes = new ArrayList<>();
    
        private DocumentReference noteRef = db.collection("notes").document();
        private CollectionReference notesCollectionRef = db.collection("notes");
        private RecyclerView mRecyclerView;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate( savedInstanceState );
            setContentView( R.layout.activity_search );
            final ListView listView = findViewById( R.id.listview4 );
            final EditText userinput = findViewById( R.id.userInputtxt );
            final Button   findbutton = findViewById( R.id.findBtn );
            final TextView resultTxt = findViewById( R.id.resultTxt );
            mRecyclerView = findViewById(R.id.recycler_view);
    
            FirebaseFirestore db = FirebaseFirestore.getInstance();
    
            CollectionReference notesCollectionRef = db
                    .collection("notes");
    
            Query notesQuery = null;
            if(documentSnapshot != null){
                notesQuery = notesCollectionRef;
    
            }
            else{
                notesQuery = notesCollectionRef
                        .orderBy("timestamp", Query.Direction.ASCENDING);
            }
    
    
            notesQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if(task.isSuccessful()){
                        String data = "";
    
                        for(final QueryDocumentSnapshot document: task.getResult()){
                            Note note = document.toObject(Note.class);
    
                            mNotes.add(note);
                            if( userinput !=null ) {
                                findbutton.setOnClickListener( new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        final String userinputString = userinput.getText().toString();
    
                                        ArrayList<String> namesList = new ArrayList<>();
                                        for (Note note : mNotes) {
                                            if (note.getTitle().contains(userinputString)) {
                                                String matchedtitle = note.getTitle();
                                                String matchedcontent = note.getContent();
                                                String matcheddata += "هاتف:" + matchedcontent + "\nالاسم:" + matchedtitle + "\n\n";
                                                namesList.add(matcheddata);
                                        }
    
                                        ArrayAdapter<String> adapter = new ArrayAdapter<>( getApplicationContext(), android.R.layout.simple_selectable_list_item, namesList );
                                        listView.setAdapter(adapter);
                                    }
    
                                } );
                            }
                            else {
                                userinput.setError( "اسم الملف مطلوب" );
                            }
                        }
                    }
                }
            });
        }
    
        @Override
        public void onStart () {
    
            super.onStart();
    
        }
    }
    

    【讨论】:

    • 谢谢@Ken Li,我昨天也在做同样的想法,我的想法和我发现我正在向适配器添加一个字符串然后将其转换为列表一样,而我需要添加一个数组将列表添加到适配器然后将其转换为列表,无论如何,您的回答对识别问题有很大帮助,如果您可以发布一种方法使(匹配)的结果出现在列表视图中,我会将其标记为正确答案。
    • 长话短说,它的作品! ,我有一个问题,为什么当我们使用 match=note 时它不起作用?
    • 即使有match = note,它仍然可以工作,但在这种情况下,拥有一个包含note 对象的变量是多余的。在我的代码中,我只是直接使用块中的note 对象来完成所有的事情。
    • 在您的原始代码中,您只有两个问题:1. 您应该在创建/更新适配器之前准备数据列表 2. 您应该将每个字符串项添加到列表中,而不是附加所有他们到一个单一的字符串。希望对您有所帮助。
    猜你喜欢
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    相关资源
    最近更新 更多