如何使用findfragmentbytag获取带有supportfragmentmanager的第一个片段

时间:2014-10-11 16:36:13

标签: android android-fragments tabs

我正在使用viewpager和tabspageradapter。在我的主要活动中,我有一个属性来保护选定选项卡中的当前片段:current_tab。当选择一个新选项卡时,它会更改其值,但我不知道如何在开头设置其值,因为我需要attribut来更新片段中的listview。我尝试过很多东西,但是大多数时候我都会遇到nullpointerexception,有人能告诉我它是如何工作的吗?

我的TabsPagerAdapter的代码:

public class TabsPagerAdapter extends FragmentPagerAdapter {

public TabsPagerAdapter(FragmentManager fm){
    super(fm);
}

@Override
public Fragment getItem(int index){
    switch(index) {
        case 0:
            return new AllShowsFragment();
        case 1:
            return new UnwatchedShowsFragment();
        case 2:
            return new WatchedShowsFragment();
    }
    return null;
}

@Override
public int getCount() {
    return 3;
}
}

主要活动最重要部分的代码:

public class MainActivity extends FragmentActivity implements
    ActionBar.TabListener {

public static FragmentCommunicater fragmentCommunicater;
public static boolean simple_progress;
public static int editmode;
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private DatabaseHandler db;
private Show current_show;
private static MyFragment current_tab;
private boolean first_launch=true;

private String[] tabs = { "All Shows", "Unwatched", "Watched" };

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

    db = new DatabaseHandler(this);
    viewPager = (ViewPager) findViewById(R.id.pager);
    actionBar = getActionBar();
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

    viewPager.setAdapter(mAdapter);
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    for (String tab_name : tabs){
        actionBar.addTab(actionBar.newTab().setText(tab_name)
                .setTabListener(this));
    }

    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
}

public void onResume(){
    super.onResume();
    getSettings();
}

public void getSettings() {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    simple_progress = sharedPrefs.getBoolean("simple_progress_key", false);
}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    viewPager.setCurrentItem(tab.getPosition());
    Fragment page = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + viewPager.getCurrentItem());
    if ((viewPager.getCurrentItem() == 0 || viewPager.getCurrentItem() == 1 || viewPager.getCurrentItem() == 2) && (page != null)) {
        current_tab = ((MyFragment) page);
        current_tab.update();
    }
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}

public static void update(){
    current_tab.update();
}
}

Ony我的片段类,我得到了新的nullpointer异常:

public class AllShowsFragment extends MyFragment {
private SQLiteDatabase newDB;
private ListView lv;
private List<Show> showList = new ArrayList<Show>();
private int position;
private DatabaseHandler db;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_shows, container, false);
    lv = (ListView) rootView.findViewById(R.id.mainlist);
    lv.setOnItemLongClickListener(new OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       int pos, long id) {
            position = pos;
            createClickMenu();
            return true;
        }
    });
    return rootView;
}

public void update(){
    populateListfromDB();
}

public void populateListfromDB() {
    db = new DatabaseHandler(this.getActivity()); 
    newDB = db.getWritableDatabase(); //Exception at this line
    showList.clear();

    Cursor cursor = newDB.rawQuery("SELECT id as _id, title, cseason, cepisode, watched FROM "
            + db.TABLE_SHOWS, null);

    cursor.moveToFirst();

    if (cursor != null & cursor.moveToFirst()) {
        cursor.moveToFirst();
        do {
            Show show = new Show(Integer.parseInt(cursor.getString(0)), cursor.getString(1),
                    cursor.getString(2), cursor.getString(3),
                    Integer.parseInt(cursor.getString(4)));
            showList.add(show);
        } while (cursor.moveToNext());
    }

    myCursorAdapter = new CustomAdapter(this, showList,((MainActivity)this.getActivity()).editmode,
            ((MainActivity)this.getActivity()).simple_progress);
    lv.setAdapter(myCursorAdapter);
}
}

例外,前几行:

     Caused by: java.lang.NullPointerException
        at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
        at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
        at wrodarczyk.com.showtracker.AllShowsFragment.populateListfromDB(AllShowsFragment.java:55)
        at wrodarczyk.com.showtracker.AllShowsFragment.update(AllShowsFragment.java:50)
        at wrodarczyk.com.showtracker.MainActivity.update(MainActivity.java:183)
        at wrodarczyk.com.showtracker.MainActivity.onTabSelected(MainActivity.java:134)
        at com.android.internal.app.ActionBarImpl.selectTab(ActionBarImpl.java:577)
        at com.android.internal.app.ActionBarImpl.addTab(ActionBarImpl.java:506)
        at com.android.internal.app.ActionBarImpl.addTab(ActionBarImpl.java:492)
        at wrodarczyk.com.showtracker.MainActivity.onCreate(MainActivity.java:53)

1 个答案:

答案 0 :(得分:0)

如果ViewPager中有一个固定数量的小页面,您只需维护自己预先填充的参考列表:

public TabsPagerAdapter(FragmentManager fm){
    super(fm);
    myTabs.add(new AllShowsFragment());
    myTabs.add(new UnWatchedShowsFragment());
    // ...
}

鉴于此,您的getItem()方法将只返回此数组列表中的索引元素。

拥有自己的标签片段索引后,您可以将current_tab存储在int中,您的更新通话就像

mAdapter.myTabs.get(current_tab).update();