From my FragmentActivity
, i want to update my ListView
of a Fragment
(created by code) at onRestart
of the FragmentActivity
. There is no fragment and tag in XML file. Here is my FragmentActivity
.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new ProfilePagerAdapter(getSupportFragmentManager(),
myFriendsList, notifiedFriendsList);
viewPager.setAdapter(mAdapter);
..........
my FragmentPagerAdapter
is
public class ProfilePagerAdapter extends FragmentPagerAdapter {
private ArrayList<Friend> myFriends;
private ArrayList<ExpandableChild> notifiedFriendsList;
private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public ProfilePagerAdapter(FragmentManager fm, ArrayList<Friend> myFriends, ArrayList<ExpandableChild> notifiedFriendsList) {
super(fm);
// TODO Auto-generated constructor stub
this.myFriends = myFriends;
this.notifiedFriendsList = notifiedFriendsList;
}
@Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new FriendsFragment(myFriends);
case 1:
return new MyProfileFragment(notifiedFriendsList);
}
return null;
}
@Override
public int getCount() {
return 2;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
In my FriendsFragment
class, i have a ListView
. I used following two methods to update the ListView
from my FragmentActivity
in the class.
public void setNewFriendList(ArrayList<Friend> myFriends){
this.friendsList = myFriends;
}
public void updateList(){
adapter.notifyDataSetChanged();
}
Now i want to update the ListView
of FriendsFragment
at onRestart()
of FragmentActivity
in following way.
@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
android.support.v4.app.Fragment frag = mAdapter
.getRegisteredFragment(0);
if (frag != null) {
((FriendsFragment) frag).setNewFriendList(myFriendsList);
((FriendsFragment) frag).updateList();
Toast.makeText(UserProfileTab.this, "Updated",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(UserProfileTab.this, "Not Updated:",Toast.LENGTH_LONG).show();
}
}
But in Toast
shows Not Updated
as frag
returns null
. I followed link1 and link1. Thanks in advance.