Android: Communication between fragments in a view pager - java

Just for reference I am been trying to follow the answer to this question
Basic Communication between two fragments
I have 2 Fragments within a ViewPager Adapter along with an Actionbar.
What I have is one fragment produces some data which can (if chosen) inserted to an SQLite table.
The second Fragment simply displays all data in the table, however I am trying to make some communication that as soon as Fragment 1 inserts data into the SQLite table. Fragment 2 is called to refresh its select query (as in do the query again) to automatically show the latest data. At the moment this is manually done with a button which I feel is not great.
This is my interface in Fragment 1
onNumbersSavedListener mCallback;
public interface onNumbersSavedListener
{
public void RequestQueryRefresh();
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
try
{
mCallback = (onNumbersSavedListener) activity;
}
catch(ClassCastException e)
{
e.printStackTrace();
}
}
This is the main Activity which contains the ViewPager and implements the interface
public class MainActivity extends FragmentActivity implements TabListener, GenerateFragment.onNumbersSavedListener
This is the main problem I am having which I do not have IDs for the fragments which answer referred in the link stated above does so.
#Override
public void RequestQueryRefresh() {
// TODO Auto-generated method stub
}
TLDR: I am just looking for an easy and clean way for as soon as Fragment 1 saves into DB, fragment 2 updates its list view by re-running its query.

see more about otto lib here : http://square.github.io/otto/
Edited:
public class FragmentA extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
public void saveData(){
//save datas before
BusProvider.getInstance().post(new EventUpdateOtto());
}
}
public class EventUpdateOtto{
public EventUpdateOtto(){
}
}
public class FragmentB extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
#Subscribe
public void subUpdateList(EventUpdateOtto mEventUpdateOtto){
//update yout list here
}
#Override
public void onResume() {
BusProvider.getInstance().register(this);
super.onResume();
}
#Override
public void onPause() {
BusProvider.getInstance().unregister(this);
super.onPause();
}
}
public class BusProvider {
private static final Bus BUS = new Bus();
public static Bus getInstance() {
return BUS;
}
private BusProvider() {
// No instances.
}
}

In your case you can improve your interface:
public interface onNumbersSavedListener
{
public void RequestQueryRefresh(Bunde bundle/*or something other*/);
}

If you are using a cursor loader, the change should automatically be reflected in the fragment displaying it. However, the fragment that wants immediate updates whenever the table is changed can register as an observer to that table:
// observer to the table
class MyObserver extends ContentObserver {
final Handler mHandler;
public MyObserver(Handler handler) {
super(handler);
// I used a handler to get back to my UI thread
mHandler = handler;
}
#Override
public void onChange(boolean selfChange) {
this.onChange(selfChange, null);
}
#Override
public void onChange(boolean selfChange, Uri uri) {
Log.i(TAG, "MyObserver: onChange");
// do what you want to do - this is what I implemented
mHandler.post(myRunnable);
}
}
Then, register it:
mHandler = new Handler();
mObserver = new MyObserver(mHandler);
ContentResolver resolver = getContext().getContentResolver();
resolver.registerContentObserver(uri, false, mEventLogObserver);
The other fragment should then do a notify:
getContext().getContentResolver().notifyChange(uri, null);
The key is the uri - one watches it, the other notifies.

Related

where and how to put a onclick in recyclerview to get the result in the activity that contain the fragment?

