我阅读了有关NPE和Firebase的所有帖子,但没有任何帮助。当我启动我的应用程序时,我总是得到NPE。我还阅读了“什么是NPE以及如何解决它”,但没有任何帮助。针对“ startListening”发生错误。我知道,启动该应用程序时没有什么要阅读的,因为聊天列表为空。但是我该如何解决呢? 我已经将适配器声明为全局变量。
这是我的代码:
public class ChatLayout extends AppCompatActivity {
private static final int SIGN_IN_REQUEST_CODE = 1;
public FirebaseListAdapter<ChatMessage> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_layout);
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
startActivityForResult(
AuthUI.getInstance().createSignInIntentBuilder()
.setTheme(R.style.AppTheme)
.build(),
SIGN_IN_REQUEST_CODE
);
} else {
Toast.makeText(this,
"Willkommen " + FirebaseAuth.getInstance()
.getCurrentUser()
.getDisplayName(),
Toast.LENGTH_LONG)
.show();
}
FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText input = (EditText) findViewById(R.id.input);
FirebaseDatabase.getInstance()
.getReference()
.child("Messagess")
.push()
.setValue(new ChatMessage(input.getText().toString(),
FirebaseAuth.getInstance()
.getCurrentUser()
.getDisplayName())
);
ListView listOfMessages = (ListView) findViewById(R.id.list_of_messages);
Query query = FirebaseDatabase.getInstance().getReference().child("Messagess");
FirebaseListOptions<ChatMessage> options = new FirebaseListOptions.Builder<ChatMessage>()
.setQuery(query, ChatMessage.class)
.setLayout(R.layout.message)
.build();
adapter = new FirebaseListAdapter<ChatMessage>(options) {
@Override
protected void populateView(View v, ChatMessage model, int position) {
TextView messageText = (TextView) v.findViewById(R.id.message_text);
TextView messageTime = (TextView) v.findViewById(R.id.message_time);
TextView messageUser = v.findViewById(R.id.message_user);
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));
}
};
listOfMessages.setAdapter(adapter);
adapter.startListening();
input.setText("");
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SIGN_IN_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Toast.makeText(this,
"Login erfolgreich",
Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(this,
"Login fehlgeschlagen. Bitte versuchen Sie es erneut.",
Toast.LENGTH_LONG)
.show();
finish();
}
}
}
@Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
@Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
答案 0 :(得分:0)
我通过更改
解决了 listOfMessages.setAdapter(adapter);
adapter.startListening();
到
adapter.startListening();
listOfMessages.setAdapter(adapter);
现在可以了。