This question already has answers here:
Passing data from one fragment to another
(4 answers)
Closed 6 years ago.
Hello i am working with fragment to pass data from one fragment to another with My Model object like Student with (id,name),but i cant able to pass and view data in second fragment from pass first fragment.
use static variable
if you use view pager then update fragment when a fragment is change
In Fragment transaction send data in constructor when when a fragment is replace
You can pass data from one fragment to other using constructor or using setArgument
Using Constructor
ModelStudent student = new ModelStudent(1, "ABCD");
FragmentTwo fragmentTwo = new FragmentTwo(student);
Using setArgument
FragmentTwo fragmentTwo = new FragmentTwo();
Bundle bundle = new Bundle();
bundle.putSerializable("STUDENT", student);
fragmentTwo.setArguments(bundle);
Fragment 1
public class FragmentOne extends Fragment {
private View rootView;
private Button btnPassData;
public FragmentOne() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.frgament_one, container, false);
btnPassData = (Button) rootView.findViewById(R.id.btnPassData);
btnPassData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ModelStudent student = new ModelStudent(1, "ABCD");
// first way
//FragmentTwo fragmentTwo = new FragmentTwo(student);
// or second way
FragmentTwo fragmentTwo = new FragmentTwo();
Bundle bundle = new Bundle();
bundle.putSerializable("STUDENT", student);
fragmentTwo.setArguments(bundle);
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content, fragmentTwo).commit();
}
});
return rootView;
}
}
Fragment 2
public class FragmentTwo extends Fragment {
private View rootView;
private ModelStudent modelStudent;
private TextView txtStudent;
public FragmentTwo() {
}
public FragmentTwo(ModelStudent modelStudent) {
this.modelStudent = modelStudent;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.frgament_two, container, false);
txtStudent = (TextView) rootView.findViewById(R.id.txtStudent);
Bundle bundle = getArguments();
ModelStudent student = (ModelStudent) bundle.getSerializable("STUDENT");
txtStudent.setText("RollNo: " + student.getRollNo() + " Name: " + student.getName());
return rootView;
}
Related
This is my view holder class inside adapter class which is a separate class file. The recycler view is shown in a fragment and on click of the recycler view item I need to go to a new fragment activity and get the texts that was shown in the clicked item
public class BookViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public final BookRecyclerAdapter mAdapter;
private TextView titleTextView, authorTextView;
public BookViewHolder(View itemView, BookRecyclerAdapter adapter) {
super(itemView);
titleTextView = (TextView) itemView.findViewById(R.id.listItem_title_tView);
authorTextView = (TextView) itemView.findViewById(R.id.listItem_author_tView);
this.mAdapter = adapter;
itemView.setOnClickListener(this);
}
private void setBookCardView(String tText, String aText){
titleTextView.setText(tText);
authorTextView.setText(aText);
}
#Override
public void onClick(View v) {
String title = titleTextView.getText().toString();
String author = authorTextView.getText().toString();
//I NEED TO PASS THIS STRINGS TO NEW FRAGMENT
}
}
How can a start a new fragment activity which can access these two strings - title and author
In the onClick method of the view holder class
Bundle bundle = new Bundle();
bundle.putString("key", "value");
bundle.putString("key", "value");
SecondFragment secondFragment = new SecondFragment();
secondFragment.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) v.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, secondFragment).addToBackStack(null).commit();
After this you can start to retrieve the data in the fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment, container, false);
String strtext=getArguments().getString("string1"); //fetching value by key
String strtext1=getArguments().getString("string2");
}
Use Bundle to pass data adapter to fragment in your click Listener
Fragment fragment = new FragmentName();
FragmentManager fragmentManager = context.getSupportFragmentManager(); // this is basically context of the class
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Bundle bundle=new Bundle();
bundle.putString("string1", "your string");
bundle.putString("string2", "your string"); //key and value
//set Fragmentclass Arguments
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
and retrieve data in fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment, container, false);
String strtext=getArguments().getString("string1"); //fetching value by key
String strtext1=getArguments().getString("string2");
}
In the view holder class onClick:
Bundle bundle = new Bundle();
bundle.putString("key", "value");
bundle.putString("key", "value");
SecondFragment secondFragment = new SecondFragment();
secondFragment.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) v.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, secondFragment).addToBackStack(null).commit();
In the recieving fragment
View view = inflater.inflate(R.layout.fragment_book, container, false);
Bundle bundle = this.getArguments();
if(bundle != null){
Snackbar.make(view, bundle.get("key").toString(), Snackbar.LENGTH_LONG).show();
}
So what i want to do is that from first.java Fragment pass the EditText data and ImageView to two.java. I manage to replace first.java with two.java when i click the button (transaction.replace(R.id.top,Two);). I am familiar with Intent but i am not sure how to pass EditText and Imageview in Fragments. Please refer to the screenshot.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
first first=new first();
transaction.add(R.id.top,first);
transaction.commit();
}
}
first.java
public class first extends Fragment implements View.OnClickListener{
Button get_button;
EditText get_input_name;
ImageView get_image;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first,container,false);
get_input_name=(EditText)rootView.findViewById(R.id.input_name);
get_button=(Button)rootView.findViewById(R.id.submit);
get_image=(ImageView)rootView.findViewById(R.id.img1);
get_button.setOnClickListener(this);
return rootView;
}
public void onClick(View v){
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
two Two=new two();
transaction.replace(R.id.top,Two);
transaction.commit();
}
}
two.java
public class two extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_two, container, false);
}
}
Anyone can help? thx
Put both values in Bundle.
Bundle bundle = new Bundle();
bundle.putString("edtValue", <EditText value>);
bundle.putString("image", <Image path/url>);
Pass Bundle in Fragment
Two.setArguments(bundle);
Fetch these value in second fragment
Bundle bundle = getArguments();
String edtValue = bundle.getString("edtValue");
Tip : You should use camel case while declaring class name, check Java Coding Style Guidelines or Google Java Style Guide
You cannot share data between two fragments if they are on different activities but you can declare a variable in activity and get the result in any of the two fragments.
If both fragment are on same activity you can use Bundle , putExtra method for sharing data.
Further read Link
RRR answer is right.
You can do this by using constructor too.
in second activity make on constructor with values you want to get.
String text;
String imagepath;
// or int imageid;
public Two(String text, String imagepath /* or int imageid*/) {
super();
this.text = text;
this.imagepath = imagepath;
//or
this.imageid = imageid;
}
and from first fragment do like this.
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
two Two=new two(get_input_name.getText().toString.Trim(),imagepath /*or R.drawable.Imageid*/);
transaction.replace(R.id.top,Two);
transaction.commit();
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
Bundle args = new Bundle();
args.putInt("your_data",value);
two Two=new two();
two.setArguments(args);
transaction.replace(R.id.top,Two);
transaction.commit();
in two.java
Get these value and set in fragment
public class two extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Bundle b = getArguments();
String s = b.getInt("your_data");
// Do Whatever you want
return inflater.inflate(R.layout.fragment_two, container, false);
}
}
This question already has answers here:
How to pass values between Fragments
(18 answers)
Closed 6 years ago.
I have Two Dynamic Fragments associated with one activity, I am trying to pass one Text from First Fragment to Second Fragment using Bundle, but I am getting Null Pointer Exception. Is it the right way to pass String between two fragments? Below is my code :
First Fragment
public class FirstFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_main, container, false);
String text = "GetThisStringInSecondFragment";
TextView txtView = null;
txtView = (TextView) view.findViewById(R.id.firstfragmenttext);
txtView.setText(text);
Bundle bundle = new Bundle();
bundle.putString("HI", text);
return view;
}
}
Second Fragment
public class SecondFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_secondmain,
container, false);
TextView txtView = null;
txtView = (TextView) view.findViewById(R.id.secondfragmenttext);
Bundle bundle = this.getArguments();
String myInt = bundle.getString("HI");
txtView.setText(myInt);
return view;
}
}
Activity
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnLoad = (Button) findViewById(R.id.btn_load);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FirstFragment hello = new FirstFragment();
fragmentTransaction.add(R.id.fragment_container, hello, "HELLO");
fragmentTransaction.commit();
FragmentManager fragmentManager2 = getFragmentManager();
FragmentTransaction fragmentTransaction2 = fragmentManager2.beginTransaction();
SecondFragment hello2 = new SecondFragment();
fragmentTransaction2.add(R.id.fragment_container, hello2, "HELLO");
fragmentTransaction2.commit();
}
};
btnLoad.setOnClickListener(listener);
}
}
You are doing getArguments in second fragment but where are you sending those arguments from first fragment. You can use Interface here and define it in activity. From activity, you can use setArgument() method for second fragment.
check the following link for more detailed information and steps to do that.
https://developer.android.com/training/basics/fragments/communicating.html
I have a Main Activity.inside that main activity i have fragment with gridview and i want change my fragment by gridview clicking.
any help...
this is my mainActivity class
public class MainActivity extends Activity implements Fragment_name_list.Communicator {
Fragment_name_list f1;
Fragment_tests f2;
FragmentManager manager;
Fragment_addStudentDetails f3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
manager=getFragmentManager();
f1 = (Fragment_name_list) manager.findFragmentById(R.id.fragment);
f1.setCommunicator(this);
//ArrayAdapter<String> adapter= new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,result);
}
#Override
public void respond(int index) {
f2 = (Fragment_tests) manager.findFragmentById(R.id.fragment2);
f3 = (Fragment_addStudentDetails) manager.findFragmentById(R.id.fragment3);
switch (index){
case 1:
///Intent i = new Intent(this,Group_AddStudent_details.class);
///i.putExtra("index", index);
//startActivity(i);
f2.changeData(index);
break;
case 2:
break;
case 3:
break;
case 4:
break;
}
}
}
this is my Fragment test class
public class Fragment_tests extends Fragment {
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test,container,false);
text = (TextView) view.findViewById(R.id.textViewp);
return view;
}
public void changeData(int index){
String[] result= getResources().getStringArray(R.array.result);
text.setText(result[index]);
}
}
this is my Fragmnet add student class
public class Fragment_addStudentDetails extends Fragment {
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_add_student_details,container,false);
text = (TextView) view.findViewById(R.id.textViewp);
return view;
}
}
i want to replace my fragmnet_test with fragmnet_add_student_details.
plzz help
First, don't put your Fragments in the layout xml for your main Activity. I can't see if you are doing this for sure from your code, but I suspect that's what you're doing because of the fields you are keeping to refer to the two Fragments you are working with.
What you want to do is have a ViewGroup of some sort (FrameLayout will work) that you put your Fragment into programmatically. Use replace on a FragmentTransaction to swap out the existing Fragment for another.
getFragmentManager().beginTransaction() //
.replace(R.id.fragmentContainer, new BlahFragment()) //
.commit();
Also, don't use mutating methods on Fragments. If the data changes, just swap out the Fragment with the aforementioned code snippet, and get yourself a new Fragment via the documented pattern:
BlahFragment.newInstance(String[] data);
I pulled this example from the docs:
public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
}
Basically I have my fragment
public class FragmentDashboard extends Fragment {
public static FragmentDashboard newInstance() {
FragmentDashboard frag = new FragmentDashboard();
return frag;
}
public void updateData(Object object){
myTextView.setText(object.getField);
//update views with object values
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
myTextView = (TextView) view.findViewById(R.id.myTextView );
}
}
Then in my activity I need to update data I do:
FragmentDashboard fragmentDashboard = (FragmentDashboard) getSupportFragmentManager().findFragmentById(R.id.layFragment);
fragmentDashboard.updateData(myObject)
This works good if I am making the call on my activity after the Fragment has been displayed (like from an asynctask on completed).
The problem I am running into is having to run the updateData right after I add the fragment on my activity's onCreate().
final FragmentTransaction ft = fragmentManager.beginTransaction();
FragmentDashboard fragmentDashboard = FragmentDashboard.newInstance();
ft.replace(R.id.layFragment, fragmentDashboard);
ft.commit();
fragmentDashboard.updateData(myObject)
Running this I get a NPE because the fragment's onCreateView hasn't been run yet and the myTextView is not initialized
I don't want to add parameters on newInstance as I'd like to avoid making the object as parcelable. Any ideas ?
You can use a local field to contains your data and use it in your onCreateView method :
public class FragmentDashboard extends Fragment {
private Object myData=null;
private TextView myTextView = null;
public static FragmentDashboard newInstance() {
FragmentDashboard frag = new FragmentDashboard();
return frag;
}
public void updateData(Object object){
myData = object;
if(myTextView != null)
myTextView.setText(myData);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
myTextView = (TextView) view.findViewById(R.id.myTextView );
if(myData != null && myTextView != null)
myTextView.setText(myData);
}
}
It isn't a good practice to set Data like updateData(Object ) . Make your model class parcelable or serializable and pass it in putExtra and get it in onViewCreated.
public static FragmentDashboard newInstance(Object object) {
Bundle args = new Bundle();
args.putParcelable("yourModelClass",object);
FragmentDashboard frag = new FragmentDashboard();
frag.setArguments(args);
return frag;
}
And in onViewCreated
if(getArguments != null)
yourModelClassObject = getArguments().getParcelable("yourModelClass");
if(yourModelClassObject != null)
textView.setText(yourModelClassObject.getField());
I have written code orally . May contain mistakes.