我想从Firebase数据库中的单个Textview中获取全部数据

时间:2020-02-16 17:05:26

标签: java android firebase-realtime-database

我创建了一个条形码扫描仪应用程序,它读取条形码ID,并需要将输出作为语音输出。为了读取所有内容,我需要在一个TextView中一起读取所有数据。我尽我最大的努力从数据库中添加查询。但它仅在TextView中显示为com.google.firebase.database.Query@9fc9e4d,而我的应用TTS引擎却清晰地读取了它。但是我需要将其设置为数据库中单个TextView下的所有数据才能说出来。请帮我????这里只有我附上了结果处理方法。

@Override 
public void handleResult(Result result) { final String scanResult = result.getText();

    databasefetch = FirebaseDatabase.getInstance().getReference("save");
    databasefetch.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {



            setContentView(R.layout.activity_second);
            TextView text = (TextView) findViewById(R.id.textView3);
            String tst = databasefetch.child("save").orderByChild("id").equalTo(scanResult).toString();
            text.setText(tst);



            //text to speech
            String  toSpeak=text.getText().toString();
            //Toast.makeText(getApplicationContext(),toSpeak,Toast.LENGTH_SHORT).show();
            txt.speak(toSpeak,TextToSpeech.QUEUE_FLUSH,null);


        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

Demo

enter image description here

2 个答案:

答案 0 :(得分:0)

尝试这样的事情

@Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
            // TODO: handle the post
            YourModelClass object = postSnapshot.getValue(YourModelClass.class);
            text.setText(object.getId().equalsIgnoreCase(scanResult) ? object.getDescription() : "");
        }
    }

答案 1 :(得分:0)

无需运行多个查询来基于id过滤数据。检查以下内容:

databasefetch = FirebaseDatabase.getInstance().getReference("save");
databasefetch.orderByChild("id").equalTo(scanResult).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        String  toSpeak = "";

        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {

            String name = childSnapshot.child("name").getValue(String.class);
            String price = childSnapshot.child("price").getValue(String.class);
            String details = childSnapshot.child("details").getValue(String.class);

            toSpeak = name + ", " + price + ", " + details;
        }

        text.setText(toSpeak);

        txt.speak(toSpeak, TextToSpeech.QUEUE_FLUSH,null);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});