How to send data from one Fragment to another Fragment in Android?

AndroidApps/ApplicationsMobile Development

This example demonstrates how do I set the Android permission on a folder/file on SD Card to be able to write to it.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <androidx.viewpager.widget.ViewPager
      android:id="@+id/viewPager"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      app:layout_behavior="@string/appbar_scrolling_view_behavior" />
   <com.google.android.material.appbar.AppBarLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:theme="@style/AppTheme">
   <com.google.android.material.tabs.TabLayout
      android:id="@+id/tabLayout"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      app:tabGravity="fill"
      app:tabMode="fixed" />
   </com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Step 3 − Create two fragment layouts and add the following code as given below −

FragmentOne.java

import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class FragmentOne extends Fragment {
   private SendMessage sendMessage;
   public FragmentOne() {
   }
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
      return inflater.inflate(R.layout.fragment_fragment_one, container, false);
   }
   @Override
   public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
      super.onViewCreated(view, savedInstanceState);
      Button btnPassData = view.findViewById(R.id.btnPassData);
      final EditText inData = view.findViewById(R.id.passMessage);
      btnPassData.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            sendMessage.sendData(inData.getText().toString().trim());
         }
      });
   }
   interface SendMessage {
      void sendData(String message);
   }
   @Override
   public void onAttach(@NonNull Context context) {
      super.onAttach(context);
      try {
         sendMessage = (SendMessage) getActivity();
      }
       catch (ClassCastException e) {
         throw new ClassCastException("Error in retrieving data. Please try again");
      }
   }
}

Fragment_fragment_one.xml −

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:fillViewport="true">
   <RelativeLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content">
   <EditText
      android:id="@+id/passMessage"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_above="@+id/btnPassData"
      android:layout_margin="16dp"
      android:hint="Enter here" />
   <Button
      android:id="@+id/btnPassData"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="PASS DATA TO FRAGMENT TWO" />
   </RelativeLayout>
</ScrollView>

FragmentTwo.java −

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentTwo extends Fragment {
   private TextView textView;
   public FragmentTwo() {
   }
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
      return inflater.inflate(R.layout.fragment_fragment_two, container, false);
   }
   @Override
   public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
      super.onViewCreated(view, savedInstanceState);
      textView = view.findViewById(R.id.txtData);
   }
   void displayReceivedData(String message) {
      textView.setText("Data received: " + message);
   }
}

Fragment_fragment_two.xml −

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".FragmentTwo">
   <TextView
      android:id="@+id/txtData"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textSize="20sp"
      android:textStyle="bold"
      android:layout_centerInParent="true"
      android:text="No data received" />
</RelativeLayout>

Step 4 − Add the following code to src/MainActivity.java

package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity implements FragmentOne.SendMessage{
   TabLayout tabLayout;
   ViewPager viewPager;
   ViewPagerAdapter viewPagerAdapter;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      viewPager = findViewById(R.id.viewPager);
      viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
      viewPager.setAdapter(viewPagerAdapter);
      tabLayout = findViewById(R.id.tabLayout);
      tabLayout.setupWithViewPager(viewPager);
   }
   @Override
   public void sendData(String message) {
      String tag = "android:switcher:" + R.id.viewPager + ":" + 1;
      FragmentTwo f = (FragmentTwo) getSupportFragmentManager().findFragmentByTag(tag);
      f.displayReceivedData(message);
   }
}

Step 5 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

Click here to download the project code.

raja
Published on 22-Nov-2019 17:14:13
Advertisements