2013-08-16 75 views
0

更新的onReceive方法的TextView我創建了一個接收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 [email protected] 
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 

任何幫助將不勝感激。謝謝。

+0

最新的247行?\ – Pavlos

+0

是tvMessage空? – Tarun

+0

爲什麼tvMessage爲空? – Pavlos

回答

0

爲什麼不從共享偏好拉出來的消息,因爲我可以看到你所儲存的信息呢?你也需要確保tvMessage不是空的,就像Tarun指出的那樣。