我正在尝试使用简单的搜索栏(EditText)并单击按钮以显示特定用户时,按用户名搜索存储在我的Firebase数据库中的用户
我的findfriends.java文件中包含以下代码
public class FindFriendsActivity extends AppCompatActivity {
private EditText seachTextBox;
private ImageView searchImage;
private RecyclerView searchResultList;
private DatabaseReference allUsersDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_friends);
searchResultList = findViewById(R.id.search_result_list);
searchResultList.setHasFixedSize(true);
searchResultList.setLayoutManager(new LinearLayoutManager(this));
allUsersDatabase = FirebaseDatabase.getInstance().getReference().child("users");
seachTextBox = findViewById(R.id.searchBox);
searchImage = findViewById(R.id.searchImage);
searchImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String seachbox = seachTextBox.getText().toString();
final Query searchpeople = allUsersDatabase.orderByChild("username").startAt(seachbox)
.endAt(seachbox + "\uf8ff");
}
});
}
@Override
protected void onStart()
{
super.onStart();
FirebaseRecyclerOptions<FindFriends> options =
new FirebaseRecyclerOptions.Builder<FindFriends>()
.setQuery(allUsersDatabase, FindFriends.class)
.build();
FirebaseRecyclerAdapter<FindFriends, FindFriendsHolder> adapter =
new FirebaseRecyclerAdapter<FindFriends, FindFriendsHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull FindFriendsHolder holder, int position, @NonNull FindFriends model)
{
holder.username.setText(model.getUsername());
holder.fullname.setText(model.getFullname());
Picasso.get().load(model.getProfileimage()).placeholder(R.drawable.friends_result_icon).fit().into(holder.userimage);
}
@NonNull
@Override
public FindFriendsHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i)
{
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.search_friends_result_layout,viewGroup,false);
FindFriendsHolder viewHolder = new FindFriendsHolder(view);
return viewHolder;
}
};
searchResultList.setAdapter(adapter);
adapter.startListening();
}
public static class FindFriendsHolder extends RecyclerView.ViewHolder
{
TextView username, fullname;
ImageView userimage;
public FindFriendsHolder(@NonNull View itemView)
{
super(itemView);
username = itemView.findViewById(R.id.username_result);
fullname = itemView.findViewById(R.id.fullname_result);
userimage = itemView.findViewById(R.id.friend_result_image);
}
}
}///end
我已经进行了一些研究,发现我需要创建一个查询并将其设置为Startat(Edittext).endAt(EditText),但是我不确定在哪里实际插入查询。
使用以下代码,我可以显示数据库中的每个用户。
任何帮助都会很棒!
答案 0 :(得分:2)
根据您的评论,您现在正在吸引所有用户。如果您只想获得一个用户,请更改以下代码行:
Query searchpeople = allUsersDatabase.orderByChild("username").startAt(seachbox)
.endAt(seachbox + "\uf8ff");
到
Query searchpeople = allUsersDatabase.orderByChild("username").equalTo(seachbox);
答案 1 :(得分:0)
如果您想简化它,可以使用 Firestore 代替实时数据库。但是,如果您仍然想使用RealtimeDB,则可以创建条件循环,例如:
if(edtUsername.text.toString == username){
// Your code
}