In my app, I have an activity that uses fragment(s). In one such fragment, I am using a recyclerview.
I just want to add (one or more) onClick(s) whose action I can process in the fragment or in the activity as appropriate.
I searched a lot. I found many solutions, but none that seems to me to really respond to my case, which is however not so exceptional.
I found a lot of solutions with the onClick in OnBindviewHolder. However, I also read very often that this solution was not acceptable because it consumed unnecessary resources.
I found a solution (https://openclassrooms.com/en/courses/4568576-recover-and-display-distant-data/4893791-interact-with-the-recyclerview) using a itemClickSupport class that works, but I don't know how to fully exploit it.
So, I'm going around in circles, and I don't know which track I should go to, without wasting my time unnecessarily realizing at the end that I didn't go in the right direction.
Edit :
Another solution that seems perfect to me (https://openclassrooms.com/fr/courses/4568596-construisez-une-interface-utilisateur-flexible-et-adaptative/4789616-creez-votre-premiere-application-avec-des-fragments), automatically creates it in the fragment by a callback, BUT, I don't know how to get it in the parent activity.
What I really want is :
on smartphone :
an activity that open a fragment 1 with a recyclerview
another activity with another fragment (with another recyclerview) opened by a click on a button in the recyclerview from the fragment 1
on tablet (with another layout) :
an activity that open both fragments, and the button in the fragment/recyclerview 1 populate the fragment/recyclerview 2.
I realize that I have a lot of trouble explaining what I want, and that my problem to find the solution probably comes from there.
I think I finally found a solution that can be useful :
activity:
public class MainActivity extends FragmentActivity implements MainFragment.SampleOnClickedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void sampleOnClicked(int position) {
Log.e("TAG", " from activity / position:" + position);
}
}
fragment:
public class MainFragment extends Fragment implements SampleAdapter.SampleRecyclerViewHolder.SampleOnListener {
private SampleOnClickedListener mCallback;
public interface SampleOnClickedListener {
void sampleOnClicked(int position);
}
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
SampleAdapter sampleAdapter = new SampleAdapter(this);
RecyclerView recyclerView = view.findViewById(R.id.sampleRecyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
recyclerView.setAdapter(sampleAdapter);
return view;
}
#Override
public void sampleOnClick(int position) {
Log.e("TAG", " from fragment / position:" + position);
mCallback.sampleOnClicked(position);
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
this.createCallbackToParentActivity();
}
private void createCallbackToParentActivity() {
try {
mCallback = (SampleOnClickedListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(e.toString() + " must implement OnButtonClickedListener");
}
}
}
Adapter:
public class SampleAdapter extends RecyclerView.Adapter<SampleAdapter.SampleRecyclerViewHolder> {
private final SampleRecyclerViewHolder.SampleOnListener mListener;
public SampleAdapter(SampleRecyclerViewHolder.SampleOnListener listener) {
this.mListener = listener;
}
#NonNull
#Override
public SampleRecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false);
return new SampleRecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SampleRecyclerViewHolder holder, int position) {
holder.itemView.setOnClickListener(v -> mListener.sampleOnClick(holder.getBindingAdapterPosition()));
}
#Override
public int getItemCount() {
// modify with real size
return 0;
}
public static class SampleRecyclerViewHolder extends RecyclerView.ViewHolder {
public SampleRecyclerViewHolder(#NonNull View itemView) {
super(itemView);
}
public interface SampleOnListener {
void sampleOnClick(int position);
}
}
}
If I'm not mistaken, the result of the click can be retrieved in the activity as well as in the fragment and that's what I needed.

Share real time Data From Viewpager Fragment to Activity

I have Fragments with a play button in my fragment. Whenever the user presses the play button from the ViewPager fragment, it calls a function in host activity which plays the player.
I am trying to implement the live data by using a ViewModel but unsuccessful.
public class SlidePlayerFragment extends Fragment {
private MyViewModel viewModel;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_slide_player, container, false);
ImageView playBtn = view.findViewById(R.id.playBtn);
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewModel.getIsPlaying().setValue(true);
viewModel.getCheck().setValue("Checking");
}
});
return view;
}
}
}
Here's my PagerAdapter
public class MyViewPagerAdapter extends FragmentStatePagerAdapter {
private int pages;
public MyViewPagerAdapter(FragmentManager fm,int count) {
super(fm);
pages = count;
}
#Override
public Fragment getItem(int i) {
return new SlidePlayerFragment();
}
#Override
public int getCount() {
return pages;
}
}
Here is the view model function
private MutableLiveData<Boolean> isPlaying;
public MutableLiveData<Boolean> getIsPlaying() {
if (isPlaying == null)
isPlaying = new MutableLiveData<>();
Log.d("TAG","Checking "+isPlaying.getValue());
return isPlaying;
}
And here is the observer segment
final Observer<Boolean> isPlaying= isPlaying -> {
//code here if playing then do some task here
};
viewModel.getIsPlaying().observe(this,isPlaying);
Note I already tried to find the predefined solution but I didn't find anything.
You do not really have to have a ViewModel for this purpose. You might just consider having public functions in the Activity which hosts the Fragments. For example, let us consider you have the following public functions in your PlayerActivity which launches all the other fragments.
public void play(String songName) {
viewModel.getIsPlaying().setValue(true);
viewModel.getCheck().setValue("Checking");
// Other actions for playing
}
Now, you might just consider the following onClick function instead of the one you are having now.
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((PlayerActivity) getActivity()).play(songName);
}
});
Hope that helps!

How to send Text to another fragment

