Google's fragment example

http://developer.android.com/training/index.html의 예제는 7인치 이상의 태블릿에서 안드로이드의 fragment를 통해 두 화면으로 분리하는 예제 입니다.

여기에서 다음과 같은 문제가 발생해서 관련 부분을 수정해 보겠습니다.

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.example.android.fragments.ArticleFragment.updateArticleView(ArticleFragment.java:71)

getActivity().findViewById()에서 발생하는 문제로 ID를 찾을 수 없어 Null Exception을 발생합니다. 다음과 같이 수정합니다.

public class ArticleFragment extends Fragment {
TextView articleText;
 
@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
        View rootView = inflater.inflate(R.layout.article_view, container, false);
        articleText = (TextView) rootView.findViewById(R.id.article);
        return rootView;
    }
}
...
public void updateArticleView(int position) {
        //TextView article = (TextView) getActivity().findViewById(R.id.article); -> This causes error.
        if (articleText != null)
            articleText.setText(Ipsum.Articles[position]);
        mCurrentPosition = position;
    }

 

Tags: 
youngdeok's picture

Language

Get in touch with us

"If you would thoroughly know anything, teach it to other."
- Tryon Edwards -