我想调用从子类到主活动类的函数。 这是我的源代码: SMS.java
public class SMS extends ListActivity {
public void testerr(String kata) {
Toast.makeText(getBaseContext(), "test coyyyy="+kata, Toast.LENGTH_LONG).show();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
SMSReceiver.java
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
try {
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]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
SMS sss = new SMS(); ---> call the main class
sss.testerr("try the words"); ---> call method from main class
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
}
}
catch(NullPointerException ex){
Toast.makeText(context, "penyakite neng kene:"+ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
我的程序在收到新的文本消息后运行,并且在调用sss.testerr(“我的示例单词”)时总是得到NullPointerException; 任何线索的家伙? 非常感谢你的帮助
答案 0 :(得分:1)
你不应该用它的构造函数实例化Activity,要么用intent启动它,要么如果Activity已经启动,那就让它实现广播接收器。
如果您只想通过接收器显示吐司,可以使用this question的答案