I'm pretty new at Android, so I've already seen similar questions like mine, but I still can't send a Text to another fragment. I get this following error:
java.lang.NullPointerException: Attempt to invoke virtual method '
Here's the code, for better understanding...
FragOne
public class FragOne extends Fragment {
SendDados enviar;
String NumPessoas;
public interface SendDados{
void setdados(String numPessoas);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
try{ enviar=(SendDados)activity;
}catch (ClassCastException e){
throw new ClassCastException("erro");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.reserva_layout, container, false);
final TextView numero=(TextView)rootView.findViewById(R.id.qtdPessoas);
reservar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NumPessoas= numero.getText().toString();
enviar.setdados("1");
}
});
FragTwo
public class FragTwo extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.confirm_reserva_layout, container, false);
numeroPessoas=(TextView)rootView.findViewById(R.id.numPessoas);
return rootView;
}
public void UpdateDados(String numPessoas)
{
numeroPessoas.setText(numPessoas);
}
Activity
public class MenuActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,ReservaFragment.SendDados {
#Override
public void setdados(String numPessoas) {
ConfirmaReservaFragment cf= (ConfirmaReservaFragment)getSupportFragmentManager().findFragmentById(R.id.confirmaReserva);
cf.UpdateDados(numPessoas);
}
What I need to do is this, when I click the button, the textView from FragOne, must be copied to FragTwo, what am I doing wrong here? I always get this error:
java.lang.NullPointerException: Attempt to invoke virtual method '
I appreciate any help.
Since we are talking about simple TextViews, copying the whole TextView to send it to another fragment seems too complicated for a simple job. Just send a String and display the text inside a new TextView inside FragTwo.
I recommend reading this link for passing parameters to fragments before their construction.
If you insist on passing TextViews as parameters to fragments then you are going to have to find a way to serialize TextViews (I don't think they implement Parcelable) and that won't be a simple job.
Regarding your code:
Names of objects start with small caps (first snippet).
Names of methods start with small caps (last snippet).
Use instanceof in onAttach (first snippet).
I don't see what ConfirmaReservaFragment is?
Also I really really recommend you type your code in English.
Fragments should comunicate through an activity so i will post you a short example of how to correctly send data from one fragment to another using a host activity:
First we will use this layout named host activity layout with a framelayout as a parent called host_fragment_container :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/host_fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
now we are going to load our host activity and set this layout as a content view and create a basic method to change fragments on this frame layout :
public class HostActivity extends AppCompatActivity
implements TextViewContainerFragment.textViewClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.host_activity_layout);
}
private void switchFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.host_fragment_container, fragment)
.commit();
}
}
Now lets create our first fragment (the one who will send the text) :
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="#+id/text_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
we will use this same xml file for both sender and receiver fragments
public class TextViewContainerFragment extends Fragment {
public interface textViewClickListener {
void onTextViewClicked(String value);
}
private textViewClickListener mActivityCallback;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.text_view_container_fragment, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final TextView textView = (TextView) view.findViewById(R.id.text_view);
//search the view by id and cast it into a text view the set it on click lsitener
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// now if the cast was successful the activity callback will be valid and ready to use
// but we are going to check if its valid anyways
if (mActivityCallback != null) {
mActivityCallback.onTextViewClicked(textView.getText().toString());
}
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
// if context is extracted from an activity
// that means its safe to cast
if (context instanceof Activity) {
mActivityCallback =
(textViewClickListener) context;
}
}
// factory method
public static TextViewContainerFragment newInstance() {
return new TextViewContainerFragment();
}
}
now that we have our interface on the fragment we will implement it on the host activity to listen for callbacks & its going to call a sencond fragment ot display the sent text :
public class HostActivity extends AppCompatActivity
implements TextViewContainerFragment.textViewClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.host_activity_layout);
if (savedInstanceState == null) {
switchFragment(TextViewContainerFragment.newInstance());
}
}
private void switchFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.host_fragment_container, fragment)
.commit();
}
#Override
public void onTextViewClicked(String value) {
switchFragment(TextReceiverFragment.newInstance(value));
}
}
Here is the code for the receiver fragment (older fragment will be replaced for this one) :
public class TextReceiverFragment extends Fragment {
public static final String ARG_TEXT_RECEIVED_FROM_ANOTHER_FRAGMENT = "text";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.text_view_container_fragment, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
((TextView) view.findViewById(R.id.text_view)).setText(getArguments() != null ?
getArguments().getString(ARG_TEXT_RECEIVED_FROM_ANOTHER_FRAGMENT)
: "No text was sent from another fragment");
}
public static TextReceiverFragment newInstance(String text) {
TextReceiverFragment fragment = new TextReceiverFragment();
Bundle argument = new Bundle();
argument.putString(ARG_TEXT_RECEIVED_FROM_ANOTHER_FRAGMENT,
text);
fragment.setArguments(argument);
return fragment;
}
}
If you really want to copy the textview from Fragment 1 to Fragment 2. I suggested you to send the config data (e.g. the text, clicked, color) of the textview instead of the whole object. As the response from Spidey ,sending the widget to other fragment will be a trouble.
To facilitate your work, A textview config model should be used to send the config data of the textview.
public class TextViewConfig implements Parcelable {
private String text;
private boolean selected;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.text);
dest.writeByte(this.selected ? (byte) 1 : (byte) 0);
}
public TextViewConfig() {
}
protected TextViewConfig(Parcel in) {
this.text = in.readString();
this.selected = in.readByte() != 0;
}
public static final Parcelable.Creator<TextViewConfig> CREATOR = new Parcelable.Creator<TextViewConfig>() {
#Override
public TextViewConfig createFromParcel(Parcel source) {
return new TextViewConfig(source);
}
#Override
public TextViewConfig[] newArray(int size) {
return new TextViewConfig[size];
}
};
public String getText() {
return text;
}
public void setText(String pText) {
text = pText;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean pSelected) {
selected = pSelected;
}
}
Since the model class can be implemented as Parcelable easily, you can use it to send the data of the textview. And then you can use the answer from Juan Hurtado to practice the communication between the fragments by sending the config data.
let's supose u wants to got to the fragment two from fragment one with text "hello" by a click event on fragment one,
your code look like this,
class FragOne extends Fragment{
onCreateView(){
.
.
<your view>.setOnClickListener(new OnClickListener(){
#cverride
onClick(){
Bundle bundle=new Bundle();
bundle.putString("msg","<ur text will gose here which u wants to send to fragment two>");
.
.
.
//now move to the fragment two here
FragTwo fragTwo=new FragTwo();
fragTwo.setArgument(bundle);
FragmentManager fragmentManager=getSupportFragmentManager();
fragmentManager.beginTransaction().add(<ur root layout is>,fragmentTwo).commit();
}
});
}
}
Now in ur Fragmnet Two,
class FragTwo extends Fragment{
onCreateView(){
.
.
//get text which is send by fragment one
Bundle bundle=new Bundle();
String text=bundle.getString("msg");//this is ur text which is send by fragment one
}
}
Hope this will help u,

