Fragment retrieve data from recycler view - android

This is an adapter for my RecyclerView. It is meant to pass data from the RecyclerView to my Fragment, but I'm not able to do that from the onClick() method.
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putString("name",name.getText().toString() );
OneFragment myFrag = new OneFragment();
myFrag.setArguments(bundle);
}
My Fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
txt_name=(TextView) txt_name.findViewById(R.id.name_emp);
String name = getArguments().getString("name");
txt_name.setText(name);
}

I'm not sure what are you intending to do. But after you set a bundle to a fragment you have to start the fragment with a transaction like this
getSupportFragmentManager().beginTransaction().add(<id of the container>, myFrag).commit();
Look the documentation on fragments

Like Below code create a method to your Activity, Where you have fragment :
Recyclerview Adapter Code :
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)context).sendData(name.getText().toString());
}
Get String in your MainActivity and call Fragment from Activity :
MainActivity Code :
String name;
public void sendData(String nameAdapter)
{
name = nameAdapter;
if(name!=null){
MedicineFragment med_frag = MedicineFragment.newInstance(name);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, med_frag)
.commit();
}
}
get name of Name in your fragment like this :
Fragment Code :
String name;
public static MedicineFragment newInstance(String nameValue) {
Bundle args = new Bundle();
MedicineFragment fragment = new MedicineFragment();
name = nameValue;
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
inside your main_activity.xml you have to take FrameLayout , by only this layout your fragment will change one to another.
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/search_layout"
android:background="#color/blue_veryLight"
android:id="#+id/content_frame">
</FrameLayout>

I know that I am late to the party. Still, I'll post an answer here.
In your adapter class make these changes.
public class FooAdapter extends extends RecyclerView.Adapter<FooAdapter.FooHolder> {
private RvClickListener mClickListener;
......
// rest of the code here
......
public FooAdapter(<other parameters>, RvClickListener clickListener) {
.....
// other variables initializations here
.....
mClickListener = clickListener;
}
......
// rest of the code here
......
#Override
public void onBindViewHolder(FooHolder holder, int position) {
// rest of the code
holder.itemView.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mClickListener != null) {
mClickListener.onClick(name.getText().toString());
}
}
});
}
// other codes here
public interface RvClickListener {
void onClick(String name);
}
}
Now it's time to the adapter in our Fragment class. You need to change the code as below.
public class FooFragment extends Fragment {
// other codes here
// before setting adapter to RecyclerView make these changes.
FooAdapter adapter = new FooAdapter(
<other parameters>,
new RvClickListener() {
#Override
public void onClick(String name) {
// do whatever you want
}
});
}

Related

How can I send the data fragment to fragment with FirebaseRecyclerAdapter

I want to send the String data in LibraryFragment to LibrarySongFragment.
LibraryFragment :
public class LibraryFragment extends Fragment {
private FirebaseRecyclerAdapter mAdapter;
#Nullable
#Override
public New onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
...
mAdapter = new LibraryAdapter(options, context);
recyclerView.setAdapter(mAdapter);
}
}
LibraryAdapter :
public class LibraryAdapter extends FirebaseRecyclerAdapter<MyModel, LibraryAdapter.MyViewHolder> {
...
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View view) {
super(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = getItem(getAdapterPosition()).getTitle();
((FragmentActivity) context).getSupportFragmentManager().beginTransaction()
.addToBackStack(null).replace(R.id.library_coordinator, new LibrarySongFragment()).commit();
}
});
}
}
}
I want to send the title that in MyViewHolder in LibraryAdapter. You can see the "String title = getItem(getAdpaterPosition()).getTitle();". Just send to LibrarySongFragment and post it in fragment_song_library.xml TextView.
You need to just create bundle of your data and set arguments in fragment object. i have modified your code. please refer
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View view) {
super(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = getItem(getAdapterPosition()).getTitle();
FragmentManager fragmentManager = ((Activity)context).getSupportFragmentManager();
Fragment fragment;
LibrarySongFragment librarySongFragment = new LibrarySongFragment();
Bundle bundle = new Bundle();
bundle.putString("KeyTitle",title);
librarySongFragment.setArguments(bundle);
fragmentManager.beginTransaction()
.addToBackStack(null).replace(R.id.library_coordinator, librarySongFragment).commit();
}
});
}
}
create inteface
in fragment from where you are going to send the data
SendMessage SM;
public interface SendMessage{
void Senddata(String message,Boolean sent);
}
override this method to same fragment
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SM = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
implement this fragment to the activity which hold these fragment
public class Activity extends AppCompatActivity implements sendfragment.SendMessage
override the message to the activity
#Override
public void Senddata(String message,Boolean sent) {
fragtwo f = (fragtwo) getSupportFragmentManager().findFragmentByTag(tag);
if(sent==true){
Toast.makeText(this, "data transfered", Toast.LENGTH_SHORT).show();
f.displaydata(message);
}
}
Create public method for sent data
public void displaydata(String massage){
String massageformat="received data is "+massage;
}
this is way to communicate between fragments in android

