java.lang.RuntimeException:无法启动活动ComponentInfo-FirebaseListAdapter空对象

时间:2019-01-09 13:36:17

标签: java firebase-realtime-database chat firebaseui

我想与firebase数据库进行公共聊天以通过大学课程。我遇到问题是因为,我学会了如何写这篇文章,并且观看了YouTube上的教程。我找到了项目,但确实做到了,但是firebase使用FirebaseListAdapter进行了一些更改。为此,我更改了代码。

目前我有这个:

我知道(可能)发生了什么,但我需要知道如何解决它。

1)ActivityChat基于互联网上的教程。

public class ActivityChat extends AppCompatActivity {
    private static int SIGN_IN_REQUEST_CODE = 1;
    private FirebaseListAdapter<ChatMsg> adapter;
    Query query = FirebaseDatabase.getInstance().getReference().child("Chats").limitToLast(50);

    FirebaseListOptions<ChatMsg> options = new FirebaseListOptions.Builder<ChatMsg>()
            .setQuery(query, ChatMsg.class)
            .setLayout(R.layout.activity_chat)
            .build();
    EditText input;
    RelativeLayout chat;
    FloatingActionButton fab;

    @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(getApplicationContext(), "Pomyślnie zalogowany!", Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(getApplicationContext(), "Nie można zalogować się. Spróbuj później.", Toast.LENGTH_SHORT).show();
            }

        }
    }

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

        input = (EditText) findViewById(R.id.input);
        chat = (RelativeLayout) findViewById(R.id.activity_chat);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FirebaseDatabase.getInstance().getReference("Chats").push().setValue(new ChatMsg(input.getText().toString(),
                        FirebaseAuth.getInstance().getCurrentUser().getEmail()));
                input.setText("");
                input.requestFocus();
                displayChatMessage();
            }

        });


        if (FirebaseAuth.getInstance().getCurrentUser() == null) {
            startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_REQUEST_CODE);
        } else {
            Toast.makeText(getApplicationContext(), "Witaj: " + FirebaseAuth.getInstance().getCurrentUser().getEmail(), Toast.LENGTH_SHORT).show();
        }


    }

    private void displayChatMessage() {
        ListView listMessage = (ListView) findViewById(R.id.list_of_message);
        adapter = new FirebaseListAdapter<ChatMsg>(options) {
            @Override
            protected void populateView(@NonNull View v, @NonNull ChatMsg model, int position) {
                TextView messageText, messageUser, messageTime;
                messageText = (TextView) v.findViewById(R.id.message_text);
                messageUser = (TextView) v.findViewById(R.id.message_user);
                messageTime = (TextView) v.findViewById(R.id.message_time);

                messageText.setText(model.getMessageText());
                messageUser.setText(model.getMessageUser());
                messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));
            }
        };
        listMessage.setAdapter(adapter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        adapter.startListening();
    }


    @Override
    protected void onStop() {
        super.onStop();
        adapter.stopListening();
    }
}

2)当我按下按钮进入聊天时,看到活动2秒钟,并且apk崩溃(Apk已停止)。

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.bsk69.spystreamgui, PID: 6214
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bsk69.spystreamgui/com.example.bsk69.spystreamgui.ActivityChat}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.firebase.ui.database.FirebaseListAdapter.startListening()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2763)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2824)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1546)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6351)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:896)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:786)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.firebase.ui.database.FirebaseListAdapter.startListening()' on a null object reference
        at com.example.bsk69.spystreamgui.ActivityChat.onStart(ActivityChat.java:222)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1249)
        at android.app.Activity.performStart(Activity.java:6792)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2726)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2824) 
        at android.app.ActivityThread.-wrap12(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1546) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6351) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:896) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:786) 
Application terminated.

1 个答案:

答案 0 :(得分:0)

问题是由NullPointerException上的ActivityChat.java:222引起的,这是您的onStart方法的最后一行:

@Override     受保护的void onStart(){         super.onStart();         adapter.startListening();     }

该错误表示您在创建startListening()之前正在呼叫adapter。由于仅在用户单击按钮时在displayChatMessage中创建适配器,因此您可以盲目地告诉它开始在onStart中连接到数据库,这是在用户单击按钮之前发生的。

在创建适配器时,很可能您可以直接开始收听:

private void displayChatMessage() {
    ListView listMessage = (ListView) findViewById(R.id.list_of_message);
    adapter = new FirebaseListAdapter<ChatMsg>(options) {
        ...
    };
    listMessage.setAdapter(adapter);
    adapter.startListening();
}

您还需要更改onStop,因为无需用户每次单击按钮就可以调用它。最简单的解决方法是:

@Override
protected void onStop() {
    super.onStop();
    if (adapter != null) {
        adapter.stopListening();
    }
}

这些空指针异常在编程中非常常见,因此我强烈建议阅读What is a NullPointerException, and how do I fix it?