How to pass data from Recyclerview to Fragment - java

I have a recyclerView populated in a Fragment and I want to Launch a new Fragment and pass data from the adapter ,I try to use Bundles but it always give a null value this my Adapter Class
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private LayoutInflater inflater;
private List<Information> mList;
private FragmentCommunication mCommunicator;
public RecyclerAdapter(Context context, List<Information> list,FragmentCommunication communication) {
inflater = LayoutInflater.from(context);
mList = list;
mCommunicator=communication;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.single_row, parent, false);
MyViewHolder holder = new MyViewHolder(view,mCommunicator);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Information current = mList.get(position);
holder.name.setText(current.name);
holder.job.setText(current.job);
FragmentB fragmentB=new FragmentB();
Bundle bundle=new Bundle();
bundle.putString("NAME",current.name);
bundle.putString("JOB",current.job);
fragmentB.setArguments(bundle);
}
#Override
public int getItemCount() {
return mList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView name;
TextView job;
FragmentCommunication mComminication;
public MyViewHolder(View itemView, FragmentCommunication Communicator) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.tv_name);
job = (TextView) itemView.findViewById(R.id.tv_gob);
mComminication=Communicator;
name.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mComminication.respond(getAdapterPosition());
}
}
and this is my new Fragment that I want to launch
public class FragmentB extends Fragment {
TextView textview;
TextView textView2;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_b,container,false);
textview= (TextView) view.findViewById(R.id.tv_name);
textView2= (TextView) view.findViewById(R.id.tv_job);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle arguments = getArguments();
if (arguments!=null){
String name= arguments.get("NAME").toString();
String job= arguments.get("JOB").toString();
textview.setText(name);
textView2.setText(job);}
}
}
this is how I connect Fragment and recyclerview Adapter
with interface
public interface FragmentCommunication {
void respond(int position);
}
and this the Fragment where the recyclerview is populated
public class RecyclerViewFragment extends Fragment {
RecyclerView mRecyclerView;
RecyclerAdapter mRecyclerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.recycler_fragment,container,false);
mRecyclerView= (RecyclerView) view.findViewById(R.id.recycler);
mRecyclerAdapter=new RecyclerAdapter(getActivity(),getData(),communication);
mRecyclerView.setAdapter(mRecyclerAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
public static List<Information> getData() {
List<Information>data=new ArrayList<>();
String[] names={"ahmed","mohammed"};
String[] jobs={"sacsd","csscs"};
for (int i=0;i<names.length;i++){
Information current=new Information();
current.name=(names[i]);
current.job=(jobs[i]);
data.add(current);
}
return data;
}
FragmentCommunication communication=new FragmentCommunication() {
#Override
public void respond(int position) {
FragmentB fragmentB=new FragmentB();
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.replace(R.id.dumper,fragmentB).commit();
}
};
}
and my mainActivity class is just add the RecyclerViewFragment
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerViewFragment fragment=new RecyclerViewFragment();
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.dumper,fragment).commit();
}
}
so what is the right way to launch fragmentB and pass the data from recyclerview Adapter to fragmentB

