selected item on spinner won't work (ANDROID)

房东的猫 提交于 2020-01-15 09:28:08

问题


My data comes from Firebase database. I successfully populated the busNumto the spinner. But my problem is whenever I got to select the busnum, nothing shows up on my spinner. Here are some of codes. List<String> busnum = new ArrayList<String>();

busRef =  new Firebase(Config.FIREBASE_URL_BUSNUMBER);
    busRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                busnum.add(postSnapshot.child("busNum").getValue().toString());
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            Toast.makeText(AddDriverActivity.this, "Failed to read data.... " +firebaseError.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, busnum);
    mSpinBusNum.setPrompt("Select bus number");
    mSpinBusNum.setAdapter(adapter);

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    busNum = parent.getItemAtPosition(position).toString();
}

回答1:


You must set Adapter after on datachange like this:

//after onDataChange 
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, busnum);
mSpinBusNum.setPrompt("Select bus number");
// Apply the adapter to the spinner
mSpinBusNum.setAdapter(adapter);        



回答2:


ArrayList<String> issueCategoryArrayList = new ArrayList<String>();
FirebaseDatabase.getInstance().getReference("issue_categories").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
            issueCategoryArrayList.add(dataSnapshot1.getValue(IssueCategory.class).getTitle());
        }
        spinner = findViewById(R.id.post_category);
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(PostActivity.this,
                android.R.layout.simple_spinner_item, issueCategoryArrayList);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(dataAdapter);;
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});


来源:https://stackoverflow.com/questions/39234482/selected-item-on-spinner-wont-work-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!