当我点击自动填充建议项目时,我正在尝试获取firebase数据库值。下面的代码是我试图实现它的方式。但是,我似乎在这一行上收到java.lang.String cannot be cast to SearchInformation
错误:
sInfo = (SearchInformation) adapterView.getAdapter().getItem(i);
我正在关注this示例中的第一个答案。
注意:我不知道这是否是使用自动完成功能从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;
}
}
答案 0 :(得分:1)
您需要将SELECT
user.*
FROM
user
WHERE
op_id IN (
SELECT
user.op_id AS op_id
FROM
user
WHERE
last_login_on IS NOT NULL
GROUP BY op_id
HAVING SUM(IF(DATE(last_login_on) > DATE(DATE_SUB(NOW(), INTERVAL 31 DAY)),
1,
0)) = 0
ORDER BY op_id ASC
)
AND role_type = 'owner'
更改为自定义适配器ArrayAdapter<String>
。然后使用ArrayAdapter<SearchInformation>
,您可以使用autoComplete.add(sInfo)
SearchInformation
的整个对象
答案 1 :(得分:0)
那是因为它是ArrayAdapter<String>
,其中有字符串。因此,您的getItem()
也会为您提供字符串。