Adnxy Adnxy - 2 years ago 563
Java Question

How to implement void OnFragmentInteractionListener?

When I launch my app I get following exception:

java.lang.RuntimeException: com.demo.mtin.mtin.MainActivity must implement OnFragmentInteractionListener

Can someone help me with this?
What code I need to add in MainActivity and where?

I have two blank fragments: PopularFragment and RatedFragment

MainActivity bellow:

public class MainActivity extends AppCompatActivity {

private RecyclerView mRecyclerView;
private MoviesAdapter mAdapter;

protected void onResume() {
SharedPreferences sharedPref = getBaseContext().getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
String order = sharedPref.getString("order", "popular");
if (order.equals("popular")) {
} else {

protected void onCreate(Bundle savedInstanceState) {
// uci i postaviti order -> popular
Log.d("NESTO", "NESTO-onCreate");
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

Toolbar toolbar = (Toolbar) findViewById(;

TabLayout tabLayout = (TabLayout) findViewById(;
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));

final ViewPager viewPager = (ViewPager) findViewById(;
final PageAdapter adapter = new PageAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
public void onTabSelected(TabLayout.Tab tab) {

public void onTabUnselected(TabLayout.Tab tab) {


public void onTabReselected(TabLayout.Tab tab) {


public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(, menu);
return true;

public boolean onOptionsItemSelected(MenuItem item) {

Intent intent = new Intent(this, SettingsActivity.class);

int id = item.getItemId();

if (id == {

return true;

return super.onOptionsItemSelected(item);

Answer Source

This is actually a pretty straight-forward error message, go for this:

public class MainActivity extends AppCompatActivity implements PopularFragment.OnFragmentInteractionListener, RatedFragment.OnFragmentInteractionListener { ... 

    public void onFragmentInteraction(Uri uri) {


You must indicate that your activity implement the fragment's interface, then implement it (can be void though).

And have the following in your fragments :

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download