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) {
}
});
Related
Sorry for my english. I have one activity and in this activity in FragmentPagerAdapter exist 5 fragments. All fragments use one object model for inforation(product name, product image ...).
My activity get data from data base. And then it data send to all fragments. My example Activity:
#BindView(R.id.tabs_sep_prod) TabLayout tabs_sep_prod;
#BindView(R.id.viewpager_sep_prod) ViewPager viewpager_sep_prod;
PrepBaseProdFragment prepBaseProdFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sep_product);
ButterKnife.bind(this);
prepBaseProdFragment = new PrepBaseProdFragment();
// there i have another fragments
// ...
setupViewPager(viewpager_sep_prod);
tabs_sep_prod.setupWithViewPager(viewpager_sep_prod);
}
private void setupViewPager(ViewPager viewPager) {
SepProductActivity.ViewPagerAdapter adapter = new SepProductActivity.ViewPagerAdapter(
adapter.addFrag(prepBaseProdFragment, getString(R.string.sep_prep_base));
// there i have another addFrag
// ...
viewPager.setOffscreenPageLimit(5);
viewPager.setAdapter(adapter);
}
#Override
public void onResume() {
super.onResume();
// this i call method from presenter, it return data in method setData
if(idCat != null && idProd != null)
sepProductPresenter.getSepProd(idCat, idProd);
}
#Override
public void setData(SepProductModel sepProductModel) {
// there i send data to fragment
prepBaseProdFragment.setDataInf(sepProductModel);
// ...
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
my fragment
public class PrepBaseProdFragment extends BaseFragment {
#BindView(R.id.text) TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_about_prod_prepare_base, parent, false);
ButterKnife.bind(this, view);
Log.e("PrepBaseProdFragment", "PrepBaseProdFragment");
return view;
}
public void setDataInf(SepProductModel sepProductModel) {
text.setText(sepProductModel.getPROPERTY_PR_SUBSTRPREP_UA_VALUE().getTEXT());
}
}
My question: when i send data from activity to fragment, my view do not have time to initialize. In fragment line text.setText(sepProductModel.getPROPERTY_PR_SUBSTRPREP_UA_VALUE().getTEXT()); error
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference
Please, help me solve my problem. I spend many times for this
You can check if the text view is null save the data in a variable inside the fragment and in onCreateView use the data variable if it is filled and set the textview text.
Something like this:
// Inside the Fragment body
private SepProductModel sepProductModel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_about_prod_prepare_base, parent, false);
ButterKnife.bind(this, view);
Log.e("PrepBaseProdFragment", "PrepBaseProdFragment");
if(this.sepProductModel != null)
text.setText(this.sepProductModel.getPROPERTY_PR_SUBSTRPREP_UA_VALUE().getTEXT());
return view;
}
public void setDataInf(SepProductModel sepProductModel) {
if(text != null){
// use text
}
else this.sepProductModel=sepProductModel;
}
I can advise you to wait for your data and then show fragments to adapter, moreover all of them use the same model. While you dont have data, you can show progress bar.
When you have needed model, you can create instances of your fragments and set bundle arguments for them. You can use method like this:
public static MyFragment newInstance(MyModel model){
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putSerializable(KEY, model);//or args.putParcelable(KEY, model);
fragment.setArguments(args);
return fragment;
}
Notice: your model need to implement Serializable or Parcelable to be putted in bundle. You may read about difference here.
Then in your set data method, when you already have your model you can setup your adapter and set it to view pager, but with this approach:
adapter.addFrag(MyFragment.newInstance(model), getString(R.string.sep_prep_base));
It have to help you, ask me if you have some questions.
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,
I want to return a callback from a custom adapter to my fragment. However the adapter won't let me pass the reference of the Fragment implementing the interface defined in custom adapter. How can I receive callbacks from adapter to fragment?
public class MyFrag extends Fragment implements MyInterface
{
#Override
public void onCreateView()
{
MyAdapter adapter = new MyAdapter(this); // error here: How to resolve
}
#Override
public void mySignal()
{
}
}
public class MyAdapter extends RecyclerViewAdapter
{
MyInterface listener;
public MyAdapter(MyInterface listener)
{
this.listener = listener;
}
public interface MyInterface
{
public void mySignal();
}
}
Just for a clear definition and SOC you could try this instead,
public class MyFrag extends Fragment
{
#Override
public void onCreateView()
{
MyAdapter adapter = new MyAdapter(new MyInterface() {
#Override
public void mySignal()
{
//do stuff here
}
});
}
}
As I know, Fragment has this method
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
Sorry for my question! What is onCreateView() method without any params?
This way will work fine if there is not any different things more.
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.
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.