Android: GraphView How do I implement time in the X axis? - android

I'm finding it a bit difficult to figure out how to implement time in the X Axis of a graph in Android?
This is my code:
for (int i = 0; i < listSize; i++)
{
String[] onlyReading = mData.get(i).getReading().split(" ");
readingList[i] = Double.parseDouble(onlyReading[0]);
String date = mData.get(i).getUnFormatedDate();
String[] temp = date.split(" ");
String[] dateTemp = null;
String[] timeTemp = null;
if(temp.length > 0)
{
dateTemp = temp[0].trim().split("-");
timeTemp = temp[1].trim().split(":");
Date dateObj = new Date();
String year = "0";
if(dateTemp != null)
{
dateObj.setDate(Integer.parseInt(dateTemp[0]));
dateObj.setMonth(Integer.parseInt(dateTemp[1]) - 1);
year = dateTemp[2].trim();
if(dateTemp[2].trim().length() == 4)
{
year = dateTemp[2].substring(2, 4);
}
dateObj.setYear(Integer.parseInt(year)+100);
}
if(timeTemp != null)
{
calendar = new GregorianCalendar(Integer.parseInt(year) + 2000, Integer.parseInt(dateTemp[1]) - 1, Integer.parseInt(dateTemp[0]), Integer.parseInt(timeTemp[0]), Integer.parseInt(timeTemp[1]));
}
dateObj = new Date(calendar.getTimeInMillis());
dateList[i] = dateObj;
}
}
if(dateList.length > 0)
{
//dates.clear();
//values.clear();
//readingData.clear();
//readingDate.clear();
GraphViewData[] data = new GraphViewData[dateList.length];
LineGraphView graphView = new LineGraphView(
getActivity() // context
, "" // heading
);
for (int i = 0; i < listSize; i++)
{
data[i] = new GraphViewData(Double.valueOf(i), readingList[i]);
}
GraphViewSeries exampleSeries = new GraphViewSeries(data);
graphView.addSeries(exampleSeries);
graphView.setDrawBackground(false);
((LineGraphView) graphView).setDrawDataPoints(true);
graphView.getGraphViewStyle().setGridColor(0);
graphView.getGraphViewStyle().setHorizontalLabelsColor(Color.WHITE);
graphView.getGraphViewStyle().setVerticalLabelsColor(Color.WHITE);
graphView.getGraphViewStyle().setNumHorizontalLabels(5);
graphView.getGraphViewStyle().setNumVerticalLabels(5);
graphView.setManualYAxisBounds(400, 0);
mGraphParent.addView(graphView);
}
}
Even though I add the Y axis values, I'm not able to figure out how to add time values to the X-axis?

I know it is an old question, but I solved by using DefaultLabelFormatter().
graphView.getGridLabelRenderer().setLabelFormatter(new DefaultLabelFormatter() {
#Override
public String formatLabel(double value, boolean isValueX) {
if (isValueX) {
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return formatter.format(value);
}
return super.formatLabel(value, isValueX);
}
});
Based on the following video:
https://www.youtube.com/watch?v=xt8gx7Z7yJU

the trick is to just convert the time to seconds or milliseconds (unix time) and you it as X-value.
There's an example on the GraphView-Demos project. Take a look at:
https://github.com/jjoe64/GraphView-Demos/blob/master/src/com/jjoe64/graphviewdemos/CustomLabelFormatterActivity.java#L68

I had the same issue. The easiest method was to convert Time into milliseconds. Using a Gregorian Calendar might be more helpful as the methods in Date are deprecated.
Calendar cal=new GregorianCalendar(2014,6,12,9,30,0);
data[i]=new GraphViewData(cal.getTimeInMillis,VALUE);
Then set the CustomLabelFormatter.
graphView.setCustomLabelFormatter(new CustomLabelFormatter() {
#Override
public String formatLabel(double value, boolean isValueX) {
// TODO Auto-generated method stub
if (isValueX) {
Date d = new Date((long) (value));
return (dateFormat.format(d));
}
return "" + (int) value;
}
});
Time/Date appears in the format specified in dateFormat.

Related

How to set the starting point of x value to 0?

