如何使用BroadcastReceiver中的onReceive方法更新TextView

时间:2013-08-16 17:00:36

标签: android android-broadcast

我创建了一个接收GCM消息并显示其内容的活动。我能够使用broadcastReceiver来获取活动中的消息,但是当我尝试使用tvMessage.append()将消息附加到TextView时它会崩溃。 这是显示活动中接收器的代码。

private final BroadcastReceiver handleDiscussionMessage = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
        WakeLockerUtility.acquire(getApplicationContext());
        SharedPreferences sharedPref =
                 getSharedPreferences(SHAREDPREF_LOCATION, 0);
                 SharedPreferences.Editor editor = sharedPref.edit();
                 editor.putString("receivedMessage", newMessage);
                 editor.commit();

        tvMessage.append("<- " + newMessage + "\n");
        Toast.makeText(getApplicationContext(), "New Message Received: " + newMessage, Toast.LENGTH_LONG).show();
        WakeLockerUtility.release();
    }

};

这是我的logcat在应用程序崩溃时显示的内容:

08-16 16:10:08.701: E/AndroidRuntime(24024): FATAL EXCEPTION: main
08-16 16:10:08.701: E/AndroidRuntime(24024): java.lang.RuntimeException: Error receiving broadcast Intent { act=com.example.miingle.DISPLAY_MESSAGE flg=0x10 (has extras) } in com.example.miingle.DiscussionsActivity$1@40dc11f8
08-16 16:10:08.701: E/AndroidRuntime(24024):    at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:794)
08-16 16:10:08.701: E/AndroidRuntime(24024):    at android.os.Handler.handleCallback(Handler.java:605)
08-16 16:10:08.701: E/AndroidRuntime(24024):    at android.os.Handler.dispatchMessage(Handler.java:92)
08-16 16:10:08.701: E/AndroidRuntime(24024):    at android.os.Looper.loop(Looper.java:154)
08-16 16:10:08.701: E/AndroidRuntime(24024):    at android.app.ActivityThread.main(ActivityThread.java:4945)
08-16 16:10:08.701: E/AndroidRuntime(24024):    at java.lang.reflect.Method.invokeNative(Native Method)
08-16 16:10:08.701: E/AndroidRuntime(24024):    at java.lang.reflect.Method.invoke(Method.java:511)
08-16 16:10:08.701: E/AndroidRuntime(24024):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-16 16:10:08.701: E/AndroidRuntime(24024):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-16 16:10:08.701: E/AndroidRuntime(24024):    at dalvik.system.NativeStart.main(Native Method)
08-16 16:10:08.701: E/AndroidRuntime(24024): Caused by: java.lang.NullPointerException
08-16 16:10:08.701: E/AndroidRuntime(24024):    at com.example.miingle.DiscussionsActivity$1.onReceive(DiscussionsActivity.java:247)
08-16 16:10:08.701: E/AndroidRuntime(24024):    at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:781)
08-16 16:10:08.701: E/AndroidRuntime(24024):    ... 9 more

任何帮助将不胜感激。感谢。

1 个答案:

答案 0 :(得分:0)

为什么不从共享首选项中提取消息,因为我可以看到您已将消息存储在那里?另外,你需要确保tvMessage不是null,因为Tarun指出。