无法从FireBase数据库ValueEventListener

时间:2019-08-23 16:36:56

标签: android firebase-realtime-database android-listview

我正在尝试使用ValueEventListener使用Firebase数据库中的内容更新listView,但是每当执行此操作时,listView都会添加少量空间,并且什么也没有发生。但是,我可以从onClick方法和onCreate方法中更新listView。

我也已经尝试添加预定义的字符串,但是仍然存在相同的问题,因此从Firebase数据库或获取数据中这不是问题。

下面是初始化listView的代码:

ArrayList<String> messages = new ArrayList<>();
final MessageAdapter messageAdapter = new MessageAdapter(this,messages);
final ListView listMessages = findViewById(R.id.list_of_messages);
listMessages.setAdapter(messageAdapter);

这是自定义ArrayAdapter的代码:

public class MessageAdapter extends ArrayAdapter<String>{
public MessageAdapter(Context context, ArrayList<String> messages) {
        super(context, 0,messages);
    }

@Override
public View getView(int position, View convertView, ViewGroup parent){
 String[] message = getItem(position).split("└");
if(convertView == null){
    convertView = 
LayoutInflater.from(getContext()).inflate(R.layout.message,parent,false);
}
if(message[1].equals("0")){
          TextView me = convertView.findViewById(R.id.message_text_me);
          me.setText(message[0]);        
convertView.findViewById(R.id.message_text_him).setVisibility(View.GONE);
} else if (message[1].equals("1")) {
            TextView him = 
convertView.findViewById(R.id.message_text_him);
            him.setText(message[0]);
convertView.findViewById(R.id.message_text_me).setVisibility(View.GONE);
}else if (message[1].equals("2")){
            TextView him = 
convertView.findViewById(R.id.message_text_him);
            him.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(Chat.this,Help.class));
                }
            });
            him.setText(message[0]);

convertView.findViewById(R.id.message_text_me).setVisibility(View.GONE);
        }
        return convertView;
    }
}

这是我更新ListView的位置:

FirebaseDatabase.getInstance().getReference()
.addListenerForSingleValueEvent(new ValueEventListener() {

@Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

if(dataSnapshot.hasChild(message)){
ArrayList<String>answers = new ArrayList<>();
for(DataSnapshot d :dataSnapshot.child(message).getChildren()){
answers.add(d.getValue().toString());
}
//this doesn't work
messages.add(answers.get((int) (Math.random() * answers.size() + 0)));
messageAdapter.notifyDataSetChanged();
}else {
//this doesn't work
messages.add("I have never heard this before,help me learn by tapping 
here"+"└"+"2");
messageAdapter.notifyDataSetChanged();

    }
}

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

}});

0 个答案:

没有答案