thank you guys for the answer,I solved the problem using an interface with String values to connect the adapter with the fragment that contains the recyclerview and the other fragment here is what I did exactly :
this is the interface
public interface FragmentCommunication {
void respond(int position,String name,String job);
}
and this is the adapter
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private LayoutInflater inflater;
private List<Information> mList;
private FragmentCommunication mCommunicator;
public RecyclerAdapter(Context context, List<Information> list,FragmentCommunication communication) {
inflater = LayoutInflater.from(context);
mList = list;
mCommunicator=communication;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.single_row, parent, false);
MyViewHolder holder = new MyViewHolder(view,mCommunicator);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Information current = mList.get(position);
holder.name.setText(current.name);
holder.job.setText(current.job);
FragmentB fragmentB=new FragmentB();
Bundle bundle=new Bundle();
bundle.putString("NAME",current.name);
bundle.putString("JOB",current.job);
fragmentB.setArguments(bundle);
}
#Override
public int getItemCount() {
return mList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView name;
TextView job;
FragmentCommunication mComminication;
public MyViewHolder(View itemView, FragmentCommunication Communicator) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.tv_name);
job = (TextView) itemView.findViewById(R.id.tv_gob);
mComminication=Communicator;
name.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mComminication.respond(getAdapterPosition(),mList.get(getAdapterPosition()).name,mList.get(getAdapterPosition()).job);
}
}
}
the fragment that contains the recyclerview
public class RecyclerViewFragment extends Fragment {
RecyclerView mRecyclerView;
RecyclerAdapter mRecyclerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.recycler_fragment,container,false);
mRecyclerView= (RecyclerView) view.findViewById(R.id.recycler);
mRecyclerAdapter=new RecyclerAdapter(getActivity(),getData(),communication);
mRecyclerView.setAdapter(mRecyclerAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
public static List<Information> getData() {
List<Information>data=new ArrayList<>();
String[] names={"ahmed","mohammed"};
String[] jobs={"sacsd","csscs"};
for (int i=0;i<names.length;i++){
Information current=new Information();
current.name=(names[i]);
current.job=(jobs[i]);
data.add(current);
}
return data;
}
FragmentCommunication communication=new FragmentCommunication() {
#Override
public void respond(int position,String name,String job) {
FragmentB fragmentB=new FragmentB();
Bundle bundle=new Bundle();
bundle.putString("NAME",name);
bundle.putString("JOB",job);
fragmentB.setArguments(bundle);
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.replace(R.id.dumper,fragmentB).commit();
}
};
}
this is the fragmentB where I get the Strings from the Adapter
public class FragmentB extends Fragment {
TextView textview;
TextView textview2;
String name;
String job;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
name=getArguments().getString("NAME");
job=getArguments().getString("JOB");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_b,container,false);
textview= (TextView) view.findViewById(R.id.getName);
textview2= (TextView) view.findViewById(R.id.getJob);
textview.setText(name);
textview2.setText(job);
return view;
}
}

If you are working with kotlin, the solution is much simpler.
Original Answer here
pass the function val itemClick: (Int) -> Unit to your adapter.
class MyRecyclerViewAdapter(params , val itemClick: (Int) -> Unit): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
internal inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
...
itemView.setOnClickListener( {itemClick(layoutPosition)} )
}
}
In your fragment use the returned value position
val myAdapter = MyRecyclerViewAdapter(params) { position ->
// do something
}

Either creating a listener interface in the adapter or using regular old getters, if I understand your question correctly.

You need to pass the Bundle to the fragment through the setArguments(Bundle args) method. Since you have not set arguments, the bundle you try to extract in your Fragment resolves to null.

You have the right idea with using a Bundle. You just need to pass it to the Fragment by calling setArguments(). Then you retrieve the Bundle in your Fragment with getArguments().
Note that instead of mList.get(position).name, you can do current.name. Similarly for job.
Another part of the problem is that you create FragmentB on two different places. In one place you also call setArguments() but do not show the fragment. In the other you show the fragment but do not call setArguments(). If you really need to do this from multiple parts of your code you should write a method to avoid these inconsistencies.

Related

TabLayoutMediator with ViewPager2 is synchronizing wrong on tab selection -Android java

ViewPager2 is scrolling to the wrong page when I am selecting a tab from a far position. Swiping and selecting tab of loaded pages working fine. The error is only happening when the page is not loaded and scrolling animation is active. I have created a large viewpager2 with 100 pages containing Recyclerview.
My Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabLayout tabLayout = findViewById(R.id.tabLayout);
ViewPager2 viewPager = findViewById(R.id.viewPager2);
viewPager.setAdapter(new viewPagerAdapter(this));
new TabLayoutMediator(tabLayout, viewPager, true, true,
((tab, position) -> tab.setText("Page: " + position))).attach();
}
private class viewPagerAdapter extends FragmentStateAdapter {
public viewPagerAdapter(FragmentActivity fa) {
super(fa);
}
#Override
public Fragment createFragment(int position) {
Fragment fragment = new itemFragment();
Bundle args = new Bundle();
args.putInt(itemFragment.ARG_PARAM1, position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getItemCount() {
return 100;
}
}
}
My Fragment
public class itemFragment extends Fragment {
public static final String ARG_PARAM1 = "parram1";
int pagePosition;
public itemFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pagePosition = getArguments().getInt(ARG_PARAM1);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frgment_item, container, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView textView = view.findViewById(R.id.textView);
textView.setText("Page - " + pagePosition);
RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setAdapter(new myAdapter());
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 16));
}
private class myAdapter extends RecyclerView.Adapter<Myvh> {
#Override
public Myvh onCreateViewHolder(ViewGroup parent, int viewType) {
return new Myvh(new TextView(getContext()));
}
#Override
public void onBindViewHolder(Myvh holder, int position) {
int codepoint=pagePosition*700 + position;
char[] ch=Character.toChars(codepoint);
holder.textView.setText(String.valueOf(ch));
}
#Override
public int getItemCount() { return 700; }
}
private class Myvh extends RecyclerView.ViewHolder {
TextView textView;
public Myvh(View itemView) {
super(itemView);
textView = (TextView) itemView;
}
}
}
I have also tried Recyclerview adapter instead of FragmentStateAdapter and getting same problem.
I have found some solution but not sufficient.
Those are:
Using old ViewPager(deprecated)
Using viewPager.setOffscreenPageLimit(100); (taking huge time to load activity)
Disabling smoothscroll ( looks awful when swiping)

