我的数据库安排如下:
我想将学生的所有值作为字符串列表或任何形式的列表获取并使用它来填充Spinner
Tab2.java
package com.example.shikh.first;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Spinner;
import android.widget.TextView;
import com.firebase.ui.FirebaseListAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
public class practice extends AppCompatActivity {
// private Spinner Category, SubCategory;
DatabaseReference reference;
Spinner areaSpinner;
ArrayList<String> areas = new ArrayList<String>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab2);
reference = FirebaseDatabase.getInstance().getReferenceFromUrl("https://practice-2f7d1.firebaseio.com");
areaSpinner = (Spinner) findViewById(R.id.spinner);
DatabaseReference mref= reference.child("areas");
FirebaseListAdapter<String> firebaseListAdapter = new FirebaseListAdapter<String>(this, EventCategories.class, android.R.layout.simple_spinner_item, mref) {
@Override
protected void populateView(View view, String s) {
((TextView)view.findViewById(R.id.text1)).setText(s.getName());
}
};
areaSpinner.setAdapter(firebaseListAdapter);
}
}
更新了代码^
当我将EventCategories放在字符串的位置时,代码在populateView(View视图,EventCategories s)方法中显示错误。
答案 0 :(得分:0)
您可以使用FirebaseUi库,该库使用FirebaseListAdapter。 FirebaseListAdapter扩展了BaseAdapter,它实现了SpinnerAdapter接口。 所以大部分代码已经写好了......
答案 1 :(得分:0)
首先,您应该创建一个名为“Student”的课程
public class Student {
String name;
String courseName;
public Student(String name, String courseName) {
this.name = name;
this.courseName = courseName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("name", name);
result.put("courseName", courseName);
return result;
}
}
保存到数据库时,可以使用push()和updateChildren()方法获取此数据库结构。您可以查看文档here 现在来到FirebaseListAdapter
FirebaseListAdapter<Student> firebaseListAdapter = new FirebaseListAdapter<Student>(this, Student.class, android.R.layout.simple_spinner_item, reference) {
@Override
protected void populateView(View view, Student s) {
((TextView)view.findViewById(R.id.text1)).setText(s.getName());
}
};
以下是FirebaseRecyclerAdapter docs。