Replacing Fragment inside ViewPager from Fragment RecycerView Adapter Return Blank Screen?

I am trying to replace the current active fragment inside ViewPager when item inside fragment's recycelerview is clicked. So far, I manage to pop up the Toast on the second fragment when the item on the first fragment is clicked, but the all the view of the second fragment is blank.
Here is my code:
MainActivity.class
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = findViewById(R.id.view_pager);
FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(adapter.getCount() - 1);
}
// ..........
private static class FragmentAdapter extends FragmentStatePagerAdapter {
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return AllGenreFragment.newInstance();
case 1:
return DashboardFragment.newInstance();
case 2:
return NotificationFragment.newInstance();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
// ..........
}
AllGenreFragment.class
public class AllGenreFragment extends Fragment {
RecyclerView genreRV;
private AllGenreAdapter allGenreAdapter;
private List<Genre> genreList;
public static AllGenreFragment newInstance() {
return new AllGenreFragment();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_genre, container, false);
genreRV = v.findViewById(R.id.rv);
genreRV.setHasFixedSize(true);
GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
genreRV.setLayoutManager(layoutManager);
genreList = new ArrayList<>();
allGenreAdapter = new AllGenreAdapter(genreList, getContext());
genreRV.setAdapter(allGenreAdapter);
return v;
}
}
AllGenreAdapter.class
public class AllGenreAdapter extends RecyclerView.Adapter<AllGenreAdapter.ViewHolder> {
// .......
class ViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder {
public ViewHolder(final View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Genre: " + genre_title.getText().toString(), Toast.LENGTH_SHORT).show();
AppCompatActivity activity = (AppCompatActivity) itemView.getContext();
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment allAnimeFragment = new AllAnimeFragment();
Bundle bundle = new Bundle();
bundle.putString("genreid", genre_id.getText().toString().trim());
allAnimeFragment.setArguments(bundle);
fragmentTransaction.replace(R.id.view_pager, allAnimeFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
}
// .......
}
AllAnimeFragment.class
public class AllAnimeFragment extends Fragment {
RecyclerView animeRV;
private AllAnimeAdapter allAnimeAdapter;
private List<Anime> animeList;
String genreid;
public static AllAnimeFragment newInstance() {
return new AllAnimeFragment();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_anime, container, false);
Bundle arguments = getArguments();
genreid = arguments.getString("genreid");
Toast.makeText(getContext(), genreid, Toast.LENGTH_SHORT).show();
// .....
return v;
}
}
Your approach is not really good, try below way:
Create a container fragment, called ContainerFragment, example, you will be using this fragment for your ViewPager.
The ContainerFragment should contain a container view, and add AllGenreFragment in the first them it is invoked.
In AllGenreFragment, create a callback, when an item in the RecyclerView be clicked, then in ContainerFragment will replace (or add) current fragment (AllGenreFragment) to AllAnimeFragment
First, create ContainerFragment,
public class ContainerFragment extends Fragment implements AllGenreFragment.OnAllGenreFragmentListener {
#Nullable #Override public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_container, container, false);
}
#Override public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initialLoad();
}
private void initialLoad() {
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, AllGenreFragment.newInstance())
.commit();
}
#Override public void onItemClicked() {
getChildFragmentManager()
.beginTransaction()
.replace(R.id.container, AllAnimeFragment.newInstance())
.commit();
}
}
This Fragment should implement a callback from AllGenreFragment for handling fragment transaction.
also, the xml layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Next step, add above fragment into ViewPager, we using ContainerFragment instead of AllGenreFragment.
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ContainerFragment().newInstance();
case 1:
return DashboardFragment.newInstance();
case 2:
return NotificationFragment.newInstance();
}
return null;
}
Ok, so now come back to AllGenreFragment, we should create a CallBack that we implement in ContainerFragment
public interface AllGenreFragmentListener {
onItemClicked();
}
and then,
private AllGenreFragmentListener listener;
#Override public void onAttach(Context context) {
super.onAttach(context);
if (getParentFragment() instanceof AllGenreFragmentListener) {
listener = (AllGenreFragmentListener) getParentFragment();
}
}
so we have an instance of AllGenreFragmentListener, from now, whenever listener call onItemClicked, the method onItemClicked in ContainerFragment will be invoked.
Ok, let do it,
create below variable and method in your AllGenreAdapter:
private AllGenreFragmentListener listener;
public void setListener(AllGenreFragmentListener listener) {
this.listener = listener;
}
and update your ViewHodler
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Genre: " + genre_title.getText().toString(), Toast.LENGTH_SHORT).show();
if (listener != null)
listener.onItemClicked()
});
}
Don't forget call setListener method in your AllGenreFragment, so please add
#Override public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (allGenreAdapter != null) allGenreAdapter.setListener(listener);
}
That all,
I type this code by hand, not in my IDE so maybe it not compile, so please fix it if you face any compile error.
Note
If you want to keep the behavior of the BACK button, override onBackPressed in your MainActivity
#Override public void onBackPressed() {
Fragment f = getCurrentFragment();
if (f != null) {
if (f.getChildFragmentManager().getBackStackEntryCount() > 1) {
f.getChildFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
} else {
super.onBackPressed();
}
}
public Fragment getCurrentFragment() {
return (Fragment) viewPager.getAdapter()
.instantiateItem(viewPager, viewPager.getCurrentItem());
}
Also, add fragment into backStack whenever we add them to the container view (in your ContainerFragment)
private void initialLoad() {
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, AllGenreFragment.newInstance())
.addToBackStack(null)
.commit();
}
#Override public void onItemClicked() {
// change `replace` to `add` and add more `.addToBackStack(null)`
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, AllAnimeFragment.newInstance())
.addToBackStack(null)
.commit();
}
you should add a context in the constructor of your adapter
public class AllGenreAdapter(Context context) extends RecyclerView.Adapter<AllGenreAdapter.ViewHolder> {
// .......
}
then pass your activity to your adapter, use it to replace your fragment

