Here is my problem: I am using AFreeChart to display a chart in my activity. The reason why I used AFreeChart was because I first finished this chart with JFreeChart, and, realized after that, it wasn't compatible with Android.
So, with AFreeChart, I could create the same chart with exactly the same code, but I don't know how to display it on a View.
Here I am creating the chart:
private void creerGraphique(){
//Here I have the creation of the DateSet
AFreeChart chart = ChartFactory.createXYLineChart(
"Mois", // Title
"Jours", // x-axis Label
"Repetitions", // y-axis Label
graph, // Dataset
PlotOrientation.VERTICAL, // Plot Orientation
true, // Show Legend
true, // Use tooltips
false // Configure chart to generate URLs?
);
}
Here I want to use it:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graphique);
this.stockTableau();
this.creerGraphique();
//HERE: How can I display it since it's already created
}
I downloaded the AFreeChart demo code, but a function which wasn't on the package was used, and so, I couldn't use it too.
I thank you for your help.
PS: I'm not an english, so I hope my problem is clear, do not hesitate to ask me more details.
Have you looked at the sample in AFreeChart? It's quite straight forward, look at what they did for this chart for instance :
http://code.google.com/p/afreechart/source/browse/trunk/afreechart_sample/src/org/afree/chart/demo/view/PieChartDemo01View.java
They extend a DemoView which is basically an Android View with a setChart method, and pass the chart to the View.
So either extend DemoView or create you own equivalent if you don't need everything that's in it and follow the sample !
Good luck.
It is also worth noting that using the code you've pasted above, it would be helpful to call the chart's draw() method when you want it to draw.
As a simple example, if you were using a SurfaceView, you could create a method something like the following:
private void drawChart(AFreeChart chart, ChartRenderingInfo info) {
getHolder.lockCanvas();
chart.draw(canvas, area, info);
getHolder().unlockCanvasAndPost(canvas);
}
Where 'canvas' and 'area' have been set.
This is useful if you are looking to do a very simple implementation where you don't want to use the DemoView discussed above.
Related
How could we achieve Synchronized charts in Android.
For my web page I've used Highcharts API. Is there any similar thing for Android. I've checked various libraries mentioned here but didn't find any which will match the requirement.
I don't want combined charts like this and this. I'm looking for Synchronized charts.
Is there any library which will meet the requirement or Should I go with webView (It's a worst case for me)
Is it possible with MPAndroidChart?
EDIT:
Resultant chart should be like the Charts given in highcharts page
Sample:
UPDATE
Motto is not just to draw the 3 charts. The Aim is to synchronize them. Synchronise means all the 3 charts have same x-axis(values), on click at any point in these charts the plot at that particular point should be highlighted in all the charts. I'm sure I didn't explain it properly. Kindly check this link and hover the graph
when clicked on chart 1 get the X and Y points and highlight them on chart 2. Same with 2nd chart.
lineChart1.setOnChartValueSelectedListener(new OnChartValueSelectedListener()
{
#Override
public void onValueSelected(Entry e, Highlight h)
{
lineChart2.highlightValue(e.getX(),e.getY(),0,false);
}
#Override
public void onNothingSelected()
{
}
});
lineChart2.setOnChartValueSelectedListener(new OnChartValueSelectedListener()
{
#Override
public void onValueSelected(Entry e, Highlight h)
{
lineChart1.highlightValue(e.getX(),e.getY(),0,false);
}
#Override
public void onNothingSelected() {
}
});
NOTE set the last argument to false so that it doesn't call the listener again and again. If this is not set then it results to deadlock.
The sample app has a good display of the features available to you "out of the box" with MPAndroidChart.
As you can see, there is an example of multiple charts inside a ListView which seems to be close to your requirement.
Likewise, the source code is available on GitHub for you to inspect and see if it has the available classes and methods for you to do what you want out of the box.
At the same time, you should understand that it is often unrealistic to expect to find a library that will exactly suit an unusual requirement from mere configuration alone. Free and open source libraries often provision for extension and customisation and MPAndroidChart is no exception. As a professional software engineer, or as an aspiring one, you should be willing and prepared to program that yourself.
In your particular case, it seems you want some kind of co-ordination between the charts. So if you click on one of them then the MarkerView appears on all at the same xIndex in the DataSet.
To attempt this, you would start by looking at the code for OnChartGestureListener. A solution can be obtained through using event-driven programming. You would set up 3 implementations of OnChartGestureListener which would use events to transmit the current gesture to a mediator who then triggers the same gestures on the other two charts. For example, inside OnChartGestureListener there is a method to implement called:
void onChartScale(MotionEvent var1, float var2, float var3);
Your implementation would look something like this:
#Override
void onChartScale(MotionEvent var1, float var2, float var3) {
//transmit event to mediator
//handle event for this chart
}
If this is too difficult then you will have to stick with Highcharts inside a WebView as you have cogently suggested yourself. However, be aware that the performance inside the WebView will not be as good as using a library that renders to canvas directly.
In short, it is possible, although difficult, to accomplish what you want using MPAndroidChart and no "out-of-the-box" solution is available.
You can surely make it using MPAndroidCharts library.
Go for 1> LineChart (with legend, simple design) for Speed
2> LineChart (cubic lines) / (gradient fill) for Elevation , Heart
While Using gradientFill apply this to eliminate dashed line and draw a straight line:
lineDataSet.enableDashedLine(0f, 0f, 0f);
lineDataSet.enableDashedHighlightLine(0f, 0f, 0f);
I've been searching for an answer for this but since i couldn't find any, i'll post the question.
I have a plot drawn, with a list below showing some data, one of the parameters of each row is drawn in the plot.
I'm trying to change the color of the point when the user clicks in one of the views of the list, to reflect in the plot that the row matches the point, but i haven't been able to replicate it.
There is any way to get an specific point of the graph, to change its color?
Thanks in advance.
I don't know if what you are trying to do is possible but you can try to add a serie to your plot containing the point that you want to highlight when user clicks. When a new click is done you just need to remove the added serie and add a new one containing the new point.
The added serie must have a different style so you can see the "changed color" and must be the last added serie so it will be in forground.
Hope it helps
Edit
What you can do to adapt it to your use case is to extend a XYPlot class, create a SeriesType highlightedPoint property and add a method like (not tested) :
public void highlightPoint(Number x, Number y, FormatterType formatter){
// if there is already a highlighted point we remove it (we want to highlight just one point)
if(highlightedPoint != null) {
removeSeries(highlightedPoint);
highlightedPoint = null;
}
// we need to highlight the new point, which means adding a serie on top of the others
highlightedPoint = new SimpleXYSeries("Highlighted Point");
highlightedPoint.addFirst(x,y);
addSeries(highlightedPoint, formatter);
}
You just need to call this method on your plot instance each time user clicks on your list.
is there any example, howto place any of charts in MPAndroidChart library to homescreen widget?
//i tried to use getChartbitmap(), but
1)bitmap is not created immediately after calling invalidate(), so it return null
2)i dont see way, howto initialize chart class without placing resources - which i cant do
for widget.
anybody have some successful example ?
The chart needs some milliseconds to draw the content onto the Bitmap. That is the reason why calling getChartBitmap() right after invalidate() will not return a valid Bitmap.
Try using a Handler and delay the time before retrieving the Bitmap by abound 100ms.
Try this code
BarData chartData =...
BarChart chart = new BarChart(mContext);
chart.setData(chartData);
chart.measure(View.MeasureSpec.makeMeasureSpec(300,View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(500,View.MeasureSpec.EXACTLY));
chart.layout(0, 0, chart.getMeasuredWidth(), chart.getMeasuredHeight());
Bitmap chartBitmap = chart.getChartBitmap();
In Activity with chart, function getChartBitmap() working fine! It's return bitmap without any errors. IMHO that's the problem, in widget we don't have an activity, placing created chart in layout is not take effect :( So, we can't have a widget with this chart at all, and it's very sad - this chart so really cool.
I am trying to add some visual indication, that there are no more pages in the desired fling direction in the ViewPager. However I am struggling to find a place, where to put relevant code.
I have tried extending ViewPager class with following code, but the Toast is not displaying (ev.getOrientation() returns always 0). I have also tried the same with history points, but ev.getHistorySize() returns also 0.
What am I missing?
Class example:
public class CustomViewPager extends ViewPager {
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* #see android.support.v4.view.ViewPager#onTouchEvent(android.view.MotionEvent)
*/
#Override
public boolean onTouchEvent(MotionEvent ev) {
boolean result = super.onTouchEvent(ev);
switch (ev.getAction() & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_MOVE:
if (ev.getOrientation() > 0) {
Toast.makeText(getContext(), "left", 0).show();
}
}
return result;
}
}
If you look at the v4 support library you will see there's a class used by ViewPager called EdgeEffectCompat (this provides the glow effect when you reach the beginning or end of a view pager in ICS+) If you look at the implementation in the compat library you will see that it has an if-statement to see if the build version is 14+ (ICS) or not. If it is, then it ends up eventually (if you trace long enough) using the normal EdgeEffect class that was inroduced in ICS. Otherwise it uses BaseEdgeEffectImpl which basically has nothing in it.
If you want, you can make your own custom ViewPager that uses EdgeEffect of your own. You can look at the android source code to see how they implemented EdgeEffect here which you can pretty much copy (just make sure to copy the overscroll_edge and overscroll_glow drawables in the AOSP /res/drawable directories to your own project since they are internal to android) or go ahead and create your own version.
Good luck.
(By the way, that's how they create the cool looking edge tilt effect in the launcher menu on ICS... so you can pretty much be as creative as you want with this ;)
I was trying to get the exact same effect that was asked in this question. I struggle with it and then I read #wnafee answer (I couldn't do it with out it).
But then I struggle to implement what was sound pretty simple from the answer.
I had so much trouble with implementing it, that I might didn't understand the answer correctly, but there were too many issues of inaccessible APIs since I wasn't working in the same package of the Compatibility library.
After I tried some approaches (none of them succeeded, and they were pretty complicated) I went to a slightly different direction, and now it works like a charm. I used some reflection, for the ones who never used it, don't worry it is really the basic of reflection.
I'm not sure if it's the best solution out there, but it worked for me, so if you would like to use it you are welcome. Please read Wnafee example since it explains some of the stuff that I did.
In order to accomplish this task you should just follow my three parts solution. (Will take you between 3-10 minutes)
Part I:
As Wnafee said I just made my own EdgeEffect class by copy paste the source code from here,
(just make sure to copy the overscroll_edge and overscroll_glow
drawables in the AOSP /res/drawable directories to your own project
since they are internal to android)
I only did 2 really small changes:
I declare that the class extends EdgeEffectCompat (I called my class EdgeEffectForEarlyVersions). public class EdgeEffectForEarlyVersions extends EdgeEffectCompat. The reason for doing this change is that the mLeftEdge and mRightEdge are of the type EdgeEffectCompat.
At the first line of the constructor of "my" new class I added a call to the parent constructor super(context);. Since there is no default constructor to EdgeEffectCompat you have to Explicitly call the constructor.
Part II
Besides that I wrote the another function. The purpose of the function is that in case of an early version (before ICS) we would like to use the EdgeEffectForEarlyVersions that we just copied. In order to get that purpose I used reflection.
This is the function:
private static void changeEdgeEffectCompactOnEarlyVersions(ViewPager viewPager, Context context)
{
/* In case that the version is earlier than 14 there is only empty implementation for the edge effect, therefore we change it.
* for more information look on the following links:
* 1. http://stackoverflow.com/questions/10773565/visual-indication-of-over-scroll-in-android
* 2. http://grepcode.com/file/repo1.maven.org/maven2/com.google.android/support-v4/r7/android/support/v4/view/ViewPager.java#ViewPager.0mLeftEdge
* 3. http://grepcode.com/file/repo1.maven.org/maven2/com.google.android/support-v4/r7/android/support/v4/widget/EdgeEffectCompat.java#EdgeEffectCompat
*/
if (Build.VERSION.SDK_INT < 14)
{
try
{
Class<ViewPager> viewPagerClass = ViewPager.class;
//Get the left edge field, since it is private we used getDeclaredField and not getDeclared
Field leftEdge = viewPagerClass.getDeclaredField("mLeftEdge");
leftEdge.setAccessible(true);
//Get the right edge field, since it is private we used getDeclaredField and not getDeclared
Field rightEdge = viewPagerClass.getDeclaredField("mRightEdge");
rightEdge.setAccessible(true);
EdgeEffectForEarlyVersions leftEdgeEffect = new EdgeEffectForEarlyVersions(context);
EdgeEffectForEarlyVersions rightEdgeEffect = new EdgeEffectForEarlyVersions(context);
//Set the mLeftEdge memeber of viewPager not to be the default one, but to be "our" edgeEffect
leftEdge.set(viewPager, leftEdgeEffect);
//Set the mRightEdge memeber of viewPager not to be the default one, but to be "our" edgeEffect
rightEdge.set(viewPager, rightEdgeEffect);
}
catch (Exception ex)
{
Log.e("refelection", ex.getMessage());
}
}
}
Part III
Now all there is left to do, is to call that function after you have the ViewPager Instance and nothing more.
I Hope it will help someone.
wnafee explained the solution well but for the lazy among us, i made an actual working implementation quite some time ago.
https://github.com/inovex/ViewPager3D
And if you just want overscroll take a look here:
https://github.com/inovex/ViewPager3D/issues/1
You have a lot of options, you can show a Toast, display a Dialog, make a TextView or image to appear over your UI, etc. Or because you know the amount of View items in the ViewPager, you could add different View at positions 0 and/or n + 1 with the message and make it bounce to the last View that actually contains your data.
You could implement:
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
public void onPageSelected(int position) {
//TODO If position is the 0 or n item, add a view at 0 or at n+1 to indicate there is no more pages with data.
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// TODO Show a Toast, View or do anything you want when position = your first/last item;
}
public void onPageScrollStateChanged(int state) {
}
});
just to complement #goBeepit dev answer when you create your own edgeffect class and you extend from EdgeEffectCompat some methods requires to be boolean. you can change those methods to boolean type and make then return true in any case, this way everything works fine
You can overload the setUserVisibleHint(boolean) function in your fragments. Pseudo code:
void setUserVisibleHint(boolean isVisibleToUser) {
// If this fragment is becoming visible
if (isVisibleToUser == true) {
// Check if it is the last fragment in the viewpager
if (indexOfThis == getActivity().indexOfLast) {
// Display right limit reached
Toast(..., "No more Frags to right",...)
}
// Check if it is the first fragment in the viewpager
else if (indexOfThis == getActivity().indexOfFirst) {
// Display Left Limit reached
Toast(..., "No more Frags to left",...)
}
}
}
I have not used this function for this purpose, but have used it for other reasons and it does fire appropriately. Hope this helps...
I've implemented a bounce back effect based on Renard's ViewPager3D: https://stackoverflow.com/a/17425468/973379
Usually with ViewPager, one uses a PagerAdapter such as FragmentPagerAdapter or FragmentStatePagerAdapter to flood the ViewPager with contents(your content are going to be views).
Now, when you use a PagerAdapter, you have one method called getCount(), http://developer.android.com/reference/android/support/v4/view/PagerAdapter.html#getCount%28%29 ,which will give you the size of the content.
Since you now, know the size you can easily display a message with an if control statement.
Try this code : http://developer.android.com/reference/android/support/v4/view/ViewPager.html
Note: I dont think you need a custom ViewPager. You will also need to understand Fragments for ViewPager. Look at samples in ApiDemos. Its a great source.
I want to input data i.e. name and age of user on a scene of AndEngine. How can I do that ??
I dont want to use a dialog for this purpose.
You asked this on the AndEngine forums and RealMayo gave you the best answer there.
Study the TextBreakExample.java - and more specifically, study the AndEngineExamples/res/layout/textbreakexample.xml file
You will see how to "blend" a standard Android EditText (not a dialog) into your game.
If all you want to do is a text entry overlay, you can add it in your onSetContentView() method:
#Override
protected void onSetContentView() {
editTextExample = new EditText(this);
this.addContentView(editTextExample, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));
}
Otherwise, if you want to make editable text whose look can be set by AndEngine, check out the example Java code and XML code