无法启动活动组件信息(nullpointer)

时间:2013-11-07 20:35:37

标签: android

我试图用标签在android中创建一个基本的ui。但是每当我尝试运行它时,我都会一直得到一个nullpointer异常。错误源自初始化viewpager。 (我不知道还有什么要输入,每当我尝试发布时我都会收到错误。)

public class MainActivity extends FragmentActivity implements TabListener {
ActionBar actionBar;
ViewPager viewPager;

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

    viewPager=(ViewPager) viewPager.findViewById(R.id.tabs);
    viewPager.setAdapter(new adapter(getSupportFragmentManager()));
    actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    ActionBar.Tab stocks = actionBar.newTab();
    stocks.setText("Stocks");
    stocks.setTabListener(this);

    ActionBar.Tab market = actionBar.newTab();
    market.setText("Market");
    market.setTabListener(this);

    ActionBar.Tab portfolio = actionBar.newTab();
    portfolio.setText("Portfolio");
    portfolio.setTabListener(this);

    actionBar.addTab(stocks);
    actionBar.addTab(market);
    actionBar.addTab(portfolio);
}

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



@Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    // TODO Auto-generated method stub

}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    // TODO Auto-generated method stub

}

class adapter extends FragmentPagerAdapter {

    public adapter(FragmentManager fm) {
        super(fm);
        // TODO Auto-generated constructor stub
    }

    public Fragment getItem(int arg0) {
        Fragment fragment = null;
        if(arg0==0) {
            fragment = new StocksFragment();
        }
        if (arg0==1){
            fragment = new MarketFragment();
        }
        if (arg0==2){
            fragment = new PortfolioFragment();
        }
        return fragment;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return 3;
    }
}

}

2 个答案:

答案 0 :(得分:1)

当然这一行会给出NPE

 viewPager=(ViewPager) viewPager.findViewById(R.id.tabs);

您正在尝试初始化的对象上调用方法(在findViewById()上调用viewPager

如果tabs位于activity_main.xml,则只需删除viewPager

viewPager=(ViewPager) findViewById(R.id.tabs);

答案 1 :(得分:-1)

findViewById是活动的方法,而不是视图的方法。所以它应该是:

viewPager=(ViewPager) this.findViewById(R.id.tabs);