我正在努力正确地获得折线图。我在Firestore数据库中有数据,并且从那里试图在折线图中显示温度读数。我正在使用Mp折线图的最新版本。我正在尝试将摄氏温度值转换为YAxis,将时间以HH:mm格式转换为xAxis。我已经尝试过用鬃毛的方式尝试这种方法,并且用谷歌搜索了不同的方法来做到这一点,但我做对了。值根本不显示,或者值显示在xAxis的错误位置。我也无法正确显示yAxis。有人已经在这里问过这个问题,答案是将偏移量设置为“ 60,0 50,60”,但这对我不起作用。
对于主要问题,我目前正在尝试使用GitHub指示的HourAxisValueFormatter。有它的文档,但我不明白如何使其工作。我是Android的To Mp库的新手,所以这很困难。 在我的活动代码和HourAxisValueFormatter下面
public class TempHistoryActivity extends AppCompatActivity {
private LineChart mChart;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private ArrayList<Integer> tempItemList;
private ArrayList<Long> timeList, convertedTimes;
private ArrayList<Date> dateList;
private Long reference;
private CollectionReference collectionReference = db.collection("whtitem");
private Toolbar toolbar;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temp_history);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
tempItemList = new ArrayList<>();
timeList = new ArrayList<>();
dateList = new ArrayList<>();
convertedTimes = new ArrayList<>();
mChart = findViewById(R.id.tempLineChart);
mChart.setTouchEnabled(true);
mChart.setPinchZoom(true);
Marker mv = new Marker(getApplicationContext(), R.layout.custom_marker_view);
mv.setChartView(mChart);
mChart.setMarker(mv);
mChart.setViewPortOffsets(60, 0, 50, 90);
mChart.setExtraLeftOffset(40);
retrieveDayDataFromDatabase();
}
private void retrieveDayDataFromDatabase() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date currentDate = calendar.getTime();
Calendar cals = Calendar.getInstance();
cals.add(Calendar.DAY_OF_YEAR, +1);
Date tomorrow = cals.getTime();
collectionReference.whereEqualTo("userId", WhtApi.getInstance()
.getUserId())
.orderBy("date", Query.Direction.ASCENDING)
.startAt(currentDate)
.endAt(tomorrow)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()){
dateList.clear();
tempItemList.clear();
for (QueryDocumentSnapshot whtitems : queryDocumentSnapshots) {
WhtItem whtItem = whtitems.toObject(WhtItem.class);
dateList.add(whtItem.getDate());
tempItemList.add(whtItem.getTemperature());
Log.d("temps", "retrieveDayDataFromDatabase: " + tempItemList);
}
Calendar cal = Calendar.getInstance();
for (int i = 0; i < dateList.size(); i++){
Date date = dateList.get(i);
Long time = Long.valueOf(date.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
//String time = DateFormat.format("HH:mm", dateList.get(i)).toString();
/* cal.setTime(dateList.get(i));
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
String t = hour +":"+minute+0;
Log.d("st", "retrieveDayDataFromDatabase: " + t);
DecimalFormatSymbols symbol = new DecimalFormatSymbols();
symbol.setDecimalSeparator(':');
DecimalFormat decimalFormat = new DecimalFormat("0.##");
NumberFormat format = NumberFormat.getInstance(Locale.US);
format.setMaximumFractionDigits(3);
format.setMinimumFractionDigits(3);
float time = 0;
try {
time = decimalFormat.parse(t).floatValue();
Log.d("timef", "retrieveDayDataFromDatabase: " + time);
} catch (ParseException e) {
e.printStackTrace();
}
Float newValue = new Float(format.format(time));
BigDecimal decimal = new BigDecimal(t).setScale(2);
Log.d("decimal", "retrieveDayDataFromDatabase: " + decimal);*/
timeList.add(time);
}
renderDayData();
}else {
Toast.makeText(TempHistoryActivity.this, "Ei lämpötilakirjauksia vielä", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(e -> Toast.makeText(TempHistoryActivity.this, "Tapahtui virhe dataa haettaessa", Toast.LENGTH_SHORT).show());
}
public void renderDayData() {
Collections.sort(timeList);
for (int i = 0; i<timeList.size(); i++){
reference = timeList.get(0);
Long Xnew = (timeList.get(1)) - reference;
convertedTimes.add(Xnew);
Log.d("converted", "renderDayData: "+ convertedTimes);
}
LimitLine llXAxis = new LimitLine(10f, "Index 10");
llXAxis.setLineWidth(4f);
llXAxis.enableDashedLine(10f, 10f, 0f);
llXAxis.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
llXAxis.setTextSize(10f);
XAxis xAxis = mChart.getXAxis();
xAxis.setValueFormatter(new HourAxisValueFormatter(reference));
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.enableGridDashedLine(10f, 10f, 0f);
xAxis.setAxisMinimum(0f);
xAxis.setAxisMaximum(10f);
xAxis.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
xAxis.setGranularity(1f);
xAxis.setDrawLimitLinesBehindData(true);
LimitLine ll1 = new LimitLine(33f, "Lämpöraja 33°C");
ll1.setLineWidth(4f);
ll1.enableDashedLine(10f, 10f, 0f);
ll1.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
ll1.setTextSize(15f);
ll1.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
YAxis leftAxis = mChart.getAxisLeft();
leftAxis.setValueFormatter(new IndexAxisValueFormatter(getTemperature()));
leftAxis.enableGridDashedLine(10f, 10f, 0f);
leftAxis.removeAllLimitLines();
leftAxis.addLimitLine(ll1);
leftAxis.setDrawZeroLine(false);
leftAxis.setAxisMinimum(0f);
leftAxis.setAxisMaximum(100f);
leftAxis.setDrawLimitLinesBehindData(false);
leftAxis.setDrawGridLines(true);
leftAxis.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
mChart.getAxisRight().setEnabled(false);
mChart.invalidate();
setDayData();
}
public ArrayList<String> getDate(){
ArrayList<String> label = new ArrayList<>();
for(int i=0; i<dateList.size(); i++){
String date = DateFormat.format("dd.MM.", dateList.get(i)).toString();
label.add(date);
}return label;
}
public ArrayList<String> getTime(){
ArrayList<String> times = new ArrayList<>();
for(int i=0; i<values.length; i++){
times.add( values[i]);
}return times;
}
public ArrayList<String> getTemperature(){
ArrayList<String> temps = new ArrayList<>();
for(int i=0; i < tempItemList.size(); i++){
String temp = tempItemList.get(i) + "°C";
temps.add(temp);
Log.d("templist", "getTemperature: " + temps);
}return temps;
}
private void setDayData() {
ArrayList<Entry> values = new ArrayList<>();
values.clear();
for (int i =0 ; i < timeList.size(); i++){
values.add(new Entry(i, tempItemList.get(i)));
Log.d("list", "setDayData: " + timeList.get(i));
Log.d("values", "setData: " + values);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Collections.sort(values, new EntryXComparator());
}
LineDataSet set1;
if (mChart.getData() != null &&
mChart.getData().getDataSetCount() > 0) {
set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);
set1.setValues(values);
mChart.getData().notifyDataChanged();
mChart.notifyDataSetChanged();
} else {
set1 = new LineDataSet(values, "Lämpötiladata");
set1.setDrawIcons(false);
set1.enableDashedLine(10f, 5f, 0f);
set1.enableDashedHighlightLine(10f, 5f, 0f);
set1.setColor(ContextCompat.getColor(this, R.color.colorPrimary));
set1.setCircleColor(ContextCompat.getColor(this, R.color.colorPrimary));
set1.setLineWidth(1f);
set1.setCircleRadius(3f);
set1.setDrawCircleHole(false);
set1.setValueTextSize(9f);
set1.setDrawFilled(true);
set1.setFormLineWidth(1f);
set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
set1.setFormSize(15.f);
if (Utils.getSDKInt() >= 18) {
Drawable drawable = ContextCompat.getDrawable(this, R.drawable.gradient);
set1.setFillDrawable(drawable);
} else {
set1.setFillColor(ContextCompat.getColor(this, R.color.colorPrimary));
}
ArrayList<ILineDataSet> dataSets = new ArrayList<>();
dataSets.add(set1);
LineData data = new LineData(dataSets);
mChart.setData(data);
Description description = new Description();
description.setText("");
mChart.setDescription(description);
mChart.invalidate();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.profile:
if (user != null && firebaseAuth != null) {
startActivity(new Intent(TempHistoryActivity.this, ProfileActivity.class));
//finish();
}
break;
case R.id.mainpage:
if (user != null && firebaseAuth != null) {
startActivity(new Intent(TempHistoryActivity.this, MainPageActivity.class));
//finish();
}
break;
case R.id.temp_history:
if (user != null && firebaseAuth != null) {
startActivity(new Intent(TempHistoryActivity.this, TempHistoryActivity.class));
//finish();
}
break;
case R.id.pulse_history:
if (user != null && firebaseAuth!=null) {
startActivity(new Intent(TempHistoryActivity.this, PulseHistoryActivity.class));
//finish();
}
break;
case R.id.time_in_temp_history:
if (user != null && firebaseAuth != null) {
startActivity(new Intent(TempHistoryActivity.this, TimeTempActivity.class));
//finish();
}
break;
case R.id.action_signout:
//signout
if (user != null && firebaseAuth != null) {
firebaseAuth.signOut();
startActivity(new Intent(TempHistoryActivity.this, MainActivity.class));
//finish();
}
break;
}
return super.onOptionsItemSelected(item);
}
}
public class HourAxisValueFormatter extends ValueFormatter
{
private long referenceTimestamp; // minimum timestamp in your data set
private DateFormat mDataFormat;
private Date mDate;
public HourAxisValueFormatter(long referenceTimestamp) {
this.referenceTimestamp = referenceTimestamp;
this.mDataFormat = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
this.mDate = new Date();
}
@Override
public String getFormattedValue(float value){
// convertedTimestamp = originalTimestamp - referenceTimestamp
long convertedTimestamp = (int) value;
// Retrieve original timestamp
long originalTimestamp = referenceTimestamp + convertedTimestamp;
// Convert timestamp to hour:minute
return getHour(originalTimestamp);
}
public int getDecimalDigits()
{
return 0;
}
private String getHour(long timestamp){
try{
mDate.setTime(timestamp*1000);
return mDataFormat.format(mDate);
}
catch(Exception ex){
return "xx";
}
}
}
这是我的输出atm output
这就是我想要得到的 enter image description here
我希望xAxis值是“ 07:00、08:00、09:00、10:00、11:00、12:00、13:00、14:00、15:00、16:00 ,17:00“