My recycler view not shown for the first time in fragment

I am a beginner at android development. I tried to display data on Recycle View using MVVM. When I opened the fragment the first time it is empty, the second time it showed data. Adapter not called the first time. How to fix this.
Fragment class
public class fragmentEmployee extends Fragment {
private FragmentEmployeeBinding binding;
private ViewGroup viewGroup;
private View view;
private RecyclerView mRecycleView;
private UserAdapter mAdapter;
private EmployeeRegisterViewModel viewModel;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_employee, viewGroup, false);
view = binding.getRoot();
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Toast.makeText(getContext(), "onViewCreated", Toast.LENGTH_SHORT).show();
mRecycleView = binding.recyleViewEmployee;
viewModel = new ViewModelProvider(this).get(EmployeeRegisterViewModel.class);
viewModel.init();
initRecycleView();
viewModel.getEmployee().observe(getViewLifecycleOwner(), new Observer<List<employeeModel>>() {
#Override
public void onChanged(List<employeeModel> employeeModels) {
mAdapter.notifyDataSetChanged();
}
});
}
private void initRecycleView() {
mAdapter = new UserAdapter(getContext(), viewModel.getEmployee().getValue());
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
mRecycleView.setLayoutManager(layoutManager);
mRecycleView.setAdapter(mAdapter);
}
}
UserAdapter class
public class UserAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
public List<employeeModel> employeeModelList= new ArrayList<>();
public Context context1;
public UserAdapter(Context context,List<employeeModel> employeeModels){
employeeModelList = employeeModels;
context1 = context;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem,parent,false);
ViewHolder viewHolder=new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
(ViewHolder)holder).username.setText(employeeModelList.get(position).getName());
}
#Override
public int getItemCount() {
return employeeModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView username;
public ViewHolder(#NonNull View itemView) {
super(itemView);
username=itemView.findViewById(R.id.userText);
}
}
}
Try reordering like this.
Remove
mAdapter = new UserAdapter(getContext(), viewModel.getEmployee().getValue());
from initRecycleView
mAdapter = new UserAdapter(getContext(), viewModel.getEmployee().getValue());
viewModel.getEmployee().observe(getViewLifecycleOwner(), new Observer<List<employeeModel>>() {
#Override
public void onChanged(List<employeeModel> employeeModels) {
mAdapter.notifyDataSetChanged();
}
});
initRecycleView();
mAdapter.notifyDataSetChanged();
Above method will work if the list declared inside adapter has any change. So, calling above method without changing adapter's list is useless.
Add a method to UserAdapter class to update list data. Like:
public void updateData(List<employeeModel> updatedList){
employeeModelList.clear();
employeeModelList.addAll(updatedList);
notifyDataSetChanged();
}
And call this method inside observer. Like:
viewModel.getEmployee().observe(getViewLifecycleOwner(), new
Observer<List<employeeModel>>() {
#Override
public void onChanged(List<employeeModel> employeeModels) {
mAdapter.updateData(employeeModels);
}
});
where are you get your network data?
If your get in here -> viewModel.init();
I think it just timing problem.
Just change code sequence
initRecycleView();
viewModel.getEmployee().observe(getViewLifecycleOwner(), new Observer<List<employeeModel>>() {
#Override
public void onChanged(List<employeeModel> employeeModels) {
mAdapter.notifyDataSetChanged();
}
});
viewModel.init();

How I can connect two fragments and write listeners in adapter

