How can I send the data fragment to fragment with FirebaseRecyclerAdapter - android

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

Related

android fragment view throw null pointer exception even after being initialized in onCreateView

here i have a fragment interaction, where if recycler view item get clicked it passed data to MainActivity and then MainActivity call DetailFragment.updateText() method to update it's view but the views are not initialized even though i did that in onViewCreated(), if DetailFragment.updateText() is getting called before views are initialized then how can i make sure they get called after views have been initialized.
* note i added the DetailFragment to a DetailActivity through XML fragment tag, and the same for ListFragment and MainActivity
MainActivity
public class MainActivity extends AppCompatActivity implements ListFragment.Listener {
// the method to be called when an item in recycler view is clicked
// so i can pass this data to DetailFragment
#Override
public void listenerMethod(String firstName, String lastName) {
DetailFragment detailFragment = new DetailFragment();
detailFragment.updateText(firstName, lastName);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
ListFragment
public class ListFragment extends Fragment {
private static final String TAG = "ListFragment";
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
// fragment communication interface
public interface Listener {
void listenerMethod(String firstName, String lastName);
}
private Listener listener;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
this.listener = (Listener) context;
} catch (ClassCastException e) {
Log.d(TAG, "onAttach: "+ e.getMessage());
}
}
public ListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
recyclerView = getView().findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// some dummy data to fill the recycler view
ArrayList<User> users = new ArrayList<>();
users.add(new User("hiwa", "jalal"));
users.add(new User("mohammed", "abdullah"));
recyclerViewAdapter = new RecyclerViewAdapter(users, getActivity(), listener);
recyclerView.setAdapter(recyclerViewAdapter);
}
}
RecyclerViewAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private List<User> userList;
private Context context;
private ListFragment.Listener listener;
public RecyclerViewAdapter(List<User> userList, Context context, ListFragment.Listener listener) {
this.userList = userList;
this.context = context;
this.listener = listener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_row
, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
User user = userList.get(position);
holder.tvFirstName.setText(user.getFirstName());
holder.tvLastName.setText(user.getLastName());
}
#Override
public int getItemCount() {
return userList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvFirstName;
public TextView tvLastName;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvFirstName = itemView.findViewById(R.id.row_first_name);
tvLastName = itemView.findViewById(R.id.row_last_name);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
User user = userList.get(getAdapterPosition);
listener.listenerMethod(user.getFirstName(), user.getLastName());
}
});
}
}
}
DetailFragment
public class DetailFragment extends Fragment {
private TextView tvFirstName;
private TextView tvLastName;
public DetailFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_detail, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tvFirstName = view.findViewById(R.id.detail_frag_first_name);
tvLastName = view.findViewById(R.id.detail_frag_last_name);
}
// update the details fragment views
public void updateText(String firstName, String lastName) {
tvFirstName.setText(firstName);
tvLastName.setText(lastName);
}
}
activity_main
<?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"
tools:context=".MainActivity">
<fragment
android:id="#+id/main_fragment_list"
android:name="com.example.peacewithfragments.ListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
activity_detail
<?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"
tools:context=".DetailsActivity">
<fragment
android:id="#+id/detailsActivity_fragment_container"
android:name="com.example.peacewithfragments.DetailFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
You create a new instance of the DetialsFragment every time you trigger the method of your listener. If you have defined the fragment in your layout xml, you must get the correct instance of the fragment from the fragmentmanager (or supportFragmentManager as you are using AppCompatActivity.
#Override
public void listenerMethod(String firstName, String lastName) {
// find the fragment by its id, sometihng like that
// id is the fragments id you defined in the layout xml
DetailsFragment detailFragment = (DetailsFragment)supportFragmentManager.findFragementById(R.id.frag_details);
detailFragment.updateText(firstName, lastName);
}
You can't directly access DetailFragment from your MainActivity as it's not part of MainActivity. So, first you have to navigate to DetailActivity and then access DetailFragment. Check below:
public class MainActivity extends AppCompatActivity implements ListFragment.Listener {
private DetailFragment detailFragment;
#Override
public void listenerMethod(String firstName, String lastName) {
if(detailFragment != null) {
detailFragment.updateText(firstName, lastName);
} else {
Intent detailIntent = new Intent(this, DetailsActivity.class);
detailIntent.putExtra("FirstName", firstName);
detailIntent.putExtra("LastName", lastName);
startActivity(detailIntent);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = findViewById(R.id.tablet_detail_container);
if (view != null) {
detailFragment = new DetailFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.tablet_detail_container, detailFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
Then in your DetailsActivity accept those extra and pass it to DetailFragment like below:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
...
String firstName = getIntent().getStringExtra("FirstName");
String lastName = getIntent().getStringExtra("LastName");
DetailFragment detailFragment = getSupportFragmentManager().findFragmentById(R.id.detailsActivity_fragment_container);
if(detailFragment != null)
detailFragment.updateText(firstName, lastName);
}

how to call main activity code in a recycler view that is inside a fragment?

i have already got all things ready set-up my fragment communication, but my only problem is how can i make the recycler view itemVitem.setOnClickListener call the overridden interface method in the main activity so i can get that data and create an intent with to go to detail activity or update detail fragment for dual-pane layout, more explanation is provided with comments on code below.
MainActivity
public class MainActivity extends AppCompatActivity implements ListFragment.Listener {
// the method to be called when an item in recycler view is clicked
// so i can pass this data to DetailFragment
#Override
public void listener(String firstName, String lastName) {
DetailFragment detailFragment = new DetailFragment();
detailFragment.updateText(firstName, lastName);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
RecyclerViewAdapter
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvFirstName;
public TextView tvLastName;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvFirstName = itemView.findViewById(R.id.row_first_name);
tvLastName = itemView.findViewById(R.id.row_last_name);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// how to call the "listener()" method in main activity
}
});
}
the fragment containing the recycler view
public class ListFragment extends Fragment {
private static final String TAG = "ListFragment";
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
// fragment communication interface
public interface Listener {
void listener(String firstName, String lastName);
}
private Listener listener;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
this.listener = (Listener) context;
} catch (ClassCastException e) {
Log.d(TAG, "onAttach: "+ e.getMessage());
}
}
public ListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
recyclerView = getView().findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// some dummy data to fill the recycler view
ArrayList<User> users = new ArrayList<>();
users.add(new User("hiwa", "jalal"));
users.add(new User("mohammed", "abdullah"));
recyclerViewAdapter = new RecyclerViewAdapter(users, getActivity());
recyclerView.setAdapter(recyclerViewAdapter);
}
}
DetailFragment
public class DetailFragment extends Fragment {
private TextView tvFirstName;
private TextView tvLastName;
public DetailFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_detail, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tvFirstName = view.findViewById(R.id.detail_frag_first_name);
tvLastName = view.findViewById(R.id.detail_frag_last_name);
}
// update the details fragment views
public void updateText(String firstName, String lastName) {
tvFirstName.setText(firstName);
tvLastName.setText(lastName);
}
}
Pass listener to your RecyclerViewAdapter and use this to call the callback
recyclerViewAdapter = new RecyclerViewAdapter(users, getActivity(), listener);
Update RecyclerViewAdapter like below
class RecyclerViewAdapter {
private Listener mListener;
....
public RecyclerViewAdapter(ArrayList<User> users, Context context, Listener listener) {
....
mListener = listener;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
....
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.listener(first_name. last_name);
}
});
....
}
....
}
Create Method in adapter class.
private Listener mListener;
public void setListener(Listener listener){
mListener = listener
}
public void removeListener(){
mListener = null;
}
Inside Fragment class, set listener like below.
recyclerViewAdapter = new RecyclerViewAdapter(users, getActivity());
recyclerViewAdapter.setListener(listener);
In ViewHolder
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.listener(first_name. last_name);
}
});
Also in OnDestroy or OnDestroyView() of fragment, call
removeListener() to avoid memory leak.

