Search code examples
javaandroidandroid-fragmentsandroid-viewpagerandroid-tabs

Dynamically update TextView inside Fragment (ViewPager Tab Layout)


I have a problem with createing a functionality in my app. I would like that the Button in one tab of my application update the TextViews which are located in the other tab of my application. Unfortunately my solutions does not work - throws NPE everytime I touch the Button1. My code:

Tab which should be updated:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class SummaryFragment extends Fragment {

    TextView textViewOne;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View summary= inflater.inflate(R.layout.fragment_summary, container, false);

        textViewOne = (TextView) summary.findViewById(R.id.books);
        textViewOne.setText("You have read " + Stats.book + " books");
        return summary;
    }

    public void updateStats() {
        textViewOne.setText("You have read " + Stats.book + " books");
    }


}

Tab on which the button is located:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class ReadingStarted extends Fragment {

    static FirstPageFragmentListener firstPageListener;

    public SummaryFragment summaryFragment;


    public ReadingStarted() {
    }

    public ReadingStarted(FirstPageFragmentListener listener) {
        firstPageListener = listener;
    }

    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View started = inflater.inflate(R.layout.fragment_started, container, false);

        Button button1 = (Button) started.findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                Stats.book=Stats.book+1;
                summaryFragment.updateStats();

            }
        });        
    return started;
    }
}

Solution

  • Problems in your code:

    1. SummaryFragment doesnot have a empty constructor every fragment requires it
    2. SummaryFragment summaryFragment should be SummaryFragment summaryFragment = new SummaryFragmet();//no initialization done so npe in summaryFragment.updateStats();
    3. Communication between fragments should be done through activity.

    See the developer docs about Fragments.