native-kline-view icon indicating copy to clipboard operation
native-kline-view copied to clipboard

fix: guard getItem against null/empty data and out-of-range index

Open shawerestart opened this issue 6 months ago • 0 comments

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:

  1. modelArray is null (data not ready yet)
  2. modelArray is empty
  3. position is 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:

  1. Computes a safe size:
    • size = (modelArray == null) ? 0 : modelArray.size()
  2. Handles empty/unavailable data:
    • returns a fallback KLineEntity with Date = "" when size <= 0
  3. Clamps index to valid range:
    • safeIndex = Math.max(0, Math.min(position, size - 1))
  4. 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 (modelArray present + 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 = null and confirm method returns fallback entity.
  • Simulate empty array and confirm method returns fallback entity.
  • Request index < 0 and > size-1, confirm clamping works and no exception occurs.

shawerestart avatar May 07 '26 08:05 shawerestart