I have 2 fragments. When I click like in one fragment, in the second fragment must appear news, which I liked.
Here is my favourite fragment I have a method Add()
RecyclerView recyclerView;
private FavouriteListAdapter adapter;
private List<News> newsList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment_favourite, container,
false);
recyclerView = rootView.findViewById(R.id.recycler_favourite);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
newsList= new ArrayList<>();
adapter = new FavouriteListAdapter(newsList);
recyclerView.setAdapter(adapter);
return rootView;
}
public void addNews(News news) {
newsList.add(news);
recyclerView.getAdapter().notifyItemInserted(newsList.size() - 1);
}
In Home Fragment I use interface listener and add
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_home);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
listener = new NewsListAdapter.ItemClickListener() {
#Override
public void likeClick(int position, News item) {
add.respond(item);
newsListAdapter.notifyItemChanged(position);
}
};
add = new NewsListAdapter.Add() {
#Override
public void respond(News news) {
((MainActivity) getActivity()).respond(news);
}
};
newsListAdapter = new NewsListAdapter(newsGenerator(), listener, add);
recyclerView.setAdapter(newsListAdapter);
return rootView;
}
Adapter for Home
#Override
public void onBindViewHolder(#NonNull NewsListAdapter.NewsViewHolder holder, final int position)
{
final News news = mainList.get(position);
holder.theme.setText(news.getTheme());
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener!=null){
listener.likeClick(position,news);
}
}
});
#Override
public int getItemCount() {
return mainList.size();
}
public class NewsViewHolder extends RecyclerView.ViewHolder {
private TextView theme;
private ImageButton like;
public NewsViewHolder(#NonNull View itemView) {
super(itemView);
theme = itemView.findViewById(R.id.theme);
like = itemView.findViewById(R.id.like);
}
}
interface ItemClickListener {
void likeClick(int position, News item);
}
public interface Add{
void respond(News news);
}
Adaper for favourites. Adapter favourites contains News and we call method add here in MainActivity
#NonNull
#Override
public FavouriteListAdapter.FavouriteNewsHolder onCreateViewHolder(#NonNull ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news, null,false);
RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
view.setLayoutParams(params);
return new FavouriteNewsHolder(view);
}
#Override
public void onBindViewHolder(#NonNull FavouriteListAdapter.FavouriteNewsHolder holder, int
position) {
final News news = newsList.get(position);
holder.theme.setText(news.getTheme());
}
#Override
public int getItemCount() {
return newsList.size();
}
public class FavouriteNewsHolder extends RecyclerView.ViewHolder {
TextView theme;
ImageButton like;
public FavouriteNewsHolder(#NonNull View itemView) {
super(itemView);
theme = itemView.findViewById(R.id.theme);
like = itemView.findViewById(R.id.like);
}
}
in Activity I overwrite my method. When I execute my programm and click button click the program stopping
#Override
public void respond(News news) {
FavouriteFragment f = (FavouriteFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_container);
f.addNews(news);
}
In logcat:
2020-03-24 21:55:12.367 13933-13933/com.example.newsfragment E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.newsfragment, PID: 13933
java.lang.ClassCastException: com.example.newsfragment.HomeFragment cannot be cast to com.example.newsfragment.FavouriteFragment
at com.example.newsfragment.MainActivity.respond(MainActivity.java:50)
at com.example.newsfragment.HomeFragment$2.respond(HomeFragment.java:51)
at com.example.newsfragment.HomeFragment$1.likeClick(HomeFragment.java:43)
at com.example.newsfragment.NewsListAdapter$1.onClick(NewsListAdapter.java:61)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
The 50 line in MainActivity
public void respond(News news) {
FavouriteFragment f = (FavouriteFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_container);
f.addNews(news);
}
Use the eventBus for this type of communication with a fragment. Using https://github.com/greenrobot/EventBus this lib I have implemented the same things(When like a post in homeFragment at that time I want to like that post in multiple fragments)
Register and unregister EventBus
#Override public void onStart() {
super.onStart();
EventBus.getDefault().register(this); }
#Override public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this); }
Post events:
EventBus.getDefault().post(new MessageEvent());

How to create an Intent within a fragment class

