Android Graphview changing x axis data - android

in my app I'm using GraphView library to create a LineGraphView. It shows data from specified dates from example from 18.01 to 30.01. When I change the boundaries for example from 25.01 to 29.01 GraphView updates the chart (cuts not needed lines) but still shows wrong x axis data (18.01 to 30.01), however when user starts to interact with chart (zooming, scrolling) it updates it's x axis and everything is fine. Is there a method to force GraphView to update it's x axis? I have only encountered this problem if user has been interacting with chart (zooming, scrolling) before changing dates if there was no interaction graphview updates properly. I'm creating charts this way:
Inside onCreate:
mGraphView = new LineGraphView(this, "Temperature Measurements");
And a function to create a chart when I fetch data from database:
public void createChart(Cursor cursor) {
GraphViewData[] values = new GraphViewData[cursor.getCount()];
while (cursor.moveToNext()) {
String time = cursor.getString(cursor
.getColumnIndex(MeasurementEntry.DATE_IN_MINUTES));
String temp = cursor.getString(cursor
.getColumnIndex(MeasurementEntry.TEMPERATURE));
values[cursor.getPosition()] = new GraphViewData(
Double.parseDouble(time), Double.parseDouble(temp));
}
mGraphView.removeAllSeries();
mGraphView.addSeries(new GraphViewSeries(values));
mGraphView.setScalable(true);
mGraphView.getGraphViewStyle().setTextSize(15);
final SimpleDateFormat formatter = new SimpleDateFormat(
"dd.MM.yyyy HH:mm");
mGraphView.setCustomLabelFormatter(new CustomLabelFormatter() {
#Override
public String formatLabel(double value, boolean isValueX) {
if (isValueX) {
return formatter.format(new Date((long) value));
}
return null;
}
});
}
And here is the screenshot with the problem:

OK, so I made it however I think it can be done better, what I done is removing graphView from parent layout, creating new graphview and adding new graphview - I do this sequence everytime user is changing the boundaries. Maybe it will help somebody (short snippet of createChart method, container is my parent layout):
container.removeView(mGraphView);
mGraphView = new LineGraphView(this, "Temperature Measurements");
container.addView(mGraphView);
mGraphView.removeAllSeries();
mGraphView.addSeries(new GraphViewSeries(values));
mGraphView.setScalable(true);
mGraphView.getGraphViewStyle().setTextSize(15);

Related

Charts - using Mp Chart

I need to draw graph like the image i have uploaded , i am using MP chart library and develop a graph but want to customize it according to my requirement but not able to find solution for my requirements my basic requirement is for x axis i want to show custom values at axis like 5-11 12-18 but i am passing value to x axis like this
private ArrayList<String> setXAxisValues() {
ArrayList<String> xVals = new ArrayList<String>();
xVals.add("10");
xVals.add("20");
xVals.add("30");
xVals.add("30.5");
xVals.add("40");
return xVals;
}
So it is showing x values like this 10 20 30 so on so i want my graph to be built upon using these x value which is happening right now but want to show custom value at bottom like 5-11 etc and this value is dynamic coming from Api response so please help me about this , Waiting for positive and early response Thanks in Advance
To format the x-axis values, you should use the setValueFormatter method which takes a callback interface were you have to implement the getFormattedValue method which is called before drawing the x-axis value.
xAxis.setValueFormatter((value, axis) -> {
String res = "";
try {
// get current position of x-axis
int currentPosition = (int) value;
// check if position between array bounds
if (currentPosition > -1 && currentPosition < maxSize) {
// get value from formatted values array
res = xVals.get(currentPosition);
}
} catch (Exception e) {
// handle exception
}
return res;
});

Passing current time in milliseconds to MPChart breaks it

