![](/img/trans.png)
[英]Android, how to update a textView in secondary activity from BroadcastReceiver.onReceive()?
[英]How to update TextView with onReceive method from BroadcastReceiver
我創建了一個活動,該活動接收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
任何幫助將不勝感激。 謝謝。
為什么不從共享首選項中拉出消息,因為我看到您已將消息存儲在那里? 另外,您還需要確保tvMessage不為Tarun所指出的為null。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.