晚上:)
我有点小问题…
正如您在下面的代码中所看到的,我正试图在textview上设置一个空指针:(
有人能告诉我我做错了什么吗?:)
字符串不是空的,或者,它是视图本身。在oncreate()中设置文本时,它正在工作。
谢谢。。
public class smsShower extends Activity{
private TextView status;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.show);
//status = (TextView)findViewById(R.id.status);
status = (TextView)findViewById(R.id.status);
}
public void displayText(String s){
status.setText(s);
}
}
SMSReceiver类:
public class smsreceiver extends BroadcastReceiver {
private String str;
private boolean received = false;
private smsShower smsshow;
@Override
public void onReceive(Context context, Intent intent) {
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
smsshow = new smsShower();
SmsMessage[] msgs = null;
str = "";
if (bundle != null)
{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
if(msgs[i].getDisplayOriginatingAddress().equals("1990"))
{
received = true;
str += msgs[i].getMessageBody().toString();
smsshow.displayText(str);
}
布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/status" android:layout_alignParentTop="true" android:text="Status:" android:layout_height="match_parent" android:layout_width="match_parent"></TextView>
</RelativeLayout>
错误日志:
02-18 01:14:20.064: ERROR/AndroidRuntime(18964): Caused by: java.lang.NullPointerException
02-18 01:14:20.064: ERROR/AndroidRuntime(18964): at com.sms1990.smsShower.displayText(smsShower.java:36)
02-18 01:14:20.064: ERROR/AndroidRuntime(18964): at com.sms1990.smsreceiver.onReceive(smsreceiver.java:47)
02-18 01:14:20.064: ERROR/AndroidRuntime(18964): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2941)
最佳答案
添加基本空检查,如下所示:
public void displayText(String s){
if (status != null)
status.setText(s);
}
你得不到npe。如何开始活动并在广播接收器中获得对它的引用?
关于android - 如何在Textview上更改文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5036370/