Search code examples
androidinterfacecommunicator

How to pass information to a fragment when an item on a listfragment is clicked


I have a fragment list SecondActivityListFragment that contains a list of items. If an item on the list is clicked, I would like to pass the info of this clicked item to another fragment called ItemViewFragment. I have created an interface class called Communicator but I have no clue how to pass the information through.

SecondActivityListFragment

public class SecondActivityListFragment extends ListFragment {

Communicator communicator;

private ArrayList<SubNote> subNotes;
private SubNoteAdapter subNoteAdapter;

@Override
public void onActivityCreated(Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);

    communicator = (Communicator) getActivity();
    subNotes = new ArrayList<SubNote>();
    subNotes.add(new SubNote("Product X", "wow", "booo", new     BigDecimal(10212).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.HEALTHCARE));
    subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
    subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
    subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
    subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
    subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
    subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
    subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));

    subNoteAdapter = new SubNoteAdapter(getActivity(), subNotes);
    setListAdapter(subNoteAdapter);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id){
    super.onListItemClick(l, v, position, id);



    launchNoteDetailActivity(position);

}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof Communicator) {
        communicator = (Communicator) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement Communicator");
    }
}

private void launchNoteDetailActivity(int position){


    ItemViewFragment itemViewFragment = new ItemViewFragment();
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.content_main, itemViewFragment, itemViewFragment.getTag()).commit();

    //communicator.respond(position);

    // Grab the note information associated with whatever note item we clicked on
    //SubNote subNote = (SubNote) getListAdapter().getItem(position);

}
}

MainActivity

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, Communicator {

//public static final String SUB_NOTE_NAME_EXTRA = "com.example.khalid.myapplication2.SubNote Title";
//public static final String SUB_NOTE_BRIEFDESCRIPTION_EXTRA = "com.example.khalid.myapplication2.SubNote BriefDescription";
//public static final String SUB_NOTE_FULLDESCRIPTION_EXTRA = "com.example.khalid.myapplication2.SubNote FullDescription";
//public static final String SUB_NOTE_PRICE_EXTRA = "com.example.khalid.myapplication2.SubNote Price";
//public static final String SUB_NOTE_CATEGORY_EXTRA = "com.example.khalid.myapplication2.SubNote Category";

// ViewPager viewPager;
// CustomSwipeAdapter imgadapter;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    MainActivityListFragment mainActivityListFragment = new MainActivityListFragment();
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.content_main, mainActivityListFragment, mainActivityListFragment.getTag()).commit();



   // viewPager = (ViewPager) findViewById(R.id.viewpager1);
   // imgadapter = new CustomSwipeAdapter(this);
   // viewPager.setAdapter(imgadapter);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}



@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

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

    SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
    SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    return true;
}


  /*  @Override
      public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
 }*/

  @SuppressWarnings("StatementWithEmptyBody")
  @Override
  public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_home) {
        MainActivityListFragment mainActivityListFragment = new MainActivityListFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_main, mainActivityListFragment, mainActivityListFragment.getTag()).commit();
        setTitle("ThimarAljazirah");
    } else if (id == R.id.nav_notification) {

        NotificationsFragment notificationsFragment = new NotificationsFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_main, notificationsFragment, notificationsFragment.getTag()).commit();
        setTitle("Notifications");

    } else if (id == R.id.nav_messages) {

    } else if (id == R.id.nav_categories) {

    } else if (id == R.id.nav_deals) {

    } else if (id == R.id.nav_settings) {
        SettingFragment settingFragment = new SettingFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_main, settingFragment, settingFragment.getTag()).commit();
        setTitle("Settings");
    } else if (id == R.id.nav_help_contact) {

    } else if (id == R.id.nav_profile) {
        MyProfile myProfile = new MyProfile();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_main, myProfile, myProfile.getTag()).commit();
        setTitle("My Profile");

    } else if (id == R.id.nav_signout) {
        SingOutFragment singOutFragment = SingOutFragment.newInstance("1", "2");
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_main,singOutFragment, singOutFragment.getTag()).commit();

    } else if (id == R.id.nav_about_us) {
        AboutUsFragment aboutUsFragment = new AboutUsFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_main,aboutUsFragment, aboutUsFragment.getTag()).commit();
        setTitle("About Thimar Aljazirah");
    }


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}


@Override
public void respond(int position) {

    ItemViewFragment itemViewFragment = new ItemViewFragment();



}
}

ItemViewFragment

public class ItemViewFragment extends Fragment {


public ItemViewFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {


    return inflater.inflate(R.layout.fragment_item_view, container, false);
}

}

Communicator

public interface Communicator {
public void respond (int position);
}

Solution

  • If both fragments are in the same Activity, this activity can implement a listener(interface) that listens for a click from fragment A and transfers data to the fragment B.

     public interface Communicator{
         void onResponse(YourData data);
     }
    
     public class MainActivity extends AppCompatActivity implements Communicator {
    
         @Override
         public void onResponse(Your data) {
             // add data to other fragment
         }
     }
    

    In order to pass the data to the activity, you have to get the listener from inside of the fragment.

     YourFragment extends Fragment {
        private Communicator communicator;
    
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            Object host = getHost();
            if (host instanceof Communicator) {
                communicator= (Communicator) host;
            }
        }
    
        @Override
        public void onDetach() {
            super.onDetach();
            communicator= null;
        }
    }
    

    Then when onClick happens for the list view. You have to do.

    onClick {
        communicator.onResponse(//your data here);
    }
    

    In the other fragment B you have to create a newInstance(//Your data) method like this.

    public static YourFragment newInstance(String string) {
        Bundle args = new Bundle();
        args.putString(STRING_KEY, string);
        YourFragment fragment = new YourFragment ();
        fragment.setArguments(args);
        return fragment;
    }
    

    and then onCreate you can retrieve the data given to the fragment

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String string = getArguments().getString(STRING_KEY);
    
    }
    

    you shouldn't use the default constructor to instantiate the fragment because of the way Android recreates fragments and activities. That's why we create newInstance method.