Interface adaptor to interface fragment android

Adaptor class that provides an interface:
public class Adaptor{
private ItemCLickCallback itemCLickCallback;
public interface ItemCLickCallback {
void onItemClick(int p);
void onSecItemClick(int p);
}
public void setItemCLickCallback(final ItemCLickCallback itemCLickCallback){
this.itemCLickCallback = itemCLickCallback;
}}
public class Overview extends Fragment implements Adaptor.ItemCLickCallback{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_overview, container, false);
Adaptor adaptor = new Adaptor(mijnwinkels, this.getActivity());
adaptor.setItemCLickCallback(this);
return view;
}
#Override
public void onItemClick(int p) {
}
#Override
public void onSecItemClick(int p) {
// On click: send data to database, remove data from database
// Needs methods that should be implemented in my activity, cant be linked to the activity
}}
So. The methods that are overwritten in my fragment need methods that should be located in my activity, those methods need the data from the fragment. Usually I would use an interface to do this, but these methods are already part of an interface from another class, so how can I put them in an interface so I can do everything from my activity? Thank you
Your question seems to mostly deal with removing duplicate code from the interface, so here's some suggestions.
You don't need to add a whole new Adaptor when you get your data in the onSuccess.
private ArrayList<Winkel> mijnwinkels;
private Adaptor mAdaptor;
onCreateView() {
//... Other code
mijnwinkels = new ArrayList<Winkel>();
// mRecyclerView =...
mAdaptor = new Adaptor(mijnwinkels, this.getActivity());
mRecyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
mRecyclerView.addItemDecoration(new VerticalSpace(30));
mRecyclerView.setAdapter(adaptor);
adaptor.setItemCLickCallback(this);
// etc...
}
#Override
public void onSuccess(ArrayList<Winkel> winkels) {
mijnwinkels.clear();
mijnwinkels.addAll(winkels);
mAdaptor.notifyDatasetChanged(); // something like this... Not sure how RecyclerView does it
}
If you make Winkel implements Parcelable and implement the necessary code for that, you remove some lines there.
#Override
public void onItemClick(int p) {
Winkel winkel = (Winkel) mijnwinkels.get(p);
Bundle detailsBundle = new Bundle();
detailsBundle.putExtra(EXTRA_WINKEL,winkel);
Details detail= new Details();
detail.setArguments(detailsBundle);
this.getFragmentManager().beginTransaction()
.replace(R.id.mycontainer,detail,null)
.addToBackStack(null)
.commit();
}
Though, really, all this can be written as its own method.
public static void showWinkel(Winkel winkel, FragmentManager fm) {
Bundle detailsBundle = new Bundle();
detailsBundle.putExtra(EXTRA_WINKEL,winkel);
Details detail= new Details();
detail.setArguments(detailsBundle);
fm.beginTransaction()
.replace(R.id.mycontainer,detail)
.addToBackStack(null)
.commit();
}
And called from anywhere
#Override
public void onItemClick(int p) {
showWinkel(mijnwinkels.get(p), this.getFragmentManager());
}
instead of
adaptor.setItemCLickCallback(this);
Once use below code for your fragment:
adaptor.setItemCLickCallback(new Adaptor.ItemCLickCallback () {
#Override
public void onItemClick(int position) {
}
});

