0

I'm trying to implement code that sends an SMS by using the default SMS application but I'm getting null context and I don't understand why.

I already tried with getBaseContext(), getContext(), getApplicationContext with no success.

What am I doing wrong?

I'm testing this code on a Moto E5 Android 8.1 Go.

The code is inside of MainActivity.java

public void sendSMS(String msg)
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) // At least KitKat
    {
        String defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(this); //<---Line 107 --- Need to change the build to API 19

        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.setType("text/plain");
        sendIntent.putExtra(Intent.EXTRA_TEXT, msg);

        if (defaultSmsPackageName != null)// Can be null in case that there is no default, then the user would be able to choose
        // any app that support this intent.
        {
            sendIntent.setPackage(defaultSmsPackageName);
        }
        startActivity(sendIntent);
    }
    else // For early versions, do what worked for you before.
    {
        Intent smsIntent = new Intent(Intent.ACTION_VIEW);
        smsIntent.setType("vnd.android-dir/mms-sms");
        smsIntent.putExtra("address", SMSParameters.getTelefono(this));
        smsIntent.putExtra("sms_body",msg);
        startActivity(smsIntent);

    }
}

Part of HomeFragment class

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) 
{
    View view = inflater.inflate(R.layout.fragment_home, container, false);

    final Button buttonAusente = view.findViewById(R.id.button_ausente);
    buttonAusente.setOnClickListener(new View.OnClickListener()
    {

        public void onClick(View view)
        {
            String message = null;

                //enviarComando AUSENTE

                //Line 70 below
            message = MessageGenerator.getMessageAusente(_password, _id, SMSParameters.getSecuencia(getContext())); //<-- Line 70
            new MainActivity().sendSMS(message);

        }
    });

    final Button buttonDesactivar = view.findViewById(R.id.button_desactivar);
    buttonDesactivar.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view)
        {
            String message = null;
           //enviarComando DESACTIVAR
            message = MessageGenerator.getMessageDesactivar(_password, _id, SMSParameters.getSecuencia(getContext()));
            new MainActivity().sendSMS(message);

        }
    });

    final Button buttonPresente = view.findViewById(R.id.button_presente);
    buttonPresente.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View view)
        {
            String message = null;

               // enviarComando PRESENTE
            message = MessageGenerator.getMessagePresente(_password, _id, SMSParameters.getSecuencia(getContext()));
            new MainActivity().sendSMS(message);
        }
    });

    final Button buttonPanico = view.findViewById(R.id.button_panico);
    buttonPanico.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View view)
        {
            String message = null;

            //  enviarComando(Comandos.PANICO);
            message = MessageGenerator.getMessagePanico(_password, _id, SMSParameters.getSecuencia(getContext()));
            new MainActivity().sendSMS(message);

        }
    });

    setStatusIcon(getContext(), Comandos.AUSENTE, view);
    setStatusIcon(getContext(), Comandos.DESACTIVAR, view);
    setStatusIcon(getContext(), Comandos.PRESENTE, view);
    setStatusIcon(getContext(), Comandos.PANICO, view);

    saveViewStatus(view);

    return view;
}
E_Blue
  • 1,021
  • 1
  • 20
  • 45
  • Please add the stacktrace to your question - also, where is this code being called? Are we in an Activity, a Service..? – PPartisan Mar 31 '19 at 07:06
  • Maybe I understand wrong the error says "Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference" – E_Blue Mar 31 '19 at 07:07
  • I don't see you calling `getApplicationContext()` in the snippet you provided. Can you update your question to provide the information I asked for? – PPartisan Mar 31 '19 at 07:08
  • I replaced by "this" with same result. Give me a minute please, I'm updating. – E_Blue Mar 31 '19 at 07:10
  • Where is this code being called? – Adib Faramarzi Mar 31 '19 at 07:11
  • I added the code from where is being called. Do I forgot to to add something? – E_Blue Mar 31 '19 at 07:15
  • You haven't added it - you have the method declaration for `sendSms()`, but where is it being called? – PPartisan Mar 31 '19 at 07:19
  • Could you post these lines of code please, `MainActivity.sendSMS(MainActivity.java:107)` and `HomeFragment$1.onClick(HomeFragment.java:70)` – PPartisan Mar 31 '19 at 07:21
  • @PPartisan I think now is ready, please refresh the page. – E_Blue Mar 31 '19 at 07:30

2 Answers2

1

new MainActivity().sendSMS(message); - This wont work. First, you do not instantiate Activities via their constructor, but with an Intent, and second, because you don't want to create a new activity, but access the Activity the Fragment is currently attached to.

In order to communicate with the host Activity from your Fragment, you can see my answer here (see Methods 2 and 3) and this sample project. These techniques are also outlined in the Android Documentation.

PPartisan
  • 8,173
  • 4
  • 29
  • 48
  • I do it that way because when I created the method inside the class HomeFragment I get an error about static method being called from non-static method, also getContext() in red and more errors. Now I will read your links. – E_Blue Mar 31 '19 at 07:40
0

not having a using System.Configuration; will cause this error.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 02 '22 at 11:32