首页 > 解决方案 > 分片方法不重复

问题描述

我正在片段中创建一个带有 MPandroid 图表的折线图。我制作了折线图并添加了代码以输入自定义值。使用 Logcat 跟踪,我发现问题是片段中的 setdata() 方法只会在应用首次启动时运行,而不是在您返回片段屏幕时运行。这意味着数据集不会更新,因此图表不会更新。

Graph.java(显示图表的片段)

public class Graph extends Fragment {

    public Graph() {
        // Required empty public constructor
    }

    private LineChart mChart;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_graph, container, false);
        Log.e("create","graph oncreate method reached");
        //initialize chart
        mChart = view.findViewById(R.id.chart);
        //set description
        Description description = new Description();
        description.setText("Blood glucose levels");
        mChart.setDescription(description);
        //set description if no data is available
        mChart.setNoDataText("No Data Available. Add a blood glucose level input to see your graph");
        //enable touch gestures
        mChart.setTouchEnabled(true);
        //enable scaling and dragging
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(true);
        //draw background grid
        mChart.setDrawGridBackground(true);
        //draw x-axis
        XAxis xAxis = mChart.getXAxis();
        xAxis.setEnabled(false);
        // setting position to TOP and INSIDE the chart
        xAxis.setPosition(XAxis.XAxisPosition.TOP_INSIDE);
        //  setting text size for our axis label
        xAxis.setTextSize(10f);
        xAxis.setTextColor(Color.BLACK);
        // to draw axis line
        xAxis.setDrawAxisLine(true);
        xAxis.setDrawGridLines(false);

        YAxis yAxis = mChart.getAxisLeft();
        // setting the count of Y-axis label's
        yAxis.setLabelCount(12, false);
        yAxis.setTextColor(Color.BLACK);
        yAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        yAxis.setDrawGridLines(true);

        //add upper limit line
        LimitLine upper = new LimitLine(8, "Above target range");
        upper.setLineColor(Color.parseColor("#bb2d2d"));
        upper.setLineWidth(3f);
        upper.enableDashedLine(10f, 10f, 0f);
        upper.setTextColor(Color.BLACK);
        upper.setTextSize(9f);
        yAxis.addLimitLine(upper);
        //add lower limit line
        LimitLine lower = new LimitLine(4, "Below target range");
        lower.setLineColor(Color.parseColor("#2c8ec7"));
        lower.setLineWidth(3f);
        lower.enableDashedLine(10f, 10f, 0f);
        lower.setTextColor(Color.BLACK);
        lower.setTextSize(9f);
        yAxis.addLimitLine(lower);

        yAxis.setDrawLimitLinesBehindData(true);

        mChart.getAxisRight().setEnabled(false);
        mChart.getLegend().setEnabled(false);

        // add data
        setData();

        mChart.notifyDataSetChanged();
        mChart.invalidate();



        return view;
    }


    private void setData() {

        ArrayList<Entry> values = new ArrayList<>();
        values.add(new Entry(0, (float) 4.8));
        Log.e("set", "method reached");


        LineDataSet set1;
        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            set1 = new LineDataSet(values, "Blood Glucose Levels");
            set1.setDrawIcons(false);
            set1.setLineWidth(4f);
            set1.setCircleRadius(5f);
            set1.setDrawCircleHole(false);
            set1.setValueTextSize(10f);
            set1.setFormLineWidth(1f);
            set1.setFormSize(15.f);
            set1.setColor(Color.BLACK);
            set1.setCircleColor(Color.BLACK);
        }
        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(set1);
        LineData data = new LineData(dataSets);
        mChart.setData(data);
        mChart.notifyDataSetChanged();
        mChart.invalidate();
//add new input data if bundle isn't null
        if (getArguments() != null) {
            Log.e("if", "if reached");
            float myDataSet = Float.parseFloat(getArguments().getString("INPUT"));
            Log.e("data", "data retrieved");
            float count = 0;
            float mcount = count + 1;
            values.add(new Entry(mcount, myDataSet));

            data.notifyDataChanged();
            mChart.notifyDataSetChanged();
            mChart.invalidate();
        }

    }
}

Tabbed.java(片段的基础 java 类)(仅包含相关代码)