how to pass data from single activity to multiple fragments

in my application there is an activity which is having multiple fragments and activity having a spinner when the change operation occurs on spinner then all fragment should change the value, suppose
Activity temp --> fragment A --> fragment B --> fragment C
i can pass data from activity to fragment A -->B-->C using intent but if current fragment is C and the value changes from spinner then fragment C should have latest value and when i press back button then flow is
fragment C --> fragment B --> Fragment A should have latest values,
so how to maintain multiple fragment data passing from single activity
Acivity temp.java
public interface FragmentCommunicator {
void passDataToFragment(String data);
}
private class onItemSelect implements android.widget.AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (f instanceof FragmentA) {
fragmentCommunicator.passDataToFragment(data[position]);
}
}
}
FragmentA.java
public class FragmentA extends Fragment implements temp.FragmentCommunicator {
#Override
public void passDataToFragment(String data) {
this.data = data;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
((temp) context).fragmentCommunicator = this;
}
}
Using Interface we can achieve it. Simply we can call it as Data change listener.
Just follow my code to know how it works.
1.TempActivity.java
public class TempActivity extends AppCompatActivity {
public List<FragmentCommunicator> fragmentCommunicators = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temp);
final Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new String[]{"Value One", "Value Two", "Value Three"}));
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
for (FragmentCommunicator fragmentCommunicator : fragmentCommunicators) {
fragmentCommunicator.passDataToFragment(spinner1.getSelectedItem().toString());
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
ViewPager viewPager1 = (ViewPager) findViewById(R.id.viewPager1);
FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager());
adapter.addFragment(new FirstFragment(), "FirstFragment");
adapter.addFragment(new SecondFragment(), "SecondFragment");
adapter.addFragment(new ThirdFragment(), "ThirdFragment");
viewPager1.setAdapter(adapter);
viewPager1.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (FragmentCommunicator fragmentCommunicator : fragmentCommunicators) {
fragmentCommunicator.passDataToFragment(spinner1.getSelectedItem().toString());
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
2.activity_temp.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPager1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
3.FragmentCommunicator.java
public interface FragmentCommunicator {
void passDataToFragment(String data);
}
4.FragmentAdapter.java
public class FragmentAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public FragmentAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
5.FirstFragment.java
public class FirstFragment extends Fragment implements FragmentCommunicator {
private TextView textView1;
public FirstFragment() {
// Required empty public constructor
}
#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);
textView1 = (TextView) view.findViewById(R.id.textView1);
if (getActivity() instanceof TempActivity) {
((TempActivity) getActivity()).fragmentCommunicators.add(this);
}
return view;
}
#Override
public void passDataToFragment(String data) {
textView1.setText(data);
}
}
6.fragment_first.xml
<FrameLayout 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:background="#android:color/holo_orange_light">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#android:color/black"
android:textSize="24sp" />
</FrameLayout>
7.Follow same steps for remaining fragments.
Create new fragment.
Implement FragmentCommunicator interface.
Add implemented interface in Activity’s interface list.
8.Build and run you application. We achieved.
You can grab my example project here.
Happy coding…
Please use LocalBroardCast or eventBus, both is same:
Evenbus example
Check for Observer pattern. I do this for multiple fragments of each tab. All fragments implement an interface with sendData(String data) method and MainActivity has a addListener method that adds these interfaces to list object. All fragments use(MainActivity)activity.addListener(this); to register itself as an observer.
If an event triggers sending data, using foreach loop in MainActivity send data to send all registered listeners, in this case fragments.
Like all registers i register in onResume and remove listeners(empty list) onPause methods.
I would do it like this:
Create a new interface to provide the data needed to the fragments.
for example:
public interface MyDataInterface {
Data getDate();
}
Implement the interface in your Activity:
public class MainActivity extends Activity implements MyDataInterface {
// ...
#Override
public Data getDate() {
return dataForFragments;
}
}
Now when your Fragment is attached to the Activity (it's context),
Check if the context is implementing your interface and then use it to pull data from the Activity.
public class MyFargment extends Fragment {
private Data mData;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof MyDataInterface) {
MyDataInterface myDataInterface = (MyDataInterface) context;
mData = myDataInterface.getDate();
}
}
}
And if you need the data inside your Fragment onResume() method:
#Override
public void onResume() {
super.onResume();
if (getActivity() instanceof MyDataInterface) {
MyDataInterface myDataInterface = (MyDataInterface) getActivity();
mData = myDataInterface.getDate();
}
}
/Try to implement the below code Snippet/
Make a Public String or any type of Method in your Activity atatched to Fragments
Inside your Activity:
String name = "Jack";
public String getname()
{
return name;
}
Inside your Fragment:
Activity mactivity;
MainActivity main_activity;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mactivity = getActivity();
main_activity = (MainActivity) mactivity;
String name = main_activity.getname();
}
That's all same this for all the fragments..Using this you can transfer data form Single Activity to all Multiple Attached Fragments.