I have tried figuring this out, but it doesn't add up. The data doesn't appear as it should.
First I generate dummy data. This is done async because I need time between the calls to System.currentTimeMillis to get some spacing between them. (Look aside the crappy code here, this is just debug data that will not be in the release. Using Thread.sleep on the main thread is a bad idea considering ANR's)
public class AsyncGeneration extends AsyncTask<String, String, String>{
public AsyncGeneration() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
#Override
protected void onCancelled(String s) {
super.onCancelled(s);
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected String doInBackground(String... strings) {
while(root == null) {
try {
Thread.sleep(200);
}catch(InterruptedException e){}
}
List<Entry> rdata = new ArrayList<>();
for(int i = 1; i < 30; i++){
try{
Thread.sleep(200);
}catch(Exception e){
//IGNORE
}
float time = System.currentTimeMillis();
Log.e("GChart", "Timex: " + time);
Session s = new Session(r.nextInt(5000), time);//Replace time with the index in the for-loop and it works for some reason
rdata.add(new Entry(s.getXValue(), s.getYValue()));
Log.e("GChart", "Timey: " + s.getXValue());
}
final List<Entry> entries = rdata;
OverviewFragment.this.getActivity().runOnUiThread(() ->{
LineDataSet data = new LineDataSet(entries, "Distance");
data.setCircleColor(Color.parseColor("#FF0000"));
LineData lineData = new LineData(data);
tab1chart.setData(lineData);
tab1chart.invalidate(); // refresh
tab1chart.getXAxis().setValueFormatter(new DateFormatter());
tab1chart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
tab1chart.getXAxis().setTextSize(10f);
tab1chart.getXAxis().setTextColor(Color.RED);
tab1chart.getXAxis().setDrawAxisLine(true);
tab1chart.getXAxis().setDrawGridLines(true);
tab1chart.getAxisLeft().setValueFormatter(new DistanceValueFormatter());
tab1chart.getAxisLeft().setDrawGridLines(true);
Log.v("Chart", "Chart data loaded and invalidated");//This prints
});
return null;
}
}
So far everything looks fine. The data gets put into the chart, no exceptions, no crashes.
When the chart renders, a single data point shows up at the far-left of the chart. I generate 30 data points, one shows up.
That's issue #1: Only one data point shows up.
Issue #2 is slightly harder. The entire X axis at the bottom disappears. X axis is gone and when zooming, the Y axis, and its text also disappears. This is fairly hard to explain, so here is a screenshot:
It is worth mentioning the fact that if I pass i in the for-loop as the time, it shows up just as expected: all the axises are in place, zoom doesn't break anything.
(Float values can take the same values as Longs except they have decimals in addition.)
And in addition, I format the data:
public class DateFormatter implements IAxisValueFormatter {
SimpleDateFormat formatter;
public DateFormatter(){
formatter = new SimpleDateFormat("dd/MM/yy, HH:mm");
}
#Override
public String getFormattedValue(float value, AxisBase axis) {
//This method is never called. Nothing is returned
if(axis instanceof XAxis) {
String formatted = formatter.format(new Date((long) value));
Log.d("Formatter", "Formatted \"" + value + "\" to \"" + formatted + "\".");
return formatted;
}
return "Not supported";
}
}
Removing the formatter doesn't change anything, the axis is still gone. Zoom still breaks the Y axis.
So my question is: How do I fix this? I don't get why the chart doesn't work when I pass the current time in milliseconds (and I checked the values with debug output, floats can handle it). I got some debug output earlier that eventually stopped coming at all that showed the value passed to the formatter was values < 2000. I can't reproduce this any more though
The chart itself doesn't appear to be broken but from touch events it looks like every single point is pushed into the same X coordinate but only one point renders. When I touch the chart, the orange-ish lines show up indicating the position of a data point. It pops up on points that aren't visible.
When I pass the for-loop index as the X value, it works as expected, the formatter works fine (looking aside the fact that it shows the date as in 1970, but it is counted as 1 millisecond into the epoch, so that is to expect)
I looked at this as well on formatting the date. When I then try passing the milliseconds since the epoch, the chart stops working.
I'm using MPChart v 3.0.2, compiling against Android 26, using Java 8, and running Android Studio 3.0 beta 2
As for the layout, it is just a LinearLayout with a LineChart in it.
This should work, but it breaks when I pass it the current time in milliseconds for some reason. Passing any other data (as long as the numbers aren't that big) works fine.
The two images are not how the chart is supposed to look. The X axis is supposed to be visible, but for some reason it isn't along with a large amount of the data.
This is known issue of Android MPChart (have a read this thread). Time series chart supported in MPChart - You can set time (in millis) as X values for Hourly Charts.
But too many consecutive data (points) won't correctly plot in Line Charts. Because Entry object will accept only float values due to some performance constraints.
So, keep the first value as the reference and subtract each up coming value from reference value & divide by some constants (say 1000) .So , you X value set will be like 10,20,30....& so on.
Do the reverse logic in your Axis Value formatter to render the X Axis Label properly (see the code snippet).
lineChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
#Override
public String getFormattedValue(float value, AxisBase axis) {
SimpleDateFormat format2 = new SimpleDateFormat("HH:mm:ss");
return format2.format(new Date(firstTimeStamp + ((long) value) * 1000L));
}
});

How to handle time series in MPAndroidChart?

I want to add the following sort of data (can be any number of such pairs under 1000) to the newly introduced timeseries chart in MPAndroidChart library
Value : 50.0 at 1472112259
Value : 49.0 at 1472112294
Value : 50.0 at 1472112329
Value : 50.0 at 1472112360
Value : 50.0 at 1472112392
The following data will be fetched from the array.
Right now, I guess there is some mess up with the timestamps.
Here is the complete code: https://gist.github.com/utkarshns/e1723dcc57022fcd392bc3b127b6c898
UNIX timestamps will be parsed to required time format after I can successfully add values to the graph.
Currently, the problem I face is that the timestamps probably get clipped and values are overwritten which leads to a pretty messed up graph with really weird x-axis values.
Update:
Screenshots:
http://imgur.com/a/dGfmz
The problem is that Float values can't hold very big numbers and still be accurate, so you need a separate List with these timestamp values. BigDecimal should be ok for this purpose. Your distances must be in accordance to the time gaps between your events. Just iterate from the start date to end date keeping count of how many timestamps you have and add Entry with count from the timestamps you wish your value to be.
Long myValues[] = {1472112259L, 1472112294L, 1472112329L, 1472112360L, 1472112392L};// your values
ArrayList<Entry> values = new ArrayList<>();// Entry List
Long start = 1472112259L;//start
Long end = 1472112392L;//end
List<BigDecimal> mList = new ArrayList<>(); //Decimal list which holds timestamps
int count = 0;
for (Long i = start; i <= end; i++) {
mList.add(new BigDecimal(i));
if (myValues.equals(i)) {
values.add(new Entry(count, 50));
}
count++;//always increment
}
And your ValueFormatter should look like this:
AxisValueFormatter() {
private FormattedStringCache.Generic<Long, Date> mFormattedStringCache = new FormattedStringCache.Generic<>(new SimpleDateFormat("HH:mm:ss"));
#Override
public String getFormattedValue ( float value, AxisBase axis){
return mFormattedStringCache.getFormattedValue(new Date(mList.get((int)value).longValueExact()*1000), value);
}
#Override
public int getDecimalDigits () {
return 0;
}
}
If you have any question or something is unclear I'll be happy to help.

Android Drawable setLevel(); not filling SeekBar appropriately

Okay so I've been able to customize a few SeekBar's to be used as a Bar Graph type of image, but since I need to be able to switch between a Green or Red Image (depending on certain values) which you can see below. The problem is that regardless of what value I use in the setLevel for the Drawable it doesn't fill appropriately (you can see the image below for an example since the green bar should be closer to the right based on the two values)
Below is the code for the section that setups this entire MTD Commission bar section, I don't know how much of the code you would need to see so I just decided to post all of this section.
void setupMTDBarSection() {
//Get Current Date and Number of Days in Current Month
Calendar cal = Calendar.getInstance();
int numberOfDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
SimpleDateFormat today = new SimpleDateFormat("dd");
String currentDate = today.format(new Date());
//Get MTD Goal value from Preferences
String goalString = preferences.getString("keyMonthlyGoal", "0");
float mtdGoalFloat = Float.valueOf(goalString);
Integer mtdGoal = (int)mtdGoalFloat;
MTDGoalValue.setText(NumberFormat.getCurrencyInstance().format(mtdGoalFloat));
//Get Current MTD Value
String mtdString = preferences.getString("keyMTDValue", "0");
float mtdValueFloat = Float.valueOf(mtdString);
Integer mtdValue = (int)mtdValueFloat;
MTDCurrentProgress.setText(NumberFormat.getCurrencyInstance().format(mtdValueFloat));
//Do some math to determine if the Rep is below/above the daily goal
Integer dailyGoal = mtdGoal/numberOfDays;
Integer currentDayGoal = dailyGoal * Integer.valueOf(currentDate);
if (mtdValue >= currentDayGoal) {
MTDGreenTrack.setLevel(mtdValue);
MTDProgressBar.setProgressDrawable(MTDGreenTrack);
MTDProgressBar.setMax(mtdGoal);
MTDProgressBar.setProgress(mtdValue);
}
else {
MTDRedTrack.setLevel(mtdValue);
MTDProgressBar.setProgressDrawable(MTDRedTrack);
MTDProgressBar.setMax(mtdGoal);
MTDProgressBar.setProgress(mtdValue);
}
//Add Percentage to MTD Text
NumberFormat percentFormat = NumberFormat.getPercentInstance();
float percent = mtdValueFloat/mtdGoalFloat;
String percentage = percentFormat.format(percent);
MTDPercentText.setText("(" + percentage + ")");
//Setup MTD Indicator
MTDIndicator.setMax(numberOfDays);
MTDIndicator.setProgress(Integer.valueOf(currentDate));
MTDIndicator.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return true;
}
});
}
I believe I found the issue. Apparently when you call setProgressDrawable more than once then you need to re-draw the image that is used since it looses the format that was previously there. Also, don't really need to set the level each time of the drawable as well, it matches up with the progress value of the Seekbar. Below is the code that works for me so far
Rect bounds = MTDProgressBar.getProgressDrawable().getBounds();
MTDProgressBar.setProgressDrawable(MTDGreenTrack);
MTDProgressBar.getProgressDrawable().setBounds(bounds);
MTDProgressBar.setProgress(mtdValue);
MTDProgressBar.setMax(mtdGoal);

