Update
Send data from activity to fragment in android
In this example We learn how to send two string from Activity to fragment.
Android recommends to use newInstance.
In the activity:
FirstFragment fragment = FirstFragment.newInstance("Param One","Param Two");
In the fragment:
public static FirstFragment newInstance(String param1, String param2) { FirstFragment fragment = new FirstFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } }
From Activity you send data with intent as:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void goToFragment(View view) { FirstFragment fragment = FirstFragment.newInstance("Param One","Param Two"); replaceFragment(fragment, "FirstFragment"); view.setVisibility(View.GONE); } public void replaceFragment(Fragment fragment, String tag) { try { FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.content_main, fragment, tag).commit(); } catch (Exception e) { Log.d(TAG, e.toString()); } } }
and in Fragment onCreateView method:
public class FirstFragment extends Fragment { // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private String mParam1; private String mParam2; public FirstFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment FirstFragment. */ public static FirstFragment newInstance(String param1, String param2) { FirstFragment fragment = new FirstFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_first, container, false); TextView textView1 = (TextView) view.findViewById(R.id.fragment_first_param_one); TextView textView2 = (TextView) view.findViewById(R.id.fragment_first_param_two); textView1.setText(mParam1); textView2.setText(mParam2); return view; } @Override public void onAttach(Context context) { super.onAttach(context); } @Override public void onDetach() { super.onDetach(); } }
fragment_first.xml
<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="com.example.javier.activitytofragment.FirstFragment"> <TextView android:id="@+id/fragment_first_param_one" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="@string/hello_blank_fragment" /> <TextView android:id="@+id/fragment_first_param_two" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_below="@+id/fragment_first_param_one" android:text="@string/hello_blank_fragment" /> </RelativeLayout>
contentent_main.xml(This content has the fragment)
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/content_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </RelativeLayout>
content_activity.xml (This content has the activity)
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:onClick="goToFragment" /> </RelativeLayout>
activity_main.xml(this layout has the contents)
<?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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.javier.activitytofragment.MainActivity"> <include layout="@layout/content_activity" /> <include layout="@layout/content_main" /> </RelativeLayout>
Hello! With your code, my app have a error:
“Unreachable code”
there is a conflict between:
return inflater.inflate(R.layout.fragment_name, container, false);
and my code:
return fragmentView;
can help me?
Thank you!
// set Fragmentclass Arguments
this means: setup class Fragmentclass. after extends or implement class..?
HI i tried this thing but i getting a Null Pointer Exception.How to solve that error
I update the post, you can check it. Now the example works very well.
i want a code for send a data from activity and receive that data to the activity of an fragment and set that data into the fragment activity text fields
Hi John, you can read this post
http://thedeveloperworldisyours.com/android/communicating-between-fragment-and-activity/
Regards.
You need to pass data in the intent when call the activity, then get extras from the itent in oncreate of the activity and set argument for fragement and finally get the data as explained in this post
hello can i know how to pass data from activity to fragments..
I searched and tried but i am getting null pointer exception, please help me out
I am using async task and passing Jsonobject from activity to fragment, i tried using bundle but it is throwing exception.
This example send two strings from Activity to Fragment. I don’t know your code.
In Fragment.java file add the following code,
public static String name= null;
public void setName(String string){
name = string;}
In MainActivity.java from which you want to send String add the following code,
String stringYouWantToSend;
Fragment fragment = new Fragment();
fragment.setName(stringYouWantToSend);
This is helpful when we need string from fragment to activity, thanks Shailesh.
Pingback: Communicating between fragment and activity • The Developer World Is Yours
Good code! It helped! Thank you!