Fragment retrieve data from recycler view

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
}
});
}

Interface inside fragment returns null value

In onAttach() method communicator =(Communicator) activity returns null. When i click on the Image View it shows the value of communicatior is null.
I have check but not able to resolve the problem. Here in the fragment when click on the image view some data should transfer to the activity. But the reference variable of Interface Commnunicator communicator gets the null value in onAttch()
public class SendFragment extends Fragment {
ImageView imgContact;
TextView tvContactName;
String username;
Communicator communicator;
public interface Communicator {
public void sendDataToActivity(String s);
}
public static final String TAG = SendFragment.class.getSimpleName();
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Communicator) {
communicator = (Communicator) context;
} else {
throw new IllegalArgumentException(
"Must implement " + TAG + ".Communicator on caller Activity");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_send, container, false);
imgContact = (ImageView) view.findViewById(R.id.contactbook);
tvContactName = (TextView) view.findViewById(R.id.tvcontactname);
if(!TextUtils.isEmpty(username)) {
username = getArguments().getString("username").toString();
tvContactName.setText(username);
}
listeners();
return view;
}
private void listeners() {
imgContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
communicator.sendDataToActivity(Constants.selectUserName);
Intent intent = new Intent(getActivity(), AllContactsListActivity.class);
startActivity(intent);
}
});
}
}
Now the below is my Code of the activity..
public class AllContactsListActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SendFragment.Communicator,RecyclerViewAdapter.OnItemClick {
Context context;
RecyclerView recyclerView;
RecyclerView.Adapter recyclerViewAdapter;
RecyclerView.LayoutManager recylerViewLayoutManager;
ImageButton btnSliding_common;
DrawerLayout drawer;
NavigationView navigationView;
String sendFragmentStringFlag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_contacts_list);
setIds();
listeners();
}
private void listeners() {
recyclerViewAdapter = new RecyclerViewAdapter(AllContactsListActivity.this, subjects, emails, address,this);
recyclerView.setAdapter(recyclerViewAdapter);
RecyclerView.ItemDecoration itemDecoration =
new DividerItemDecoration(this, LinearLayoutManager.VERTICAL);
recyclerView.addItemDecoration(itemDecoration);
btnSliding_common.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawer.openDrawer(GravityCompat.END);
}
});
}
private void setIds() {
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
btnSliding_common = (ImageButton) findViewById(R.id.btnSliding_contact);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout_contact);
navigationView = (NavigationView) findViewById(R.id.nav_view_contact);
recylerViewLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(recylerViewLayoutManager);
}
#Override
public void sendDataToActivity(String sendMoneyflag) {
sendFragmentStringFlag=sendMoneyflag;
}
#Override
public void onClick(String username) {
if(!TextUtils.isEmpty(sendFragmentStringFlag)) {
if (sendFragmentStringFlag.equals(Constants.selectUserName)) {
Toast.makeText(this, "You clicked " + username, Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString("username", username);
SendFragment sendFragment = new SendFragment();
sendFragment.setArguments(bundle);
finish();
}
}else{
Toast.makeText(this, "USER NAME" + username, Toast.LENGTH_SHORT).show();
}
}
}
The problem probably because the host activity didn't implement the Fragment interface.
You're trying to attach the interface with the following method:
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
communicator = (Communicator) activity;
} catch (Exception e){}
}
But you didn't handle the Exception correctly. So, you don't know when the interface is set correctly. And you also override onAttach(Activity activity) which is now deprecated.
You need to change the code as following:
public static final String TAG = YourFragment.class.getSimpleName();
...
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Communicator) {
communicator = (Communicator) context;
} else {
throw new IllegalArgumentException(
"Must implement " + TAG + ".Communicator on caller Activity");
}
}
It will throw error if your host activity didn't implement the interface.
You also need to attach the fragment to your activity by using FragmentTransaction. Something like this:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SendFragment sendFragment = new SendFragment();
fragmentTransaction.add(R.id.fragment_container, sendFragment);
fragmentTransaction.commit();

