Problem with fragment findViewById

I was learning android fragments. I made a separate layout for large screens.

Now I am calling updateArticleView() from MainActivity which is actually updating the Text View inflated by the ArticleFragment. I am getting NULL by this line


But getView() works fine and I can update the text. I printed the view hierarchy and it has the element, but somehow findViewById of the activity cannot return the object.¬†Application is working. I posted the problem to stackoverflow. Let’s see someone can solve the catch.

    public class ArticleFragment extends Fragment{

    final static String ARG_POSITION = "position";
    final static String TAG = "ArticleFragment";

    int mCurrentPosition = -1;

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

        if(savedInstanceState != null){

            mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);

        return inflater.inflate(R.layout.article_view, container, false);

    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(ARG_POSITION, mCurrentPosition); //can save negative!

    public void onStart() {

        Bundle args = getArguments(); // this is to get the position of article for the first instantiation.

        if(args != null){


        } else if(mCurrentPosition != -1) {



    public  void updateArticleView(int selectedArticle){ // this is also called from mainactivity

        View myView = getView();

        Log.d(TAG, myView.toString());

        Activity myActivity = getActivity();

        Log.d(TAG, myActivity.toString());

        ViewGroup view = (ViewGroup) myActivity.findViewById(;

        //printViewHierarchy(view , "debug");

        Log.d(TAG, "article id " + String.valueOf(;
//        TextView article = (TextView) getActivity().findViewById(;

        TextView article = (TextView) getView();

        Log.d(TAG, article.toString());

//        article.setText("I am new");

        mCurrentPosition = selectedArticle;


    public static void printViewHierarchy(ViewGroup $vg, String $prefix)
        for (int i = 0; i < $vg.getChildCount(); i++) {
            View v = $vg.getChildAt(i);
            String desc = $prefix + " | " + "[" + i + "/" + ($vg.getChildCount()-1) + "] "+ v.getClass().getSimpleName() + " " + v.getId();
            Log.v("x", desc);

            if (v instanceof ViewGroup) {
                printViewHierarchy((ViewGroup)v, desc);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s