当我单击自动完成建议的项目时,我正在尝试获取firebase数据库值。下面的代码是我尝试实施它的方式。但是,我似乎在此行上遇到了java.lang.String cannot be cast to SearchInformation
错误:
sInfo = (SearchInformation) adapterView.getAdapter().getItem(i);
我遵循此示例的第一个答案。
注意:我不知道这是否是使用AutoComplete从Firebase数据库中检索信息的正确方法,但是要找出答案,我需要先解决此信息。
代码:
public class Hot extends Fragment {
private SearchInformation sInfo;
private DatabaseReference database;
public Hot() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_hot, container, false);
database = FirebaseDatabase.getInstance().getReference();
final ArrayAdapter<String> autoComplete = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1);
database.child("AutoCompleteOptions").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot suggestionSnapshot : dataSnapshot.getChildren()){
sInfo = suggestionSnapshot.getValue(SearchInformation.class);
autoComplete.add(sInfo.getEatery_name());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
AutoCompleteTextView ACTV= rootView.findViewById(R.id.actv);
ACTV.setAdapter(autoComplete);
ACTV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
sInfo = (SearchInformation) adapterView.getAdapter().getItem(i); // ** ERROR HERE **
String anID = sInfo.getEatery_id();
Log.i("ID is", anID);
}
});
return rootView;
}
}
数据模型:
public class SearchInformation {
private String eatery_name;
private String eatery_id;
public SearchInformation() {
}
public SearchInformation(String eatery_name, String eatery_id) {
this.eatery_name = eatery_name;
this.eatery_id = eatery_id;
}
public String getEatery_name() {
return eatery_name;
}
public void setEatery_name(String eatery_name) {
this.eatery_name = eatery_name;
}
public String getEatery_id() {
return eatery_id;
}
public void setEatery_id(String eatery_id) {
this.eatery_id = eatery_id;
}
}
您需要将ArrayAdapter<String>
更改为自定义适配器ArrayAdapter<SearchInformation>
。然后使用autoComplete.add(sInfo)
,您可以使用adapterView.getAdapter().getItem(i)
SearchInformation
的整个对象那是因为它是 ArrayAdapter<String>
,其中有字符串。因此,您的getItem()
也为您提供了一个字符串。