1

I'm trying to make a tabbed android app. Both tabs are listviews. The first tab gets posts from an RSS Feed. The second tab displays them organized into categories.

The problem is that I want to populate the listview in the second tab from the fragment of the first tab.

My code for the first fragment is:

public class PostsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.posts_fragment, container, false);
    return view;
}

...
...
...

// Populate the "posts_fragment.xml" with Posts 
public void populate_postview() {
    ListView lv1;

    lv1 = (ListView)getView().findViewById(R.id.postlist);
    lv1.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1 , arrays.PsychoTitle));
    lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            ...             
        }
    });

// Populate the "categories_fragment.xml" with Categories
public void populate_catview() {
    ListView lv2;

    lv2 = (ListView)getView().findViewById(R.id.catList);
    lv2.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1 , arrays.PsychoCategories));
}

The problem here is that catList in populate_catview() is a part of "categories_fragment.xml" but using getView() returns the current layout which is "posts_fragment.xml".

So how can I populate the item list in the second fragment?

Sheharyar
  • 73,588
  • 21
  • 168
  • 215

2 Answers2

1

Take a look at my answer here Call functions of Activities Belonging to a Fragment it shows enough to explain it. You shouldn't directly call the methods of another fragment. The fragments should be self contained. Create an interface to the activity which then calls a method with the data in the second fragment.

Community
  • 1
  • 1
FabianCook
  • 20,269
  • 16
  • 67
  • 115
1

Assuming that both fragments have the same parent activity, one solution is to save the data backing the list in the parent activity. Then when the user taps on either tab, the corresponding fragment retrieves the data and populates the list accordingly.

WindsurferOak
  • 4,861
  • 1
  • 31
  • 36