从Firebase获取特定价值

时间:2018-02-02 05:32:58

标签: java android firebase firebase-realtime-database

我有这个firebase数据库:

enter image description here

使用此代码创建:

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys


class Delegate(QStyledItemDelegate):
    def paint(self, painter, option, index):
        if not index.parent().isValid():
            QStyledItemDelegate.paint(self, painter, option, index)
        else:
            widget = option.widget
            style = widget.style() if widget else QApplication.style()
            opt = QStyleOptionButton()
            opt.rect = option.rect
            opt.text = index.data()
            opt.state |= QStyle.State_On if index.data(Qt.CheckStateRole) else QStyle.State_Off
            style.drawControl(QStyle.CE_RadioButton, opt, painter, widget)

    def editorEvent(self, event, model, option, index):
        value = QStyledItemDelegate.editorEvent(self, event, model, option, index)
        if value:
            if event.type() == QEvent.MouseButtonRelease:
                if index.data(Qt.CheckStateRole) == Qt.Checked:
                    parent = index.parent()
                    for i in range(model.rowCount(parent)):
                        if i != index.row():
                            ix = parent.child(i, 0)
                            model.setData(ix, Qt.Unchecked, Qt.CheckStateRole)

        return value


def main():
    app = QApplication(sys.argv)
    tree = QTreeWidget()
    tree.setItemDelegate(Delegate())

    for i in range(3):
        parent = QTreeWidgetItem(tree)
        parent.setText(0, "Parent {}".format(i))
        for x in range(5):
            child = QTreeWidgetItem(parent)
            child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
            child.setText(0, "Child {}".format(x))
            child.setCheckState(0, Qt.Unchecked)

    tree.expandAll()
    tree.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

它实际上是一个简单的应用程序,让用户注册一些数据。我想做的是我想创建一个private DatabaseReference mDatabase; private EditText tbfirstname; private EditText tblastname; private EditText tbemail; private Button btnSubmit; private String str_firstname; private String str_lastname; private String str_email; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mDatabase = FirebaseDatabase.getInstance().getReference().child("Users"); //GUI DECLARATIONS tbfirstname = (EditText) findViewById(R.id.tb_firstname); tblastname = (EditText) findViewById(R.id.tb_lastname); tbemail = (EditText) findViewById(R.id.tb_email); btnSubmit = (Button) findViewById(R.id.btn_register); btnSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //HANDLES VALUES FROM TB TO STR str_firstname = tbfirstname.getText().toString().trim(); str_lastname = tblastname.getText().toString().trim(); str_email = tbemail.getText().toString().trim(); HashMap<String, String> dataMap = new HashMap<String, String>(); dataMap.put("Firstname", str_firstname); dataMap.put("Lastname", str_lastname); dataMap.put("Email", str_email); mDatabase.push().setValue(dataMap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(MainActivity.this,"Registered Successfully!",Toast.LENGTH_LONG).show(); tbfirstname.setText(""); tblastname.setText(""); tbemail.setText(""); } else { Toast.makeText(MainActivity.this, "There was an Error. Try Again!", Toast.LENGTH_LONG).show(); } } }); } }); } ,它将根据用户在该文本框中输入的内容在数据库中查找特定数据并返回一个值。

例如,我搜索search textbox,如果数据库中有一个具有相同值的电子邮件,我希望它返回其根值steve@sample.com。如果以某种方式没有所述记录,我希望它以L4JyRA77YKldmMWM-C7或其他东西返回。

要求:我真的是Android和Firebase的初学者,所以如果你能使代码新手友好,这真的是一个很好的帮助。谢谢!

2 个答案:

答案 0 :(得分:2)

首先,您需要从firebase数据库temp.add(users.get(i));

获取所有记录

创建列表email = temp.get(i).getEmailId();

的副本

您可以在temp中添加特定的可搜索用户详细信息 - FirebaseDatabase.getInstance().getReference().child("Your table name").orderByChild("email").equalTo(your searchable emailid ).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator(); List<User> users = new ArrayList<>(); while (dataSnapshots.hasNext()) { DataSnapshot dataSnapshotChild = dataSnapshots.next(); User user = dataSnapshotChild.getValue(User.class); users.add(user); } String userids = ""; List<User> temp = new ArrayList(); try { for (int i = 0; i < users.size(); i++) { if (users.get(i).getEmailid().equals("your searchable email")) { temp.add(users.get(i)); //Here you can find your searchable user Log.e("temp", "+" + temp.get(i).getFirebaseId()); email = temp.get(i).getEmailId(); } } } catch (Exception e) { e.printStackTrace(); Log.e("Logs", e.toString()); } } @Override public void onCancelled(DatabaseError databaseError) { } });

现在你可以获得像这样1. cmd + shift + k 2. cmd + option + shift + k 3. Restart Xcode 4. Restart your pc.

的useremail
<script>
        window.onbeforeunload = function () {
            window.location.href = 'http://localhost:61632/index.html#/login';
//Here set the path where you wanted your application to go after reload.
        };
    </script>

答案 1 :(得分:1)

DatabaseReference reference = FirebaseDatabase.getInstance().getReference();

Query query = reference.child("Users").orderByChild("Email").equalTo("editext.getText()");
query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            // dataSnapshot is the "issue" node with all children with id 0
            for (DataSnapshot issue : dataSnapshot.getChildren()) {
                // do something with the individual "issues"
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

要记住的一些常见事项绝不是使用大写字母命名节点