Sound Muter & Flashlight for Android

Android call fragment method from activity

Sometimes, you have to call a method of a fragment from its parent activity. For example, you have a fragment that displays a list of SMS. When there is a new incoming SMS, the SMS receiver in your activity will call a method of the fragment to upload the SMS list. Calling the method of the fragment from its parent activity is simple. You need to find the fragment by its tag name using the findFragmentByTagName of FragmentManager class. Then call the method of the fragment to do something that you wish.
In the example application below, when a new message arrives, the broadcast receiver (SMSReceiver) defined and registered in the MainActivity will call the showLastSMS() method of the LastSMSFragment to display the last sms.

In the example application, you need to add a FrameLayout container to the activity_main.xml file. Then create another layout file called fraglayout.xml file for the fragment.

call fragment method from activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""



In the src directory, you create LastSMSFragment class. In this class, you have a method called showLastSMS() that will be called from the MainActivity to display the last sms.

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class LastSMSFragment extends Fragment {
  private TextView tv;
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     //Inflate the layout for this fragment
     View view = inflater.inflate(R.layout.fragmentlayout, container, false);    
     return view;
   public static LastSMSFragment newInstance() {
     return (new LastSMSFragment());
   public void showLastSMS(String mess){

In the MainActivity class, you define and register a broadcast receiver called SMSReceiver to receive the new coming SMS. In the onReceive() method, you pass the received SMS to the LastSMSFragment through showLastSMS() method to display the SMS.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

   private SMSReceiver smsReceiver;
   protected void onCreate(Bundle savedInstanceState) {
     smsReceiver = new SMSReceiver();
     // Register receiver to receive the last sms
     IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
     registerReceiver(smsReceiver, intentFilter);
     // Display fragment
     // Sending sms for testing
     sendSms("089256724", "This is the last sms.");

   private class SMSReceiver extends BroadcastReceiver {
     public void onReceive(Context context, Intent intent) {

        Bundle bundle = intent.getExtras();
        SmsMessage[] smsm = null;
        String sms_str = "";
        if (bundle != null) {
           // Get the SMS message
           Object[] pdus = (Object[]) bundle.get("pdus");
           smsm = new SmsMessage[pdus.length];
           for (int i = 0; i < smsm.length; i++) {
             smsm[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
             sms_str += "Sent From: " + smsm[i].getOriginatingAddress();
             sms_str += "\r\nMessage: ";
             String message=smsm[i].getMessageBody().toString();
             sms_str +=smsm[i].getMessageBody().toString();
             sms_str += "\r\n";

           LastSMSFragment lastSMSFragment = (LastSMSFragment)getSupportFragmentManager().findFragmentByTag("lastSMSFragment");
           if(lastSMSFragment==null) // if the fragment is not showing, show it
           // Call fragment method to display sms in the textview



   public void showFragment(){
     LastSMSFragment lastSMSFragment=LastSMSFragment.newInstance();
     FragmentTransaction transact=getSupportFragmentManager().beginTransaction();
     transact.add(, lastSMSFragment, "lastSMSFragment");

   public void sendSms(String phoneNo, String sms){
     SmsManager smsMgt= SmsManager.getDefault();
     smsMgt.sendTextMessage(phoneNo, null, sms, null, null);
     Toast.makeText(this,"The message was sent.", Toast.LENGTH_SHORT).show();


   public void onPause(){
     try {
        // Unregister the receiver
     }catch(Exception e){}

Before running the example application, you need to make sure that the application is able to send and receive SMS by adding the following lines to your AndroidManifest file.

<uses-permission android:name= "android.permission.SEND_SMS" />
<uses-permission android:name= "android.permission.RECEIVE_SMS" />

Posted by: Dara | post date: 03-28-2015 | Subject: Android Apps Development

write programming tip

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.