I want to set the starting point of x value to 0 instead of -1 when there is one data.
This is my execution screen. enter image description here
I tried many methods, but it didn't work.
Does anyone know a solution?
ArrayList values = new ArrayList<>();
for (int i = 0; i < userDataList.size(); i++) {
int time = userDataList.get(i).getTime();
values.add(new Entry(i, time));
}
final ArrayList<String> xLabelList = new ArrayList<String>();
for (int i = 0; i < userDataList.size(); i++) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMdd");
Date date = null;
try {
date = simpleDateFormat.parse(Float.toString(userDataList.get(i).getDate()));
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat newFormat = new SimpleDateFormat("MM/dd");
String dateString = newFormat.format(date);
xLabelList.add(dateString);
}
xAxis.setValueFormatter(new ValueFormatter() {
#Override
public String getFormattedValue(float value) {
if(value<0)
return xLabelList.get(0);
return xLabelList.get((int) value);
}
});
You can try using xAxis.setAvoidFirstLastClipping(true) (it's Kotlin) so that the first and the last labels will be hidden.

How to get entries to match xAxis values MP line chart, Android

I am struggling to get a line chart correctly. I have data in Firestore database and from there I am trying to display temperature readings in a line chart. I am using the latest version of Mp line chart. I am trying to get the temperature values in Celsius to YAxis and the time in HH:mm format to the xAxis. I have tried this in mane ways and googled different ways to do this and I just can't get it right. Either the values don't show at all or the values show but in the wrong spot of the xAxis. also I can't get the yAxis showing correctly. Someone has asked about that here already and the answer was to put the ofset "60, 0 50, 60" but that don't work for me.
For the main issue I am currently trying to use the HourAxisValueFormatter which was instructed in GitHub. There is documentation of it but I can't understand how to get it working. I am new to Android an To Mp library so that is why it is difficult.
Below my activity code and the 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";
}
}
}
Here is my output atm
output
and this is what I am trying to get
enter image description here
I want the xAxis values to be "07:00, 08:00, 09:00, 10:00, 11:00, 12:00, 13:00, 14:00, 15:00, 16:00, 17:00"

Mountain Chart Logarithmic