How to Change the X-axis using Graph View Demo in android

Basically i want to draw a graph where x-axis gives you the date and y axis gives u the count
I am getting data from server and parsing it in my two array's one is for count and other is for date
i am getting values in two array like this
SoapObject o=(SoapObject)p2.getProperty(xx);
UserCallStatusBean ld=new UserCallStatusBean();
if(o.getProperty("Month").toString().equals("anyType{}")){
ld.setDuration("");
}
else{
ld.setDuration(o.getProperty("Month").toString());
}
ld.setCount(Integer.parseInt(o.getProperty("Count").toString()));
CallStatus.add(ld);
GraphViewData o1=new GraphViewData(_iLoopCounter,Double.parseDouble(o.getProperty("Count").toString()));
String o2=new String(o.getProperty("Month").toString());
//String o2=new String(String.valueOf(_iLoopCounter));
arrData[xx]=o1;
arrXaxis[xx]=o2;
_iLoopCounter++;
After Getting the Value in two array i use Graph View Demo to create a grapg like
setContentView(R.layout.graphs);
// init example series data
exampleSeries = new GraphViewSeries(arrData);
// graph with dynamically genereated horizontal and vertical labels
GraphView graphView;
graphView = new BarGraphView(
this,"");
graphView.addSeries(exampleSeries); // data
graphView.setScalable(true);
graphView.setScrollable(true);
graphView.setViewPort(2,6);
graphView.setScrollable(true);
graphView.setHorizontalLabels(arrXaxis);
graphView.setGravity(Gravity.CENTER);
graphView.setBaselineAlignedChildIndex(4);
//graphView.setHorizontalLabels(labels);
LinearLayout layout = (LinearLayout) findViewById(R.id.graph1);
layout.addView(graphView);
Now My issue of concern is i am getting value of count on y-axis but i am also getting count of date on x-axis instead i want to show the date on x-axis
I Have read various articles to get string value on x-axis ,finded one to use Cutom lavel formatter , But didnt knw how to use so what i can do to get x-axis ? (Date Value)
I hope u understands ,Expecting Answer Pleasue will b aLl Mine
Thanks in advance

Categories

Resources