NewUserSO
NewUserSO

Reputation: 211

FragmentBasics gives Null Pointer Exception

I'm using the code from Google's example here in the zip file.

When I run it as it is everything goes well.

If I remove the support lib and change FragmentActivity to Activity and support.Fragment to Fragment ( also gertsupportFragmentManager() to FragmentManager() ) and the Manifest to point to api 17 like this : <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="17" />

I'm getting a NPE when I click the list Item. I don't understand what changed and can't find the R.id.article.

Since I haven't change the layout files and I didn't mess much with the code I'm guessing it has something to do with the APIs and/or the lifecycle of the Activity/Fragments in place of FragmentActivity and support.Fragment .

error is :

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 code is here :

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 class :

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."
};
}

Upvotes: 0

Views: 648

Answers (2)

Richard Hoska
Richard Hoska

Reputation: 21

The answer marked as accepted did not work for me. I ended up finding a detailed answer here (http://marksunghunpark.blogspot.com/2015/04/googles-fragment-example-error.html)

From Sunghun's Blog:

It will load news content when you click a item from the headlines. The MainActivity switches Fragment to display it in a handset but it displays news content in the second pane in a table device. Error comes from ArticleFragment class. When the MainActivity loads two pane news_articles.xml in /res/layout-large, it cannot find view having ID 'article' because it tried to find the view by calling getActivity().findViewById(). This does not work. You have to read the 'article' TextView from rootView of the article_view.xml.

Upvotes: 2

Raghunandan
Raghunandan

Reputation: 133580

Declare TextView as a class member

Initialize it in 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 looks for a view with the mentioned in the current infalted layout. If not found you get NPE. So infalte the layout use the view object to initialize textview.

Upvotes: 1

Related Questions