简体   繁体   中英

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:

<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:

<?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:

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.

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 .

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
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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