尝试使用Retrofit将数据从mysql拉入android并输出折线图。第一部分(提取数据)工作正常。在Android中将数据过滤到MPALinechart十分困难。
我希望折线图显示一段时间内用户的心情。因此,底轴将是一月,二月,三月等,而左轴将是他们的心情。
心情从0-4排名,其中0是负面情绪(如沮丧),4是正面情绪(如退出)。想法是,该行将向人们显示他们随着时间的推移的心情,并且他们可以看到自己的心情在哪几周/几月内消失。
到目前为止,我的代码:
// Retrofit call to the MYSQL server.
Call<List<MoodLogLineGraph>> call = RetrofitClient.getInstance().getApi().moodLogLineGraph(userId);
call.enqueue(new Callback<List<MoodLogLineGraph>>() {
@Override
public void onResponse(Call<List<MoodLogLineGraph>> call, Response<List<MoodLogLineGraph>> response) {
// All JSON entries form the MYSQL server are parsed into an ArrayList.
ArrayList<Entry> dataVals = new ArrayList<Entry>();
// For loop which dynamically adds all entries to the ArrayList
for (MoodLogLineGraph moodLogList : response.body()) {
moodLogList.getMoodName();
moodLogList.getPosted();
if (moodLogList.getMoodName().equals("Excited")) {
dataVals.add(new Entry(1, 3));
}
if (moodLogList.getMoodName().equals("Happy")) {
dataVals.add(new Entry(1, 1));
}
if (moodLogList.getMoodName().equals("Fine")) {
dataVals.add(new Entry(1, 0));
}
if (moodLogList.getMoodName().equals("Calm")) {
dataVals.add(new Entry(1, 1));
}
if (moodLogList.getMoodName().equals("Upset")) {
dataVals.add(new Entry(1, 1));
}
if (moodLogList.getMoodName().equals("Stressed")) {
dataVals.add(new Entry(1, 0));
}
if (moodLogList.getMoodName().equals("Anxious")) {
dataVals.add(new Entry(1, 1));
}
if (moodLogList.getMoodName().equals("Confused")) {
dataVals.add(new Entry(1, 1));
}
if (moodLogList.getMoodName().equals("Guilty")) {
dataVals.add(new Entry(1, 1));
}
if (moodLogList.getMoodName().equals("sad")) {
dataVals.add(new Entry(1, 1));
}
if (moodLogList.getMoodName().equals("Depressed")) {
dataVals.add(new Entry(1, 0));
}
}
//Initialising the PieChart variables which control the presentation.
LineDataSet lineDataSet1 = new LineDataSet(dataVals,"");
lineDataSet1.setColors(color);
lineDataSet1.setValueTextSize(14);
LineData lineDataSet = new LineData(lineDataSet1);
mLineChart.setData(lineDataSet);
mLineChart.invalidate();
mLineChart.setDrawGridBackground(false);
mLineChart.setTouchEnabled(true);
mLineChart.setDragEnabled(true);
mLineChart.setScaleEnabled(true);
mLineChart.setPinchZoom(true);
XAxis xl = mLineChart.getXAxis();
xl.setAvoidFirstLastClipping(true);
xl.setPosition(XAxis.XAxisPosition.BOTTOM);
final String[] months = new String[]{"Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Sep", "oct", "Nov", "Dec"};
IAxisValueFormatter formatter = new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return months[(int) value];
}
};
xl.setGranularity(1f); // minimum axis-step (interval) is 1
xl.setValueFormatter(formatter);
YAxis leftAxis = mLineChart.getAxisLeft();
leftAxis.setInverted(true);
YAxis rightAxis = mLineChart.getAxisRight();
rightAxis.setEnabled(false);
我不知道如何使用每一行数据并将其绘制在图表上。这需要从数据库中动态完成,而不是硬编码。如果有人能帮助我启动并运行此代码,我将不胜感激。