I'm trying to create a mountain chart using SciChart, but I need to create using Logarithmic, I tried the below code, but dont change chart and missing YAxis label.
I change the demo SciChart to it:
public class MountainChartFragment extends ExampleBaseFragment {
#BindView(R.id.chart)
SciChartSurface surface;
private double selectedLogBase = 10d;
#Override
protected int getLayoutId() {
return R.layout.example_single_chart_fragment;
}
#Override
protected void initExample() {
//final IAxis xBottomAxis = sciChartBuilder.newDateAxis().withGrowBy(0.1d, 0.1d).build();
final IAxis xBottomAxis = sciChartBuilder.newDateAxis().withGrowBy(0.1d, 0.1d).build();
final IAxis yRightAxis = sciChartBuilder.newLogarithmicNumericAxis().withScientificNotation(ScientificNotation.LogarithmicBase).withLogarithmicBase(selectedLogBase).withGrowBy(0.1d, 0.1d).build();
//final IAxis yRightAxis = sciChartBuilder.newNumericAxis().withGrowBy(0.1d, 0.1d).build();
final PriceSeries priceData = DataManager.getInstance().getPriceDataIndu(getActivity());
final IXyDataSeries<Date, Double> dataSeries = sciChartBuilder.newXyDataSeries(Date.class, Double.class).build();
dataSeries.append(priceData.getDateData(), priceData.getCloseData());
final FastMountainRenderableSeries rSeries = sciChartBuilder.newMountainSeries()
.withZeroLine(0.001)
.withDataSeries(dataSeries)
.withStrokeStyle(0xAAFFC9A8, 1f, true)
.withAreaFillLinearGradientColors(0xAAFF8D42, 0x88090E11)
.build();
UpdateSuspender.using(surface, new Runnable() {
#Override
public void run() {
Collections.addAll(surface.getXAxes(), xBottomAxis);
Collections.addAll(surface.getYAxes(), yRightAxis);
Collections.addAll(surface.getRenderableSeries(), rSeries);
Collections.addAll(surface.getChartModifiers(), sciChartBuilder.newModifierGroupWithDefaultModifiers().build());
sciChartBuilder.newAnimator(rSeries).withWaveTransformation().withInterpolator(new DecelerateInterpolator()).withDuration(3000).withStartDelay(350).start();
}
});
}
}
But dont worked
There are no labels because default TickProvider implementation for LogarithmicNumericAxis can't generate any ticks for auto calculated VisibleRange which is set for YAxis ( it has next values - Min = 10460.814629837885, Max = 13048.710993563885) The nearest values which which would satisfy LogBase = 10 would be 10000 and then 100000 and data set of example lies between these two values so TickProvider returns zero values to render.
In this case there are two possible workarounds:
Try to pick up some other LogBase value;
Set some alternative TickProvider implementation for YAxis (e.g. you can try to use TickProvider for NumericAxis or create your own implementation):
yRightAxis.setTickProvider(new NumericTickProvider());
I change the code and worked well. This is my code:
xAxis = sciChartBuilder.newNumericAxis().withGrowBy(0.1d, 0.1d).withVisibleRange(1.1, 2.7).build();
yAxis = generateLogarithmicAxis();
//yAxis = sciChartBuilder.newNumericAxis().withGrowBy(0.1d, 0.1d).build();
//yAxis.setTickProvider(new NumericTickProvider());
final SimpleDateFormat formatDate = new SimpleDateFormat("yyyyMMdd");
String data1 = "20190401";
Date date1 = null;
Calendar c = Calendar.getInstance();
final IXyDataSeries<Date, Double> dataSeries = sciChartBuilder.newXyDataSeries(Date.class, Double.class).build();
try {
date1 = formatDate.parse(data1);
for(int i = 0 ; i<1000 ; i+=10){
double random = Math.random() * 100.0 + 5;
dataSeries.append(date1, random);
c.setTime(date1);
c.add(Calendar.DATE, 1);
date1 = c.getTime();
}
} catch (ParseException e) {
e.printStackTrace();
}
final FastLineRenderableSeries rSeries = sciChartBuilder.newLineSeries().withZeroLine(0.01d).withDataSeries(dataSeries).withStrokeStyle(0xFF279B27, 1f, true).build();
UpdateSuspender.using(surface, new Runnable() {
#Override
public void run() {
Collections.addAll(surface.getXAxes(), xAxis);
Collections.addAll(surface.getYAxes(), yAxis);
Collections.addAll(surface.getRenderableSeries(), rSeries);
Collections.addAll(surface.getChartModifiers(), sciChartBuilder.newModifierGroupWithDefaultModifiers().build());
sciChartBuilder.newAnimator(rSeries).withSweepTransformation().withInterpolator(new DecelerateInterpolator()).withDuration(3000).withStartDelay(350).start();
}
});

Get time range in a formatted time list using current time

