user3375184 user3375184 - 3 months ago 102x
Android Question

getApplicationContext() error Android

I have a fragment that allows a user to enter in a message and a phone number to which the message will be delivered. I am getting an error "cannot resolve method getApplicationContext()" I have looked at the answer here the method getApplicationContext() is undefined but it didn't help me, maybe I am implementing it wrong but I am not sure! This code works fine as an activity but not as a fragment.

FragmentTab1 class

package com.androidbegin.absfragtabhost;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class FragmentTab3 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab3, container, false);

sendBtn = (Button) rootView.findViewById(;
txtphoneNo = (EditText) rootView.findViewById(;
txtMessage = (EditText) rootView.findViewById(;

sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {

return rootView;

Button sendBtn;
EditText txtphoneNo;
EditText txtMessage;

protected void sendSMSMessage() {
Log.i("Send SMS", "");

String phoneNo = txtphoneNo.getText().toString();
String message = txtMessage.getText().toString();

try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
} catch (Exception e) {
"SMS failed, please try again.",

public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(, menu);
return true;



The method getApplicationContext() does not exist in the class Fragment. It does exist, however, in the class Activity, so you can use getActivity().getApplicationContext() to get the context from within a fragment object. (Assuming the fragment is attached to an activity so getActivity() will return a non-null object, which is usually true)