2015-06-21 75 views
0

我是新来的android和卡住了一个小问题。我在Relativelayout中有TextView元素。而且我的应用程序正在从GCM接收broadcast,并且想根据收到的broadcast动态更新此TextView。我曾尝试使用TextViewElementId.setText方法。但它不起作用。无法更新textview

从layout.xml文件

<TextView 
    style="@style/LabelFont" 
    android:id="@+id/txtView1" 
    android:text="-" 
    android:textColor="#ffffff" 
    android:layout_alignParentRight="true"/> 

片段从我的Activity类(在这里我通过适当的数据和文本视图ID setBroadcastText方法)

public void setBroadcastText(final String pstrText ,final TextView tvView){ 

    handler.post(new Runnable() 
    { 
     public void run() 
     { 
      ptvView.setText(pstrText); 
     } 
    }); 

}

这个片段当收到与此文本框相关的数据时,将调用setBroadcastText方法。

我是否需要在运行时添加一些内容来更新此文本视图?

+0

有没有例外,或者它不起作用? –

+0

它是否在'ptvView.setText(pstrText);'行中断? – Youngjae

+0

是的..有一个例外:空指针异常。 java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'boolean android.os.Handler.post(java.lang.Runnable)'。我猜,它将tvView引用为空对象引用。尝试在null对象引用上的int android.widget.TextView.getID()上调用虚拟方法。 – Yasha

回答

0

您的处理程序为空。因此它崩溃。

+0

TextView。 android.widget.TextView.getID()正在调用空对象引用,即在findViewById中传递的R.id.TextViewId为null。 – Yasha

0
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.Handler.post(java.lang.Runnable)' on a null object reference. 

这意味着处理程序为空。 你应该调用方法后像现在这样的初始化处理程序对象:

handler=new Handler(); 
+0

它不是空的处理程序。但是TextView。 android.widget.TextView.getID()正在调用空对象引用,即在findViewById中传递的R.id.TextViewId为null。 – Yasha

0

很多[R & d后,这是我想通。 要更新视图,并接收到广播时,请执行下列操作:

在GCMIntentService类,

import android.support.v4.content.LocalBroadcastManager 
//your code 
protected void onMessage(final Context arg0, final Intent arg1) { 
//Other parts of your code 
Intent broadcast = new Intent("IntentName"); 
           broadcast.putExtra("Intent_Key", "Intent_Value"); 
           LocalBroadcastManager.getInstance(context).sendBroadcast(broadcast); 
} 

现在,在活动课,其中文本视图必须更新,收到此广播。就是这样。

import android.support.v4.content.LocalBroadcastManager; 
// 
protected void onCreate(Bundle savedInstanceState) { 
//Other parts of onCreate 
    LocalBroadcastManager.getInstance(this).registerReceiver(NewMethodName, 
       new IntentFilter("IntentName")); 

} 

实现您的方法NewMethodName()作为BroadcastReceiver()方法来更新您的运行时视图。