Subscriber not getting fired when using Otto

I'm trying out Otto on Android and i'm trying to send back a message from my Fragment to the Activity. Here's the basics of my code:
My Bus provider:
public final class BusProvider {
private static final Bus mInstance = new Bus();
private BusProvider() {}
public static Bus getBusProviderInstance() {
return mInstance;
}
}
My Activity has the following code:
public class MyActivity
extends BaseActivity {
// ....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BusProvider.getBusProviderInstance().register(this);
// ....
}
#OnClick(R.id.profile_image)
public void onImageClicked() {
// ...
MyFragment fragment = MyFragment.newInstance(choices);
fragment.show(getFragmentManager(), "myChoices");
}
#Subscribe
public void onButtonChoicePicked(MyFragment.ChoicePickedEvent event) {
Toast.makeText(this, "reaching here", Toast.LENGTH_SHORT).show();
}
#Override
protected void onStop() {
super.onStop();
BusProvider.getBusProviderInstance().unregister(this);
}
// ...
}
and these are the important bits of code from my Fragment:
public class MyFragment
extends BaseDialogFragment {
// ...
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_choices,
container,
false);
setupDialogButtons(inflater, layout);
return layout;
}
private void setupDialogButtons(LayoutInflater inflater, LinearLayout parentView) {
ChoiceButtonViewHolder holder;
holder = new ChoiceButtonViewHolder(inflater, parentView);
holder.populateContent("First Choice", 1);
parentView.addView(holder.mChoiceTextView);
}
class ChoiceButtonViewHolder {
#InjectView(R.id.item_dialog_choice_desc) TextView mChoiceTextView;
private int mPosition;
ChoiceButtonViewHolder(LayoutInflater inflater, ViewGroup container) {
TextView mChoiceTextView = (TextView) inflater.inflate(R.layout.item_dialog_choice, container, false);
ButterKnife.inject(this, mChoiceTextView);
}
public void populateContent(String choiceDesc, int position) {
mChoiceTextView.setText(choiceDesc);
mPosition = position;
}
#OnClick(R.id.item_dialog_choice_desc)
public void onChoiceClicked() {
MyFragment.this.mDialog.dismiss();
BusProvider.getBusProviderInstance().post(new ChoicePickedEvent(1));
}
}
public static class ChoicePickedEvent {
public int mPositionClicked;
ChoicePickedEvent(int position) {
mPositionClicked = position;
}
}
}
I don't get any errors. But when i click my button from the fragment, the event onButtonChoicePicked doesn't get called.
Am I doing something wrong?
Am i misunderstanding how Otto works?
Is it a weird combination of ButterKnife and Otto that makes it not work?
Make sure you are importing "com.squareup.otto.Subscribe" not "com.google.common.eventbus.Subscribe"
The example code works without any issues independently. The reason i was facing this problem initially (as was rightly pointed out by #powerj1984): There was a misconfiguration in my project, where the bus that was being injected (via Dagger) was different from the bus instance that was being subscribed to for updates :P.
Lesson learnt: make sure the bus you use, is the same instance in both cases.

Categories

Resources