public class Tabbed extends AppCompatActivity {

    private InputViewModel mInputViewModel;
    private static final int MY_PERMISSIONS_REQUEST_SEND_SMS = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tabbed);
        androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        InputRoomDatabase db = Room.databaseBuilder(getApplicationContext(), InputRoomDatabase.class, "input_database")
                .build();

        // Create an instance of the tab layout from the view.
        TabLayout tabLayout = findViewById(R.id.tab_layout);
        // Set the text for each tab.
        tabLayout.addTab(tabLayout.newTab().setText(R.string.graph));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.table));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.analysis));

        // Set the tabs to fill the entire layout.
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        // Use PagerAdapter to manage page views in fragments.
        // Each page is represented by its own fragment.
        final ViewPager viewPager = findViewById(R.id.pager);
        final PagerAdapter adapter = new PagerAdapter
                (getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);

        // Setting a listener for clicks.
        viewPager.addOnPageChangeListener(new
                TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(
                new TabLayout.OnTabSelectedListener() {
                    @Override
                    public void onTabSelected(TabLayout.Tab tab) {
                        viewPager.setCurrentItem(tab.getPosition());
                    }

                    @Override
                    public void onTabUnselected(TabLayout.Tab tab) {
                    }

                    @Override
                    public void onTabReselected(TabLayout.Tab tab) {
                    }
                });
    }
//getting inputs from room and putting them into the view in table
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mInputViewModel = ViewModelProviders.of(this).get(InputViewModel.class);
        //only add if there is a new input
        if (requestCode == INPUT_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
            //retrieve input from room database
            Input1 input1 = new Input1(data.getStringExtra(input.EXTRA_REPLY));
            //insert the inputs into the view model of the recyclerView
            mInputViewModel.insert(input1);

            //convert the String input1 to a double
            Double d = Double.parseDouble(input1.getValue());

            //send d value to graph.java
            Bundle bundle = new Bundle();
            Log.e("Testing", "Bundle made");
            bundle.putString("INPUT", String.valueOf(d));
            Graph myObj = new Graph();
            myObj.setArguments(bundle);

            }

            //display pop-up if no input is added don't save the input
        } else {
            Toast.makeText(
                    getApplicationContext(),
                    R.string.empty_not_saved,
                    Toast.LENGTH_LONG).show();
        }
    }
        public static final int INPUT_ACTIVITY_REQUEST_CODE = 1;

}

日志猫:

2019-09-19 11:42:55.074 16844-16844/com.example.mysugartracker E/create: graph oncreate method reached
2019-09-19 11:42:55.076 16844-16844/com.example.mysugartracker E/set: method reached
2019-09-19 11:42:55.121 16844-16844/com.example.mysugartracker E/table: table oncreate method reached
2019-09-19 11:43:00.869 16844-16844/com.example.mysugartracker E/Testing: Bundle made
2019-09-19 11:43:00.871 16844-16844/com.example.mysugartracker E/hello: text sent

仅针对某些情况:数据由用户在单独的活动中输入,然后保存在房间数据库中。其中一个片段显示了输入的 recyclerview 列表(工作正常),另一个片段应在折线图中显示输入。该应用程序运行良好,没有错误或崩溃,但输入未显示在图表中。

我在网上找到的所有内容都说要刷新您只需要调用mChart.notifyDataSetChanged(); mChart.invalidate(); 我所做的数据,但数据仍然没有显示。从我的 logcat 中,我知道 setdata() 方法在提交输入时不会再次运行。

我需要一种方法来修复我的代码,以便数据动态更新,或者某种方法来确保再次调用 setdata()。

谢谢您的帮助!

标签: androidandroid-studioandroid-fragmentsmethodsmpandroidchart

解决方案


从我可以看到您对 setData 的调用在 onCreateView 中。如果视图只创建一次,那么它只会被调用一次。

如果您继续进行另一项活动,然后返回此活动,就会发生这种情况。由于活动没有被破坏,它不会被重新创建,它将使用已经存在的活动。

每当您显示片段时,您都需要更新数据。为此,在片段中使用 onResume。

@Override
public void onResume(){
    super.onResume();

    setData();
}

推荐阅读