I am looking ways to create a line chart using AnyChart library in android. The values are coming dynamically through my api link (in json format).I have tried many times but wasn't able to do it. Some help would be appreciated. Thank you.
The code is as folllows-
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("status");
String cdata = jsonObject.getString("chart_data"); // for extra condition
final JSONArray jsonArray1 = jsonObject.getJSONArray("chart_data");
if (success.equals("true") && !cdata.equals(null)) {
for (int i = 0; i < jsonArray1.length(); i++) {
JSONObject object1 = jsonArray1.getJSONObject(i);
String devinfo = object1.getString("Device Info");
dev[i] = object1.getString("Device Info");
String value = object1.getString("Value");
// chart AnyChart
Cartesian cartesian = AnyChart.line();
cartesian.animation(false);
cartesian.padding(10d, 20d, 5d, 20d);
cartesian.crosshair().enabled(true);
cartesian.crosshair()
.yLabel(true)
// TODO ystroke
.yStroke((Stroke) null, null, null, (String) null, (String) null);
cartesian.tooltip().positionMode(TooltipPositionMode.POINT);
// cartesian.title("Trend of Sales of the Most Popular Products of ACME Corp.");
// cartesian.yAxis(0).title("Number of Bottles Sold (thousands)");
cartesian.xAxis(0).labels().padding(1d, 1d, 1d, 1d);
List<DataEntry> seriesData = new ArrayList<>();
seriesData.add(new CustomDataEntry(dev[i], Integer.parseInt(value)));
Set set = Set.instantiate();
set.data(seriesData);
Mapping series1Mapping = set.mapAs("{ x: 'x', value: 'value' }");
// Mapping series2Mapping = set.mapAs("{ x: 'x', value: 'value2' }");
// Mapping series3Mapping = set.mapAs("{ x: 'x', value: 'value3' }");
Line series1 = cartesian.line(series1Mapping);
series1.name("Brand");
series1.hovered().markers().enabled(true);
series1.hovered().markers()
.type(MarkerType.SQUARE)
.size(4d);
series1.tooltip().position("right")
.anchor(Anchor.RIGHT_CENTER)
.offsetX(5d)
.offsetY(5d);
cartesian.legend().enabled(true);
cartesian.legend().fontSize(13d);
cartesian.legend().padding(0d, 0d, 10d, 0d);
anyChartView.setChart(cartesian);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
In your code, you recreate the chart, series, List of DataEntries and config the chart for every point. To create the chart correctly and apply the data from DB you should execute the following steps in order: