简体   繁体   English

从 ArrayAdapter 中的 firebase 数据库中获取数据无法正常工作

[英]Fetching data from firebase database in ArrayAdapter not working properly

I am fetching a name of countries from firebase and trying to show them in AutoCompleteTextView, the XML code given below:我正在从 firebase 获取国家名称并尝试在 AutoCompleteTextView 中显示它们,下面给出的 XML 代码:

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:text="Select Country"
    android:textColor="@color/black"
    android:textSize="18sp"
    android:textStyle="bold" />

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/TextInputLayoutStyles">
        <AutoCompleteTextView
            android:id="@+id/auto_complete_country"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="none"
            android:backgroundTint="@color/white"
            android:textColor="@color/black"
            android:text="Select"/>
    </com.google.android.material.textfield.TextInputLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

list_iten.xml is given below: list_iten.xml 如下:

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:padding="16dp"
    android:ellipsize="end"
    android:maxLines="1"
    android:textAppearance="?attr/textAppearanceSubtitle1">
</TextView>

Java code is given below: Java代码如下:

public class AddUniversityActivity extends AppCompatActivity {
    AutoCompleteTextView autoCompleteTextView;
    Context context;
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

       setContentView(R.layout.activity_add_university);
       autoCompleteTextView = findViewById(R.id.auto_complete_country);
       context = this;

       autoCompleteTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addCountries();
            }
        });
  }

      private void addCountries(){
            ArrayList<String> list = new ArrayList<>();
            ArrayAdapter<String> adapterItems = new ArrayAdapter<String>(this, R.layout.list_items, list);
            autoCompleteTextView.setAdapter(adapterItems);

            FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
            DatabaseReference databaseReference = firebaseDatabase.getReference();
            databaseReference.child("CountryList").child("CountryName");
            databaseReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    list.clear();
                    for (DataSnapshot snapshot1 : snapshot.getChildren()) {
                        if (snapshot1.exists()) {
                            String data = snapshot1.child("CountryName").getValue(String.class);
                            list.add(data);
                            if (data!=null){
                                Toast.makeText(context, "name", Toast.LENGTH_SHORT).show();
                            }
                            else {
                                Toast.makeText(context, "no name", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }
                @Override
                public void onCancelled(@NonNull DatabaseError error) {

                }
            });
        }
}

在此处输入图像描述

When I click on that AutoCompleteTextViwe it toasts 'no data' and sometimes shows only 1 item in it that is the latest inserted country in firebase.当我单击那个 AutoCompleteTextViwe 时,它显示“无数据”,有时只显示 1 个项目,即 firebase 中最新插入的国家/地区。

This line in your code does nothing:您代码中的这一行什么都不做:

databaseReference.child("CountryList").child("CountryName");

Only once you assign the result of this expression to a variable will you have a reference to a path in the database.只有将此表达式的结果分配给变量后,您才能引用数据库中的路径。 But even then it would point to nothing, as there is no data at CountryList/CountryName .但即便如此,它也不会指向任何内容,因为CountryList/CountryName中没有数据。

To load and show the country names from the database you showed in your question would be something like this:要从您在问题中显示的数据库中加载和显示国家/地区名称,如下所示:

FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = firebaseDatabase.getReference();
DatabaseReference listReference = databaseReference.child("CountryList");
listReference.addValueEventListener(new ValueEventListener() { // 👈 load list of countries
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        list.clear();
        for (DataSnapshot countrySnapshot: snapshot.getChildren()) {
            String data = countrySnapshot.child("CountryName").getValue(String.class);
            list.add(data);
        }
        adapter.notifyDataSetChanged(); // 👈 Tell the adapter that its data has changed
    }
    @Override
    public void onCancelled(@NonNull DatabaseError error) {
        throw error.toException(); // 👈 never ignore errorss
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM