I'm looking for a good example, how I can call a method that is declared in MainAcitivity from another class in the same package.
我正在寻找一个很好的例子,我如何调用同一个包中另一个类在MainAcitivity中声明的方法。
I have a getSMS method in MainAcitivity class, that looks like as following:
我在MainAcitivity类中有一个getSMS方法,如下所示:
private void sendSMS(String phoneNumber, String message) {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
public void getSMS(){
sendSMS("5556", "You're at home.");
}
I'm calling getSMS() method in another class from MainActivity class.
我在MainActivity类的另一个类中调用getSMS()方法。
public void tSMS(){
MainActivity mainActivity = new MainActivity();
mainActivity.getSMS();
}
Now I'm calling the method in other class using the conditional statement.
现在我使用条件语句在其他类中调用该方法。
if (activity.getType() == 3) {
tSMS();
}
Logcat:
logcat的:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
1 个解决方案
#1
0
getSms() and sendSms() shouldn't be defined in your activity. Check some info about structuring your code: https://medium.com/@dmilicic/a-detailed-guide-on-developing-android-apps-using-the-clean-architecture-pattern-d38d71e94029
不应在您的活动中定义getSms()和sendSms()。查看有关构建代码的一些信息:https://medium.com/@dmilicic/a-detailed-guide-on-developing-android-apps-using-the-clean-architecture-pattern-d38d71e94029
#1
0
getSms() and sendSms() shouldn't be defined in your activity. Check some info about structuring your code: https://medium.com/@dmilicic/a-detailed-guide-on-developing-android-apps-using-the-clean-architecture-pattern-d38d71e94029
不应在您的活动中定义getSms()和sendSms()。查看有关构建代码的一些信息:https://medium.com/@dmilicic/a-detailed-guide-on-developing-android-apps-using-the-clean-architecture-pattern-d38d71e94029