Search code examples
androidandroid-fragmentsandroid-activityandroid-graphview

How to send data from activity to the fragment for update a graph?


public class GraphUpdate extends Fragment {
    private final Handler mHandler = new Handler();
    private Runnable mTimer;
    private LineGraphSeries<DataPoint> mSeries;
    private double graph2LastXValue = 5d;
    private int value;
    private String TAG = "FRAGMENT";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        GraphView graph = (GraphView) rootView.findViewById(R.id.graph);
        mSeries = new LineGraphSeries<DataPoint>();
        graph.addSeries(mSeries);
        graph.getViewport().setXAxisBoundsManual(true);
        graph.getViewport().setMinX(0);
        graph.getViewport().setMaxX(40);

        return rootView;
   }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
        mTimer = new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "onResume");
                graph2LastXValue += 1d;
                mSeries.appendData(new DataPoint(graph2LastXValue, value), true, 40);
                mHandler.postDelayed(this, 1000);
            }

        };
        mHandler.postDelayed(mTimer, 300);
     }

I have to update this graph with the data of my Main_Activity.

MainActivity at runtime send some data to my Fragment. GraphUpdate update the graph with the data.

what is the best way? I have read how to send the data from activity to fragment with Interface or Bundle, but for keep updated the graph what the best solution is?


Solution

  • just create a method in fragment which actually update your graph .and using fragment object from your activity call update graph method which you already declare in fragment simple.e.x.

    frag=(cast)getSupportFragmentManager().findFragmentByTag("fragment tag");
    frag.updateGraph() from your activity. 
    and declare updateGraph method in fragment.