native-kline-view
native-kline-view copied to clipboard
fix: guard getItem against null/empty data and out-of-range index
Summary
This PR hardens data access in the Android native K-line chart module by making getItem(int position) null-safe and index-safe in BaseKLineChartView.
The change prevents runtime crashes when chart data is empty, not initialized, or when an out-of-range index is requested during rendering/interaction.
Scope
Only the following file is included in this PR scope:
src/native-modules/native-kline-view/android/src/main/java/com/github/fujianlian/klinechart/BaseKLineChartView.java
Problem
Previously, getItem(int position) directly returned:
configManager.modelArray.get(position)
This could fail in common edge cases:
modelArrayisnull(data not ready yet)modelArrayis emptypositionis out of bounds (negative or larger than last index)
Any of the above could trigger exceptions and cause chart instability/crashes.
What Changed
getItem(int position) now:
- Computes a safe size:
size = (modelArray == null) ? 0 : modelArray.size()
- Handles empty/unavailable data:
- returns a fallback
KLineEntitywithDate = ""whensize <= 0
- returns a fallback
- Clamps index to valid range:
safeIndex = Math.max(0, Math.min(position, size - 1))
- Reads item using safe index:
modelArray.get(safeIndex)
Why This Approach
- Keeps method behavior predictable under transient/edge states.
- Prevents crashes without requiring upstream callers to add repetitive bounds/null checks.
- Minimizes surface area of change by localizing safety logic inside one accessor method.
Expected Impact
- Improved robustness during chart initialization and fast state transitions.
- Safer behavior when gesture/render logic requests boundary indices.
- No functional regression for normal in-range requests.
Risk Assessment
Low risk:
- Change is limited to one method.
- Normal path (
modelArraypresent + valid index) remains effectively unchanged. - Fallback behavior only applies to previously unsafe states.
Test Plan
Manual verification
- Open market chart with valid kline data and verify rendering unchanged.
- Open chart when data is delayed/empty and verify no crash.
- Perform fast interactions (scroll/scale/crosshair) during data refresh and verify stability.
Edge-case verification
- Simulate
modelArray = nulland confirm method returns fallback entity. - Simulate empty array and confirm method returns fallback entity.
- Request index
< 0and> size-1, confirm clamping works and no exception occurs.