亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何防止將用戶輸入添加到 MPandroidchart 時出現

如何防止將用戶輸入添加到 MPandroidchart 時出現

小怪獸愛吃肉 2023-07-28 16:06:02
我使用 MPandroidchart 在 android studio 上的片段中創建了一個折線圖,并使其圖表的點來自用戶輸入。但是,我收到錯誤“java.lang.NullPointerException”。我知道此錯誤是由于嘗試使用空值引起的,但我不確定如何在我的情況下修復它。編輯:用戶輸入保存在房間數據庫中我從一個方法中檢索用戶輸入,該方法中有代碼確保輸入為空時不會保存。我認為問題是因為圖表正在嘗試在用戶添加數據之前構建,因為輸入選項是顯示圖表的片段的一部分,因此圖表正在嘗試在數據準備好之前構建。Graph.javapublic 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);        //initialize input1 database        InputRoomDatabase db = Room.databaseBuilder(getActivity(),InputRoomDatabase.class, "input_database")                .build();        //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);    }當我運行應用程序時,它崩潰并給出此錯誤 java.lang.NullPointerException: Attempt to invoke virtual method 'double android.os.Bundle.getDouble(java.lang.String)' on a null object reference 我已在 Graph.java 中用 ** 標記了問題代碼正如我所說,我認為問題在于圖表正在嘗試在數據準備好之前構建,但我不確定如何避免這個問題。
查看完整描述

1 回答

?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

代碼:

Double?d?=?getActivity().getIntent().getExtras().getDouble("STRING_I_NEED");
float?myDataSet?=?d.floatValue();

假設 4 個方法調用都返回非空值。請參閱庫方法的文檔,了解它們何時可能返回null,以及一般如何避免令人不快的意外。

文檔說getExtras()返回

之前用 putExtra() 添加的所有額外內容的映射,如果沒有添加則為 null。

當調用可以返回 的庫方法時null,您的代碼應該檢查結果null(或捕獲NullPointerException),或確保這種情況不會發生,或兩者兼而有之。

  • 由于Intents來自系統的其余部分,因此您不能保證它們總是有額外的內容,因此代碼需要在調用之前測試getExtras()is的結果,并妥善處理。nullgetDouble()

  • 您還需要調試為什么它Intent沒有您期望的額外內容。

  • 如果Intent具有額外項,但這些額外項沒有名為 的雙精度值"STRING_I_NEED",則將getDouble("STRING_I_NEED")返回0.0。您可能需要將顯式傳遞defaultValuegetDouble()或測試Bundle?containsKey("STRING_I_NEED").

  • 如果您想要浮點值,請考慮調用getFloat()而不是getDouble().?我認為這會將雙精度值轉換為浮點數。


查看完整回答
反對 回復 2023-07-28
  • 1 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號