I have managed to create a tabbed activity using recycle view and have made a list-view in each fragment, now I have the lists I need to make the cards in the fragment clickable and create an intent to start a new activity. I have tried on-click method and onListItemClick even though I knew that would not work.
Basically I need to create one more layer of lists for each fragment which will lead to a list of actions (webviews, Maps, and information).
Example Code is below
ublic class LOneFragment extends Fragment {
public LOneFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
MyAdapter adapter = new MyAdapter(new String[]{"League One News", "AFC Wimbledon", "Blackburn Rovers", "Blackpool", "Bradford City", "Bristol Rovers", "Bury", "Charlton Athletic", "Doncaster Rovers", "Fleetwood Town",
"Gillingham", "Milton Keynes Dons", "Northampton Town", "Oldham Athletic", "Oxford United", "Peterborough United", "Plymouth Argyle", "Portsmouth", "Rochdale", "Rotherham United",
"Scunthorpe United", "Shrewsbury Town", "Southend United", "Walsall", "Wigan Athletic"});
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView;
}
public void onListItemClick(ListView l, View v, int position, long id) {
if (position == 3) {
Intent intent = new Intent(getContext(), Bradford.class);
startActivity(intent);
}
My adaptor class
public class MyAdapter extends RecyclerView.Adapter {
private String[] mDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
}
}
public MyAdapter(String[] myDataset){
mDataset = myDataset;
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.mTextView.setText(mDataset[position]);
}
#Override
public int getItemCount() { return mDataset.length; }
}
This works perfect for me.
1) Create method in viewholder class which will take position, get array item from position and use the way you like.
2) Access it in onBindViewHolder method with itemView instance which is the full row at given position,
public class MyAdapter extends RecyclerView.Adapter {
private String[] mDataset;
public MyAdapter(String[] myDataset){
mDataset = myDataset;
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.mTextView.setText(mDataset[position]);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.bindCliks(groupItem);
}
});
#Override
public int getItemCount() { return mDataset.length; }
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
}
public void bindCliks(int position) {
Intent intent = new Intent(context,
OtherActivity.class);
//use number here to get your string item and use it to other activity.
context.startActivity(intent);
}
}

Pass object from GridView of Fragment to ListView of another Fragment

I have a GridView in FragmentA containing all objects. When the user tap on each object, these objects are added into ListView of FragmentB.
Note that FragmentA and FragmentB are both in the same Activity, side by side.
I have tried using Bundle to send object from FragmentA to FragmentB but I was stucked as I have no idea how FragmentB is going to know that a new object has been added.
Bundle object is sent from ProductGridAdapter (under FragmentA) and receiver will be FragmentB where FragmentB will update the ListView for the latest objects added by FragmentA
Here is my code:
ProductGridAdapter.java
public class ProductGridAdapter extends ArrayAdapter<Product> {
private List<Product> productList;
private Context context;
public ProductGridAdapter(Context context, int resource,
List<Product> objects) {
super(context, resource, objects);
this.context = context;
this.productList = objects;
}
#Override
public int getCount() {
return ((null != productList) ?
productList.size() : 0);
}
#Override
public Product getItem(int position) {
return ((null != productList) ?
productList.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(null == view) {
view = layoutInflater.inflate(R.layout.grid_product, null);
}
final Product product = productList.get(position);
if(product != null) {
final CardView productGridLayout = (CardView) view.findViewById(R.id.product_gridlayout);
final TextView productName = (TextView) view.findViewById(R.id.product_name);
final ImageView productIcon = (ImageView) view.findViewById(R.id.product_icon);
productName.setText(product.getName());
productIcon.setImageDrawable(product.getDrawable());
productGridLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentB fragment = new FragmentB();
Bundle bundle = new Bundle();
bundle.putSerializable("product", product);
fragment.setArguments(bundle);
}
});
}
return view;
}
}
FragmentA.java
public class FragmentA extends Fragment {
private GridView gridView;
private ProductGridAdapter productAdapter;
public FragmentA() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_product_display, container, false);
gridView = (GridView) rootView.findViewById(R.id.gridview);
productAdapter = new ProductGridAdapter(getActivity(), R.layout.fragment_product_display, getProductList());
gridView.setAdapter(productAdapter);
gridView.destroyDrawingCache();
gridView.setVisibility(GridView.INVISIBLE);
gridView.setVisibility(GridView.VISIBLE);
return rootView;
}
}
FragmentB.java
public class FragmentB extends Fragment {
private ListView listView;
private PaymentListAdapter paymentAdapter;
private LinearLayout button;
private ArrayList<String> arr;
public FragmentB() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_payment, container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);
paymentAdapter = new PaymentListAdapter(getActivity(), R.layout.fragment_payment, getProductList());
// button = (LinearLayout) rootView.findViewById(R.id.payment);
listView.setAdapter(paymentAdapter);
Bundle bundle = this.getArguments();
Product product = (Product) bundle.getSerializable("product");
return rootView;
}
you can have two common method in interface class in main activity, To update view in both fragment,When some changes happens in FragmentA you have to notify that changes to main activity then main activity should communicate to FragementB about that changes.try to do as like this,Hope this will help you.Happy Coding!

Categories

Resources