FragmentBasics给出空指针异常

时间:2013-11-07 18:52:54

标签: android android-fragments

我在zip文件中使用了Google的示例here中的代码。

当我运行它时,一切顺利。

如果我删除了支持库并将FragmentActivity更改为Activity并支持.Fragment到Fragment(还有gertsupportFragmentManager()到FragmentManager()),并且Manifest指向api 17,如下所示:     <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="17" />

单击列表项时,我收到NPE。我不明白发生了什么变化,无法找到R.id.article。

由于我没有更改布局文件,因此我并没有太多地使用代码,我猜测它与API和/或活动/片段的生命周期有关代替FragmentActivity和support.Fragment。

错误是:

11-07 18:30:20.397: E/AndroidRuntime(1266): FATAL EXCEPTION: main
11-07 18:30:20.397: E/AndroidRuntime(1266): java.lang.NullPointerException
11-07 18:30:20.397: E/AndroidRuntime(1266):     at com.example.android.fragments.ArticleFragment.updateArticleView(ArticleFragment.java:63)
11-07 18:30:20.397: E/AndroidRuntime(1266):     at com.example.android.fragments.MainActivity.onArticleSelected(MainActivity.java:70)
11-07 18:30:20.397: E/AndroidRuntime(1266):     at com.example.android.fragments.HeadlinesFragment.onListItemClick(HeadlinesFragment.java:75)

ArticleFragment代码在这里:

public class ArticleFragment extends android.app.Fragment {
final static String ARG_POSITION = "position";
int mCurrentPosition = -1;

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

    // If activity recreated (such as from screen rotate), restore
    // the previous article selection set by onSaveInstanceState().
    // This is primarily necessary when in the two-pane layout.
    if (savedInstanceState != null) {
        mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
    }

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.article_view, container, false);
}

@Override
public void onStart() {
    super.onStart();

    // During startup, check if there are arguments passed to the fragment.
    // onStart is a good place to do this because the layout has already been
    // applied to the fragment at this point so we can safely call the method
    // below that sets the article text.
    Bundle args = getArguments();
    if (args != null) {
        // Set article based on argument passed in
        updateArticleView(args.getInt(ARG_POSITION));
    } else if (mCurrentPosition != -1) {
        // Set article based on saved instance state defined during onCreateView
        updateArticleView(mCurrentPosition);
    }
}

public void updateArticleView(int position) {
    TextView article = (TextView) getActivity().findViewById(R.id.article);
    article.setText(Ipsum.Articles[position]);
    mCurrentPosition = position;
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // Save the current article selection in case we need to recreate the fragment
    outState.putInt(ARG_POSITION, mCurrentPosition);
}
}

Ipsum课程:

package com.example.android.fragments;

public class Ipsum {

static String[] Headlines = {
    "Article One",
    "Article Two"
};

static String[] Articles = {
    "Article One\n\nExcepteur pour-over occaecat squid biodiesel umami gastropub, nulla laborum salvia dreamcatcher fanny pack. Ullamco culpa retro ea, trust fund excepteur eiusmod direct trade banksy nisi lo-fi cray messenger bag. Nesciunt esse carles selvage put a bird on it gluten-free, wes anderson ut trust fund twee occupy viral. Laboris small batch scenester pork belly, leggings ut farm-to-table aliquip yr nostrud iphone viral next level. Craft beer dreamcatcher pinterest truffaut ethnic, authentic brunch. Esse single-origin coffee banksy do next level tempor. Velit synth dreamcatcher, magna shoreditch in american apparel messenger bag narwhal PBR ennui farm-to-table.",
    "Article Two\n\nVinyl williamsburg non velit, master cleanse four loko banh mi. Enim kogi keytar trust fund pop-up portland gentrify. Non ea typewriter dolore deserunt Austin. Ad magna ethical kogi mixtape next level. Aliqua pork belly thundercats, ut pop-up tattooed dreamcatcher kogi accusamus photo booth irony portland. Semiotics brunch ut locavore irure, enim etsy laborum stumptown carles gentrify post-ironic cray. Butcher 3 wolf moon blog synth, vegan carles odd future."
};
}

2 个答案:

答案 0 :(得分:2)

标记为已接受的答案对我不起作用。我最终在这里找到了详细的答案(http://marksunghunpark.blogspot.com/2015/04/googles-fragment-example-error.html

来自Sunghun的博客:

  

当您点击标题中的项目时,它会加载新闻内容。   MainActivity切换片段以将其显示在手机中但是它   在表格设备的第二个窗格中显示新闻内容。错误   来自ArticleFragment课程。当MainActivity加载两个窗格时   news_articles.xml中的/res/layout-large,找不到ID为'article'的视图,因为它试图通过调用查找视图   getActivity().findViewById()。这不起作用。你必须阅读   来自'article'的{​​{1}}的{​​{1}} TextView

答案 1 :(得分:1)

TextView声明为类成员

onCreateView

中对其进行初始化
TextView article; 
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
    Bundle savedInstanceState) {

    // If activity recreated (such as from screen rotate), restore
    // the previous article selection set by onSaveInstanceState().
    // This is primarily necessary when in the two-pane layout.
    if (savedInstanceState != null) {
        mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
    }
    View view =inflater.inflate(R.layout.article_view, container, false); 
     article = (TextView) view.findViewById(R.id.article);
    // Inflate the layout for this fragment
    return view;
}

findViewById查找当前的infalted布局中提到的视图。如果没有找到,你会得到NPE。因此,使布局使用视图对象初始化textview。