Get data from fragments inside viewpager

I have a FRAGMENT with a viewpager with 7 other fragments. These fragments are used to enter user details. In the final fragment, there is a "submit" button where I need to get all the user details entered in the other fragments. How can I do this
I saw this question which didnt help. So please dont mark this question duplicate.
The base fragment:
public class Register_Layout extends Fragment implements ViewPager.OnPageChangeListener{
public Register_Layout(){}
static ViewPager viewPager1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_register_layout, container, false);
viewPager1 = (ViewPager) view.findViewById(R.id.view_pager1);
viewPager1.setOffscreenPageLimit(7);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
viewPager1.setAdapter(new MyAdapter(fragmentManager));
return view;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
if(position==0)
{
fragment = new Register();
}
if(position==1)
{
fragment = new Register_Page2();
}
if(position==2)
{
fragment = new Register_Page3();
}
if(position==3)
{
fragment = new Register_Page4();
}
if(position==4)
{
fragment = new Register_Page5();
}
if(position==5)
{
fragment = new Register_Page6();
}
if(position==6)
{
fragment = new Register_Page7();
}
return fragment;
}
#Override
public int getCount() {
return 7;
}
}
The final fragment where I should get data of all other fragments:
public class Register_Page7 extends Fragment {
public Register_Page7(){
}
EditText editText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_register_page7, container, false);
Button Previous = (Button) view.findViewById(R.id.Previous7);
Button Regiter = (Button) view.findViewById(R.id.Submit);
Regiter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setMessage("Are you sure you want to submit?");
alertDialogBuilder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
alertDialogBuilder.setNegativeButton("No,Let me check the details again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
Previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Register_Layout().viewPager1.setCurrentItem(5);
}
});
return view;
}
}
You will probably want to use the fragment manager to get all of the instantiated fragments, and loop through them to get their relevant data.
You could create a subclass of Fragment that all of the fragments would inherit from. This subclass would have a getText method(or some other type of public method), that gets the text from the EditText view.
For other types of data(like switches), you would have similar functions to get the data from the fragment.
Edited
So you could create a new fragment that is derived from Fragment.
public class BaseEntryFragment extends Fragment {
public BaseEntryFragment() {}
public String getEntryText() {}
}
Then you take your existing fragments and extend your new fragment..
public class Register_Page7 extends BaseEntryFragment {
private EditText _editText;
public Register_Page7() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
//other create view code
_editText = (EditText)FindViewById(R.id.edit_text);
}
#Override
public String getEntryText() {
return _editText.getText();
}
}
Then with your submit..
List<Fragment> fragments = getActivity().getSupportFragmentManager().getFragments();
for(Fragment frag : fragments) {
// do type checks here
BaseEntryFragment f = (BaseEntryFragment)frag;
String someValue = f.getEntryText();
}
Please note, my Java is really really rusty, so it may not be the perfect syntax. This is just some code to get you started and not intended to be copied and pasted.
i think it is easier in each fragment, you store the user data on a SharedPreference (the data structure can be a json string or whatever you like), at the end (last fragment) read the shared pref data, and perform the register
hope that helps
I recommend you to use an Activity to hold your ViewPager and declare there the variables or objects you want to save from Fragments.
In each Fragment you want to save data you have to use interface to pass the data to the Activity. Here is the way to do it: Passing data between a fragment and its container activity
Then in your last Fragment you can call (with generated getters for the variables I mentioned before) to your container Activity like this:
YourActivity yourActivity = ((YourActivity) getActivity());
int foo = yourActivity.getFooInt();
You can find fragments in your Activity and get data from each fragment by public method. Variable position is position of fragment in your viewpager
public Fragment getFragment(ViewPager container, int position) {
String name = makeFragmentName(container.getId(), position);
return mFragmentManager.findFragmentByTag(name);
}
private static String makeFragmentName(int viewId, int index) {
return "android:switcher:" + viewId + ":" + index;
}

