我试图添加一个"搜索用户"活动到一个简单的应用程序,我试图做。但是我无法接收用户输入(来自SearchView)并使用它来查询Firebase数据库,最终在Listview中显示所有内容(使用FirebaseListAdapter)。
问题主要在于Firebase部分,我无法理解。这是代码:
SearchView userSearchView;
ListView userListView;
SearchUserListAdapter UserAdapter;
String currentUserName;
String currentEnteredQuery = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_user);
userSearchView = (SearchView) findViewById(R.id.user_searchview);
userListView = ( ListView) findViewById(R.id.listview_search);
final Intent startConversation = new Intent(this,ConversationActivity.class);
//Start a new conversation
userListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(startConversation);
}
});
Query query = UserDbRef.orderByChild(currentEnteredQuery);
final FirebaseListAdapter firebaseListAdapter = new FirebaseListAdapter<UserItem>(this, UserItem.class, R.layout.user_item, query) {
@Override
protected void populateView(View v, UserItem userItem) {
((TextView)v.findViewById(android.R.id.text1)).setText(userItem.getUser_name());
}
};
userListView.setAdapter(firebaseListAdapter);
userSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String inputQuery) {
currentEnteredQuery = inputQuery;
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_search_user, menu);
return true;
}
答案 0 :(得分:0)
将您的查询放入SearchView的Listener中,以便每次使用特定条件进行搜索时都会查询:
userSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String inputQuery) {
currentEnteredQuery = inputQuery;
//Your Firebase Query here
Query query = UserDbRef.orderByChild(currentEnteredQuery);
final FirebaseListAdapter firebaseListAdapter = new FirebaseListAdapter<UserItem>(this, UserItem.class, R.layout.user_item, query) {
@Override
protected void populateView(View v, UserItem userItem) {
((TextView)v.findViewById(android.R.id.text1)).setText(userItem.getUser_name());
}
};
userListView.setAdapter(firebaseListAdapter);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
同样在这些方面:
final FirebaseListAdapter firebaseListAdapter = new FirebaseListAdapter<UserItem>(this, UserItem.class, R.layout.user_item, query) {
@Override
protected void populateView(View v, UserItem userItem) {
((TextView)v.findViewById(android.R.id.text1)).setText(userItem.getUser_name());
}
};
您使用 R.layout.user_item 作为列表的布局,但您使用的是 android.R.id.text1 。据我所知, android.R 是Android SDK中内置的资源。如果您使用 android.R.layout.simple_list_item_1 ,我认为这是视图。继续检查 R.layout.user_item ,然后将ID更改为布局中的相应视图。