0

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.

I have a getSMS method in MainAcitivity class, that looks like as following:

    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.

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:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
busterscruggz
  • 67
  • 2
  • 10
  • https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it – Kuffs Sep 18 '17 at 12:49
  • Activities are not supposed to be instantiated manually. If you have code within an Activity you want to call and the Activity is not open, it probably belongs in a helper class. – Kuffs Sep 18 '17 at 12:51
  • If this method have no thing to do with UI of your app. Why not to put it on a utility class? – Maged Saeed Sep 18 '17 at 12:54
  • You mean, I can call from any other class but can't call from Activity? https://stackoverflow.com/questions/10787159/android-call-an-method-from-another-class – busterscruggz Sep 18 '17 at 12:54

1 Answers1

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

sergiosua
  • 364
  • 2
  • 4