RecyclerView.Adapter onClick ClassCastException

I'm trying to load a Fragment inside an Activity and I was able to load the items. Now, what I want to do is to click the items on the list and pass it to the DetailsView.class which is a Fragment that will receive the bundle data. But everytime I click on the item I always get an error. Below is the logcat error that I'm getting
Logcat Error
java.lang.ClassCastException: com.test.example.LoadAFragment cannot be cast to com.test.example.MainActivity at com.test.example.controller.DetailsView.onCreateView(DetailsView.java:178)
line java:178
MainActivity activity = ((MainActivity) getActivity());
LoadAFragment.class
public class LoadAFragment extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_layout);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.frame_container, myFragment);
fragmentTransaction.commit();
}
}
RecyclerView Adapter
public class MyFragmentAdapter extends RecyclerView.Adapter <RecyclerView.ViewHolder> {
private List<ListModel> list;
private Context mContext = null;
private DetailsView detailsView;
public MyFragmentAdapter(Context context, List<ListModel> list) {
mContext = context;
this.list = list;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
final ListModel list = list.get(holder.getAdapterPosition());
String mID = list.getID();
final int id = Integer.valueOf(mID );
((MyViewHolder) holder).title.setText(list.getTitle());
((MyViewHolder) holder).caption.setText(list.getCaption());
((MyViewHolder) holder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = ((Activity) mContext).getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Bundle bundle = new Bundle();
bundle.putInt("id", id);
detailsView = new DetailsView ();
detailsView.setTitle(title);
detailsView.setArguments(bundle);
transaction.replace(R.id.frame_container, detailsView);
transaction.addToBackStack("list");
transaction.commit();
}
});
}
#Override
public int getItemCount() {
return (list != null? list.size():0);
}
private class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public TextView caption;
MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
caption = (TextView) itemView.findViewById(R.id.caption );
}
}
}
MyFragment.class
public class MyFragment extends Fragment{
List<ListModel> list;
RecyclerView mRecyclerView;
MyFragmentAdapter myFragmentAdapter;
ListDb listDb;
public MyFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
listDb = new ListDb(getActivity());
list = listDb.getList();
myFragmentAdapter = new MyFragmentAdapter (getActivity(), list);
mRecyclerView.setAdapter(myFragmentAdapter);
return rootView;
}
}
DetailsView.class
public class DetailsView extends Fragment{
private MainActivity activity;
Bundle b;
public DetailsView() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
b = savedInstanceState.getBundle("save");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
activity = ((MainActivity) getActivity());
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (b != null) {
setTitle(b.getString("title"));
id = b.getInt("id");
}
if (b != this.getArguments().getInt("id")) {
b = this.getArguments().getInt("id");
//get data from id
}
}
}
The best and cleanest solution would be to pass a listener to the adapter.
public interface MyClickListener {
void onResult(Data data);
}
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public MyAdapter(Context context, MyClickListener listener, List<ListModel> list) {
mContext = context;
this.list = list;
this.listener = listener;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
Data data = getData(position);
//bind views
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onResult(data);
}
});
}
}
Have the Fragment implement the listener and create the new adapter.
public class MyFragment extends Fragment implements MyClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyAdapter adapter = new MyAdapter(getActivity(),this,listData);
}
#Override
public void onResult(Data data) {
//do work after an item is clicked
}
}
Cast getActivity() to 'LoadAFragment' instead of 'MainActivity' in DetailsView.java. This way:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
activity = ((LoadAFragment) getActivity());
return rootView;
}
try this way to get Reference of MainActivity in your DetailViewFragment
private MainActivity parent_activity;
#Override
public void onAttach(Activity activity)
{
parent_activity = (MainActivity.class.isAssignableFrom(activity
.getClass())) ? (MainActivity) activity : null;
super.onAttach(activity);
}
#Override
public void onDetach()
{
parent_activity = null;
super.onDetach();
}
Now use the reference using:
if(parent_activity!=null)
{
parent_activity.someMethod();
}

Categories

Resources