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!
Related
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.
I am working on phonebook app in android which contains frequently called numbers activity too.I have got the list of numbers with the counter that how many times its have been called.But now i want only 10 most called numbers from that list.
Here is the working code:
I have sorted data using map.
Basically i wanted to sort the data by value which is counter of called numbers.
ListView list_view2;
String[] PERMISSIONS = {Manifest.permission.READ_CALL_LOG};
ArrayList<Integer> listdata2;
ArrayList<Integer> key;
ArrayList<Integer> value;
int maxIndex = 0;
Integer val;
HashMap<String, Integer> map = new HashMap<String, Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frequently_called);
list_view2 = findViewById(R.id.list_view2);
listdata2 = new ArrayList<Integer>();
getCallDetails();
}
#SuppressLint("LongLogTag")
private String getCallDetails() {
StringBuffer sb = new StringBuffer();
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.READ_CALL_LOG)
!= PackageManager.PERMISSION_GRANTED) {
requestContactsPermissions();
return requestContactsPermissions();
}
Cursor managedCursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, null);
Integer number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
while (managedCursor.moveToNext()) {
String phNumber = managedCursor.getString(number);
Integer callType = managedCursor.getInt(type);
Integer callDate = managedCursor.getInt(date);
Date callDayTime = new Date(Long.valueOf(callDate));
Integer callDuration = managedCursor.getInt(duration);
Log.e("Phone number", phNumber + "");
Log.e("call type", callType + "");
Log.e("call duration", callDuration + "");
// Log.e("call date", callDate + "");
Log.e("call day time", callDayTime + "");
String dir = null;
int dircode = new Integer(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
if (map.get(phNumber) == null) {
map.put(phNumber+"", 1);
} else {
Integer scount = map.get(phNumber).intValue();
scount++;
map.put(phNumber+"", scount);
//Log.e("map values", map + "");
}
}
managedCursor.close();
//Log.e("map.keySet()",map.keySet().toString());
HashSet<String> numbersset=new HashSet<String>(map.keySet());
ArrayList<String> numbers= new ArrayList<String>();
ArrayList<Integer> counts= new ArrayList<Integer>();
Iterator iterator=numbersset.iterator();
while(iterator.hasNext()) {
String no = iterator.next().toString();
numbers.add(no);
counts.add(map.get(no));
}
Log.e("number count ",numbers.size()+"|");
Log.e("count count ",counts.size()+"|");
for (int i=0;i<counts.size();i++){
for(int j=0;j<counts.size();j++){
int t1=counts.get(i);
int t2=counts.get(j);
if(t1 > t2){
for(t1=0;t1>=10;t1++) {
for(t2=0;t2>=10;t2++) {
int temp = counts.get(j);
counts.set(j, counts.get(i));
counts.set(i, temp);
String temps = numbers.get(j);
numbers.set(j, numbers.get(i));
numbers.set(i, temps);
}
}
}
}
}
//Sorting data in reverse
for (int i=0;i<counts.size();i++){
Log.e("sort-"+numbers.get(i),counts.get(i)+"");
}
return sb.toString();
}
private String requestContactsPermissions () {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CALL_LOG)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, 1);
} else {
ActivityCompat.requestPermissions(this, PERMISSIONS, 1);
}
return null;
}
}
For your count array.This will sort your counts array in descendingorder.
Comparator mycomparator = Collections.reverseOrder();
Collections.sort(counts,mycomparator);
now if you want to get 10 elements from your ArrayList.
ArrayList<Integer> popular_counts= new ArrayList<Integer>();
for(int i = 0; i< 9; i++){
popular_counts.add(counts.get(i));
}
popular_counts is your final ArrayList.
You can create loop that will be 10 times and another one which will search every time for the biggest counter and add the coresponding number to the new list.
#Override
protected void onCreate(Bundle savedInstanceState) { // Exaple to show result
ArrayList<String> number = new ArrayList<>();
number.add("0521392");
number.add("0521396");
number.add("0521397");
number.add("0521398");
number.add("0521391");
ArrayList<Integer> counts = new ArrayList<>();
counts.add(10);
counts.add(5);
counts.add(6);
counts.add(10);
counts.add(7);
for (String n : mostCalled(number, counts, 8)){ // Calling the function and printing the output
Log.i("go", "phone number: " + n);
}
}
private ArrayList<String> mostCalled(ArrayList<String> number, ArrayList<Integer> counts, int howMuchNumbersToShow){ // function that get list of phone numbers and list of how meany times each number called and return the howMuchNumbersToShow most called numbers (who called the most times)
if (number.size() != counts.size()){
return new ArrayList<>();
}
int biggerNumber = -1; // will store the current biggest number
int lastBiggerNumber = 10000000; // will store the last bigger number
int biggerNumberPlace = -1; // will store the place of the biggest number in the array
ArrayList<Integer> biggerNumberLocationList = new ArrayList<>(); // will store all the places of the biggest numbers in the array
if (howMuchNumbersToShow > number.size())
howMuchNumbersToShow = number.size();
for (int l=0; l<howMuchNumbersToShow; l++){
for (int x=0; x<counts.size(); x++){
if (!biggerNumberLocationList.contains(x)) // to get each number one time (help in case more then one phone number called the same amount)
if (counts.get(x) >= biggerNumber && counts.get(x)<= lastBiggerNumber){
biggerNumber = counts.get(x);
biggerNumberPlace = x;
}
}
lastBiggerNumber = biggerNumber;
biggerNumber = -1;
biggerNumberLocationList.add(biggerNumberPlace);
}
ArrayList<String> mostCalledPhoneNumbers = new ArrayList();
int place_in_array;
String phoneNumber;
for (int f=0; f<biggerNumberLocationList.size() ; f++) {
place_in_array = biggerNumberLocationList.get(f);
phoneNumber = number.get(place_in_array);
mostCalledPhoneNumbers.add(phoneNumber);
// Log.i("go", "place in array " + biggerNumberLocationList.get(f) + ", the phone number " + number.get(biggerNumberLocationList.get(f)) + " called " + counts.get(biggerNumberLocationList.get(f)) + " times ");
}
return mostCalledPhoneNumbers;
}
It would be easier to use HashMap for this job or even ArrayList<> of type object that stores string and int.
after studying a lot i made this custom code .which worked perfect.i guess its lengthy.but still.again thanks to #Tejas Pandya and #guy.
//putting above data into hashmap
HashMap<String,Integer> hm = new HashMap<String,Integer>();
for(int i = 0; i < counts.size(); i++) {
hm.put(numbers.get(i),counts.get(i));
}
//create list from elements of hashmaps
List<Map.Entry<String,Integer>> list = new LinkedList<Map.Entry<String, Integer>>(hm.entrySet());
//sort the list
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
#Override
public int compare(Map.Entry<String, Integer> stringIntegerEntry,
Map.Entry<String, Integer> t1) {
return (t1.getValue()).compareTo(stringIntegerEntry.getValue());
}
});
HashMap<String,Integer> temp = new LinkedHashMap<String,Integer>();
for(Map.Entry<String,Integer> aa : list){
temp.put(aa.getKey() , aa.getValue());
Log.e("descending",aa.getValue()+"");
Log.e("descending",aa.getKey()+"");
}
String temp2 = String.valueOf((list.subList(0, 10)));
Log.e("final",temp2+"");
i have a graph view to implement an analysis graph
All the x-axis and y-axis data is get from the sqlite db data to show the output
x-axis is showing date
y-axis is showing weight
but I have no idea to implement them out, I am stuck,
below is my code but its wrong and I haven't completed yet, can someone help me to solve and build
DBHelperNote connect = new DBHelperNote(getActivity());
SQLiteDatabase db = connect.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM weight;",null);
String[] weight = new String[cursor.getCount()];
int i = 0;
while(cursor.moveToNext()){
d = cursor.getString(cursor.getColumnIndex("weightnum"));
weight[i] = d;
i++;
}
String[] date = new String[cursor.getCount()];
int r = 0;
while(cursor.moveToNext()){
e = cursor.getString(cursor.getColumnIndex("date"));
date[r] = e;
r++;
}
GraphView line_graph = (GraphView) contentView.findViewById(R.id.graph);
LineGraphSeries<DataPoint> line_series =
new LineGraphSeries<DataPoint>(new DataPoint[] {
>> here "while" getting error
while ( a!=weight.length) {
new DataPoint(Integer.parseInt(weight[i]), Integer.parseInt(date[i]));
i++;
}
}
);
line_graph.addSeries(line_series);
line_series.setDrawDataPoints(true);
line_series.setDataPointsRadius(10);
line_series.setOnDataPointTapListener(new OnDataPointTapListener() {
#Override
public void onTap(Series series, DataPointInterface dataPoint) {
Toast.makeText(getActivity(), "Series: On Data Point clicked: " + dataPoint, Toast.LENGTH_SHORT).show();
}
});
Hmn, it might be an error with the data type in their example they use a double instead of an int.
http://www.android-graphview.org/documentation/category/live-chart
private DataPoint[] generateData() {
int count = 30;
DataPoint[] values = new DataPoint[count];
for (int i=0; i<count; i++) {
double x = i;
double f = mRand.nextDouble()*0.15+0.3;
double y = Math.sin(i*f+2) + mRand.nextDouble()*0.3;
DataPoint v = new DataPoint(x, y);
values[i] = v;
}
return values;
I have a list that is populated with data taken from database.
The data of the list are passed to the view to display them. For each id taken from the database, I want to add a day to the calendar, then, I added the id what I need in an array, in order to have them sorted.
The problem is the loop in the list, instead of iterating based on the number of id in the array, the cycle continues without stopping ... I hope I explained, this is all the code
private Integer[] id_nome_op;
public void checkOperatori() {
SQLiteDatabase db = new DatabaseHelper(getActivity()).getReadableDatabase();
String OPERATORI = "SELECT _id, ...... ORDER BY _id ASC";
Cursor cur = db.rawQuery(OPERATORI, null);
int count = cur.getCount();
id_nome_op = new Integer[count];
nome_op = new String[count];
cognome_op = new String[count];
for (int i = 0; i < count; i++) {
cur.moveToNext();
id_nome_op[i] = cur.getInt(0);
nome_op[i] = cur.getString(1);
cognome_op[i] = cur.getString(2);
mWeekView.setData(nome_op, cognome_op);
}
cur.close();
db.close();
}
#Override
public List<WeekViewEvent>onMonthChange(int newYear, int newMonth) {
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
final String strDate = simpleFormat.format(calendarioFooter.getTime());
List<WeekViewEvent> events = new ArrayList<WeekViewEvent>();
SQLiteDatabase db = new DatabaseHelper(getActivity()).getReadableDatabase();
String tabella_op = "SELECT m._id, m.id_operatore, ...........";
Cursor cur = db.rawQuery(tabella_op, null);
while (cur.moveToNext()) {
startTime = (Calendar) calendarioFooter.clone();
id_appuntamento = cur.getString(0);
id_operator = cur.getInt(1);
dat = cur.getString(2);
ora_iniz = cur.getString(3);
ora_fin = cur.getString(4);
id_servizio = cur.getString(5);
id_client = cur.getString(6);
nome_cliente = cur.getString(7);
cognome_cliente = cur.getString(8);
nome_operatore = cur.getString(9);
colore_serv = cur.getInt(10);
tipo_serv = cur.getString(11);
int giorno_ok = Integer.parseInt(dat.substring(8, 10));
int ora_inizio = Integer.parseInt(ora_iniz.substring(0, 2));
int minuto_inizio = Integer.parseInt(ora_iniz.substring(3, 5));
int ora_fine = Integer.parseInt(ora_fin.substring(0, 2));
int minuto_fine = Integer.parseInt(ora_fin.substring(3, 5));
int size = id_nome_op.length;//array id
for(int i = 1; i< size; i++){
if (i == 1) {
startTime.set(Calendar.DAY_OF_MONTH, giorno_ok);
} else if (i == 2) {
startTime.set(Calendar.DAY_OF_MONTH, giorno_ok);
startTime.add(Calendar.DATE, 1);
} else if (i == 3) {
startTime.set(Calendar.DAY_OF_MONTH, giorno_ok);
startTime.add(Calendar.DATE, 2);
}
startTime.set(Calendar.HOUR_OF_DAY, ora_inizio);
startTime.set(Calendar.MINUTE, minuto_inizio);
startTime.set(Calendar.MONTH, newMonth - 1);
startTime.set(Calendar.YEAR, newYear);
Calendar endTime = (Calendar) startTime.clone();
endTime.set(Calendar.HOUR_OF_DAY, ora_fine);
endTime.set(Calendar.MINUTE, minuto_fine);
WeekViewEvent event = new WeekViewEvent(id_appuntamento, getEventTitle(startTime), startTime, endTime);
event.setColor(colore_serv);
events.add(event);
}
}
cur.close();
db.close();
return events;
}
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.