How to call a method defined in a ListFragment from an adapter?

I've got a ListFragment and a custom adapter.
From the adapter I get the onClick event from a button defined in the rows. In the onClick method I get some id, which I'd like to pass to the ListFragment to do some stuff.
How can I call the method showTask in the ListFragment from the adapter?
listfragment
public class TaskListFragment extends ListFragment{
/* ... */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new TaskListAdapter(getActivity(), data);
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
setListAdapter(mAdapter);
}
public void showTask(long id) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
TaskFragment taskFragment = new TaskFragment();
Bundle args = new Bundle();
args.putLong("id", id);
taskFragment.setArguments(args);
ft.replace(R.id.fragment_container, taskFragment);
ft.commit();
}
}
adapter
public class TaskListAdapter extends ArrayAdapter<Task>{
/* ... */
private OnClickListener mOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
long id = (Integer) v.getTag();
// how can I call showTask(id) ?
}
};
}
A common solution is for the adapter to be an inner class of the fragment, so it can just call the method directly.
Or, pass the fragment (or some interface implemented by the fragment) to the adapter via its constructor.
Create your adapter like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new TaskListAdapter(getActivity(), data, TaskListFragment.this);
}
Which would change your adapter constructor to:
public TaskListAdapter(Context context, List<Task> data, TastListFragment fragment) {
this.fragment = fragment;
}
And now, you have an object that points to your TaskListFragment:
private OnClickListener mOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
long id = (Integer) v.getTag();
fragment.showTask(id);
}
};

Categories

Resources