I have a formatted time list like following:
00:30:00 -
01:00:00 -
.
.
.
.
23:30:00
How can I get the range between currentTime-(1 hour) and currentTime+(3 hours) from that list in Android?
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("GTC"));
long now = Calendar.getInstance().getTimeInMillis();
Log.i("time", ""+now);
timeTableAdapter = new TimeTableAdapter(
TimeTableAdvanced.this, R.layout.timetable_item,
timeTableList);
adapterCount = timeTableAdapter.getCount();
for (int i = 0; i < adapterCount; i++) {
String inputString = timeTableList.get(i)
.getDepartureTime();
Date dat;
try {
dat = df.parse(inputString);
if (dat.getTime() <= now+(3*3600000) && dat.getTime() >= now-3600000 ) {
View item = timeTableAdapter.getView(i, null,
null);
timetablelayout.addView(item);
View line = new View(TimeTableAdvanced.this);
line.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, 1));
line.setBackgroundColor(getResources()
.getColor(R.color.black));
timetablelayout.addView(line);
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I don't see any difficulties here.
Suppose you have X = current time in millis
HOUR_IN_MILLIS = 3600000
Time A = X - 1 hrs = X - HOUR_IN_MILLIS millis
Time B = X + 3 hrs = X + (3 * HOUR_IN_MILLIS) millis
If you need a range in 1/2 hour intervals, you iterate
for (long i = A; i <= B; i =+ HOUR_IN_MILLIS/2) { //add time to list }
I solved my problem. Apparently, I was not only getting time but also date while taking miliseconds for current time. Here is the solution:
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
String date = df.format(Calendar.getInstance().getTime());
Date now;
long nowtime = 0;
try {
now = df.parse(date);
nowtime=now.getTime();
Log.i("time", ""+now);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
timeTableAdapter = new TimeTableAdapter(
TimeTableAdvanced.this, R.layout.timetable_item,
timeTableList);
adapterCount = timeTableAdapter.getCount();
for (int i = 0; i < adapterCount; i++) {
String inputString = timeTableList.get(i)
.getDepartureTime();
Date dat;
try {
dat = df.parse(inputString);
Log.i("time1", ""+dat.getTime());
Log.i("time2", ""+nowtime);
if (dat.getTime() <= nowtime+(3*3600000) && dat.getTime() >= nowtime-3600000 ) {
View item = timeTableAdapter.getView(i, null,
null);
timetablelayout.addView(item);
View line = new View(TimeTableAdvanced.this);
line.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, 1));
line.setBackgroundColor(getResources()
.getColor(R.color.black));
timetablelayout.addView(line);
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Achartengine Line Graph

I'm using Achartengine to create a Line Graph. My current month is showing however the second line, last month, isn't showing it. Here's the lass and logcat: So as you can see from the logcat my dates are correct and so is the count from the previous month. So why its not showing is beyond me.
Log Cat:
08-07 16:13:43.969: I/PROJECTCARUSO(11734): DEBUG startdate: 2013-07-01 enddate: 2013-07-31
08-07 16:13:43.969: I/PROJECTCARUSO(11734): count: 9
08-07 16:13:43.979: I/PROJECTCARUSO(11734): DEBUG startdate: 2013-08-01 enddate: 2013-08-31
Class:
public class TempHistoryFragment extends Fragment{
private GraphicalView mChartView;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
Calendar cal = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
SimpleDateFormat month_date = new SimpleDateFormat("MMMMMMMMM");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
String month_name = month_date.format(cal.getTime());
ArrayList<Integer> xArray = new ArrayList<Integer>();
ArrayList<Integer> yArray = new ArrayList<Integer>();
ArrayList<Integer> xArray2 = new ArrayList<Integer>();
ArrayList<Integer> yArray2 = new ArrayList<Integer>();
cal.add(Calendar.MONTH ,-1);
String prev_month_name = month_date.format(cal.getTime());
int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
//***********************************************//
// Our first data Last MONTH
//***********************************************//
//start date for cursor
//cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DATE, 1);
String startdate = df.format(cal.getTime());
//end date
cal.set(Calendar.DATE, daysInMonth);
String enddate = df.format(cal.getTime());
Log.i("PROJECTCARUSO","DEBUG startdate: " + startdate + " enddate: " + enddate);
Cursor c = getActivity().getContentResolver().query(StatusProvider.CONTENT_URI_CHARTING, null, "? < " + StatusData.KEY_CHARTING_DATE + " AND ? > " + StatusData.KEY_CHARTING_DATE , new String[] {startdate, enddate}, null); //
c.moveToFirst();
Log.i("PROJECTCARUSO","count: " + c.getCount());
if (c.getCount()>0 && c!=null) {
while (c.isAfterLast() == false) {
if ((isNumeric(c.getString(c.getColumnIndex(StatusData.KEY_CHARTING_TEMPERATURE))))) {
java.util.Date date = null;
int day = 0;
//get date from database
String datetest = c.getString(c.getColumnIndex(StatusData.KEY_CHARTING_DATE));
//try to reformat to date.
try {
date = format.parse(datetest);
day = date.getDate();
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
xArray.add(day);
}
c.moveToNext();
}
}
int[] x = new int[xArray.size()];
for (int i = 0; i < xArray.size(); i++) {
x[i] = xArray.get(i);
}
int[] y = new int[yArray.size()];
for (int i = 0; i < yArray.size(); i++) {
y[i] = yArray.get(i);
}
TimeSeries series = new TimeSeries(prev_month_name);
for( int i = 0; i < y.length; i++)
{
series.add(x[i], y[i]);
}
//***********************************************//
// Our second data THIS MONTH
//***********************************************//
//start date for cursor
cal2.set(Calendar.DATE, 1);
String startdate2 = df.format(cal2.getTime());
//end date
cal2.set(Calendar.DATE, daysInMonth);
String enddate2 = df.format(cal2.getTime());
Log.i("PROJECTCARUSO","DEBUG startdate: " + startdate2 + " enddate: " + enddate2);
Cursor c2 = getActivity().getContentResolver().query(StatusProvider.CONTENT_URI_CHARTING, null, "? < " + StatusData.KEY_CHARTING_DATE + " AND ? > " + StatusData.KEY_CHARTING_DATE , new String[] {startdate2, enddate2}, null); //
c2.moveToFirst();
if (c2.getCount()>0 && c2!=null) {
while (c2.isAfterLast() == false) {
if (isNumeric(c2.getString(c2.getColumnIndex(StatusData.KEY_CHARTING_TEMPERATURE)))){
yArray2.add(c2.getInt(c2.getColumnIndex(StatusData.KEY_CHARTING_TEMPERATURE)));
java.util.Date date = null;
int day = 0;
//get date from database
String datetest = c2.getString(c2.getColumnIndex(StatusData.KEY_CHARTING_DATE));
//try to reformat to date.
try {
date = format.parse(datetest);
day = date.getDate();
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
xArray2.add(day);
}
c2.moveToNext();
}
}
int[] x2 = new int[xArray2.size()];
for (int i = 0; i < xArray2.size(); i++) {
x2[i] = xArray2.get(i);
}
int[] y2 = new int[yArray2.size()];
for (int i = 0; i < yArray2.size(); i++) {
y2[i] = yArray2.get(i);
}
TimeSeries series2 = new TimeSeries(month_name);
for( int i = 0; i < x2.length; i++)
{
series2.add(x2[i], y2[i]);
}
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(series);
dataset.addSeries(series2);
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer(); // Holds a collection of XYSeriesRenderer and customizes the graph
XYSeriesRenderer renderer = new XYSeriesRenderer(); // This will be used to customize line 1
XYSeriesRenderer renderer2 = new XYSeriesRenderer(); // This will be used to customize line 2
mRenderer.addSeriesRenderer(renderer);
mRenderer.addSeriesRenderer(renderer2);
// Customization time for line 1!
renderer.setColor(getResources().getColor(R.color.complementary));
renderer.setPointStyle(PointStyle.SQUARE);
renderer.setFillPoints(true);
// Customization time for line 2!
renderer2.setColor(getResources().getColor(R.color.base));
renderer2.setPointStyle(PointStyle.DIAMOND);
renderer2.setFillPoints(true);
mChartView = ChartFactory.getLineChartView(getActivity(), dataset, mRenderer);
//Set Chart Title and labels
mRenderer.setChartTitle("Temperature Tracking");
mRenderer.setChartTitleTextSize(getResources().getDimension(R.dimen.largeText));
mRenderer.setLabelsColor(getResources().getColor(R.color.primaryTextDark));
//YAxis of Temp
mRenderer.setYTitle("Temperature", 0);
mRenderer.setYAxisMin(80, 0);
mRenderer.setYAxisMax(110, 0);
mRenderer.setYLabelsAlign(Align.CENTER);
mRenderer.setYLabelsColor(0, getResources().getColor(R.color.primaryTextDark));
//XAxis of month
mRenderer.setXLabels(20);
mRenderer.setXTitle(month_name);
mRenderer.setXAxisMin(1);
mRenderer.setXAxisMax(daysInMonth);
mRenderer.setXLabelsColor(getResources().getColor(R.color.primaryTextDark));
//Set the display
mRenderer.setMarginsColor(getResources().getColor(R.color.transparent));
mRenderer.setShowCustomTextGrid(true);
mRenderer.setAxisTitleTextSize(getResources().getDimension(R.dimen.mediumText));
mRenderer.setLabelsTextSize(getResources().getDimension(R.dimen.smallMediumText));
mRenderer.setPanEnabled(false, false);
mRenderer.setClickEnabled(false);
mRenderer.setZoomEnabled(false, false);
return mChartView;
}
#SuppressWarnings("unused")
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
}
Oh and here are those colors:
<color name ="base">#51bbc2</color>
<color name ="complementary">#C25951</color>
Thanks #Dan you lead me to the solution. I went and logged all the points to make sure all the right values were getting placed in the right array and come to find out yArray.add(c.getInt(c.getColumnIndex(StatusData.KEY_CHARTING_TEMPERATURE))); somehow got deleted. So now it works! Yay!

Categories

Resources