我想使用Firebase中的数据填充微调器而不是ListView。 下面的代码适用于ListView。但是如何用微调器替换ListView呢?希望有人能帮助我。
我的研究: Firebase data to Spinner
Populatate the spinner from Firebase database
这是我的主要活动:
public class Ansattliste extends AppCompatActivity {
DatabaseReference databaseAnsatt;
ListView lvansattliste;
Button btnleggtilansatt;
List<Ansatt> listansatt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ansattliste);
databaseAnsatt = FirebaseDatabase.getInstance().getReference("Ansatte");
lvansattliste = (ListView)findViewById(R.id.lvansattliste);
listansatt = new ArrayList<>();
btnleggtilansatt = (Button)findViewById(R.id.btnleggtilansatt);
btnleggtilansatt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent leggtil = new Intent(Ansattliste.this, Leggtilansatt.class);
startActivity(leggtil);
}
});
}
@Override
protected void onStart() {
super.onStart();
databaseAnsatt.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
listansatt.clear();
for (DataSnapshot ansattSnapshot : dataSnapshot.getChildren()) {
final Ansatt ansatt = ansattSnapshot.getValue(Ansatt.class);
listansatt.add(ansatt);
final listAnsatt adapter = new listAnsatt(Ansattliste.this, listansatt);
lvansattliste.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
@Override
public void onCancelled (DatabaseError databaseError){
}
});
}
}
我的适配器:
public class listAnsatt extends ArrayAdapter<Ansatt> {
private Activity context;
private List<Ansatt> listansatt;
public listAnsatt(Activity context, List<Ansatt> listansatt) {
super(context, R.layout.list_ansatt, listansatt);
this.context = context;
this.listansatt = listansatt;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_ansatt, null, true);
TextView tvansattnavn = (TextView) listViewItem.findViewById(R.id.tvansattnavn);
TextView tvansaattnr = (TextView) listViewItem.findViewById(R.id.tvansattnr);
Ansatt ansatt = listansatt.get(position);
tvansattnavn.setText(ansatt.getAnsattnavn());
tvansaattnr.setText(ansatt.getAnsattnr());
return listViewItem;
}
火力地堡: Firebase
答案 0 :(得分:0)
你做了类似跟随的事情(我已经改编自我在这里的Kotlin代码,因此可能会出现一些语法错误)......假设你有getAnsattnavn()
是你想要的价值在旋转器中显示。您仍然拥有listansatt
,大概是您在微调器中选择项目时会查找。
在onDataChange
:
List<String> optionList = new ArrayList<>();
for (DataSnapshot ansattSnapshot : dataSnapshot.getChildren()) {
final Ansatt ansatt = ansattSnapshot.getValue(Ansatt.class);
optionList.add(ansatt.getAnsattnavn());
listansatt.add(ansatt);
}
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, optionList);
spinnerControl.setAdapter(adapter);