【问题标题】:How to write Firebase query to filter out data?如何编写 Firebase 查询来过滤数据?
【发布时间】:2017-04-13 21:14:39
【问题描述】:

我想编写一个查询,以便使用编辑文本过滤数据,下面的代码确实有效,但会带来所有不需要的搜索数据。你能帮我么? JSON对象如下:我要过滤掉的数据是用户名

public class SearchActivity extends AppCompatActivity {

ListView searchList;
DatabaseReference databaseReference;
FirebaseListAdapter<SearchDetails> listAdapter;
String search;
EditText editTextSearch;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);

    searchList = (ListView) findViewById(R.id.listViewSearch);
    databaseReference = FirebaseDatabase.getInstance().getReference().child("Search Users");

    editTextSearch = (EditText) findViewById(R.id.editTextSearch);


    editTextSearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            search = editTextSearch.getText().toString();
            if (search.equals("")){
                searchList.setAdapter(null);
            }else{
                searchList.setAdapter(listAdapter);
            }
        }
    });

    Query query = databaseReference.startAt(search).endAt(search+"~").limitToFirst(10);
    listAdapter = new FirebaseListAdapter<SearchDetails>(
            this,
            SearchDetails.class,
            R.layout.search_layout,
            query
    ) {
        @Override
        protected void populateView(View v, SearchDetails model, int position) {
            TextView username = (TextView) v.findViewById(R.id.textViewUsername);
            username.setText(model.getUsername());
            TextView name = (TextView) v.findViewById(R.id.textViewName);
            name.setText(model.getName());
        }
    };

}
}

【问题讨论】:

  • 您能具体说明一下,您要获取哪些数据?这个问题对我来说不是很清楚。
  • 我想只过滤掉用户名
  • 嘿@Jama 我在下面为您添加了答案,如果这有帮助和/或您想了解更多信息,请告诉我。

标签: android firebase firebase-realtime-database firebaseui


【解决方案1】:

为了解决这个问题,我们需要了解一些关于 Firebase 的事情,很多开发人员可能会忽略这些事情。

  • 它是基于 NoSQL 的数据存储,因此您必须相应地构建数据。
  • Firebase 允许您将节点嵌套到数据结构中,深度最多可达 32 级,这很容易被滥用

我认为您手头的问题是“拥有一个EditText,允许用户搜索您的用户用户名

我建议你解决这个问题的方法是像这样扁平化你的数据结构

您可以在 usernames 数组中包含对象。每个对象的键是username,值是另一个带有empty-key : "" 的对象,就像这样。

然后您可以拥有另一个 users 数组,其中的键又是 usernames,其余数据作为对象存在于其下。

现在您可以轻松地在 usernames 上运行您的过滤查询,而不必担心在该查询中获取不必要的数据的开销。

一旦您知道选择了哪个username,您就可以查询users 以从数组中获取准确的user

【讨论】:

    【解决方案2】:

    Query query = databaseReference.orderByChild("username").startAt(search).endAt(search+"~").limitToFirst(10);

    【讨论】:

    • 很抱歉,它没有用,它带来了所有不需要的数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    相关资源
    最近更新 更多