I use AchartEngine to create a LineGraph.
I have the data from the database in the format:
dd-mm-yyyy count
for example:
01-05-2013 3
01-08-2013 7
01-11-2013 4
01-12-2013 15
...
code fragment
...
int values = new Date[myCursor.getCount()];
Date[] dat = new Date[myCursor.getCount()];
SimpleDateFormat dfIn = new SimpleDateFormat("yyyy-MM-dd");
do{
try {
dat[kk]=dfIn.parse(myCursor.getString(0));
values[kk]=myCursor.getInt(1);
}
catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
kk++;
}
while(myCursor.moveToNext());
...
TimeSeries series = new TimeSeries("Line1");
for( int i = 0; i < dat.length; i++)
{
series.add(datki[i], values[i]);
}
I have a questions:
Dates and values I hold in separate tables.
How can I add to TimeSeries this data ???
Is it possible to add the date in the format mm-yyyy ???
Please help
If using chartfactory :
intent = ChartFactory.getTimeChartIntent(this, getDateDemoDataset(), getDemoRenderer(), "MM-yyyy");
If using timechart:
TimeChart chart = new TimeChart(dataset, renderer);
chart.setDateFormat("MM-yyyy");
Related
I am using PhilJay/MPAndroidChart library in my app and I'd like to know if 2 things are possible:
to show the last 14 days and then scroll for previous days?
Can the dates (currently on the top of the graph) be moved to the bottom, along the x axis?
Here is the current pic from the app and where i want to move date
my method:
private void populateGraph(Cursor data) {
ArrayList<Entry> cravingsPoints = new ArrayList<Entry>();
ArrayList<Entry> severityPoints = new ArrayList<Entry>();
ArrayList<String> dates = new ArrayList<String>();
int index = 0;
for (int i = 0; i < data.getCount(); i++) {
if (i == 0) {
// if orientation changed we need to start from the first one again
data.moveToFirst();
} else {
data.moveToNext();
}
try {
String date = data.getString(data.getColumnIndex(SmokeFreeContentProvider.DIARY_DATE));
int cravings = data.getInt(data.getColumnIndex(SmokeFreeContentProvider.DIARY_CRAVINGS_COUNT));
int severity = data.getInt(data.getColumnIndex(SmokeFreeContentProvider.DIARY_CRAVINGS_SEVERITY));
DateTime diaryEntry = DateTimeFormat.forPattern("yyyyMMdd").parseDateTime(date);
String entryLabel = diaryEntry.toString("dd MMM");
cravingsPoints.add(new Entry(cravings, index));
severityPoints.add(new Entry(severity, index));
dates.add(entryLabel);
index++;
} catch (Exception e) {
Log.e("SmokeFreeCravingsGraph", e.getMessage(), e);
}
}
LineDataSet cravingsLineData = new LineDataSet(cravingsPoints, getString(R.string.cravings));
LineDataSet severityLineData = new LineDataSet(severityPoints, getString(R.string.severity));
cravingsLineData.setCircleSize(4f);
cravingsLineData.setLineWidth(6f);
cravingsLineData.setColor(getResources().getColor(R.color.green));
severityLineData.setCircleSize(4f);
severityLineData.setLineWidth(6f);
severityLineData.setColor(getResources().getColor(android.R.color.holo_blue_light));
ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>();
dataSets.add(cravingsLineData);
dataSets.add(severityLineData);
Paint infoPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
infoPaint.setTextAlign(Paint.Align.CENTER);
infoPaint.setTextSize(com.github.mikephil.charting.utils.Utils.convertDpToPixel(14f));
infoPaint.setColor(getResources().getColor(R.color.dark_grey));
mChart.setDrawGridBackground(false);
mChart.setDrawYValues(false);
mChart.setDescription("");
mChart.setStartAtZero(true);
mChart.setPaint(infoPaint, Chart.PAINT_INFO);
mChart.setNoDataText(getString(R.string.no_cravings_info));
mChart.setNoDataTextDescription(getString(R.string.no_cravings_full_info));
mChart.setData(new LineData(dates, dataSets));
}
Yes, check the documentation: Modifying the Viewport
Take a look at the setVisibleXRange(float xRange) method.
Yes, check the documentation: XAxis
Take a look at the xAxis.setPosition(...) method.
Using the GraphView library i found this part of code:
/*
* use Date as x axis label
*/
long now = new Date().getTime();
data = new GraphViewData[size];
for (int i=0; i<size; i++) {
data[i] = new GraphViewData(now+(i*60*60*24*1000), rand.nextInt(20)); // next day
}
exampleSeries = new GraphViewSeries(data);
if (getIntent().getStringExtra("type").equals("bar")) {
graphView = new BarGraphView(
this
, "GraphViewDemo"
);
} else {
graphView = new LineGraphView(
this
, "GraphViewDemo"
);
((LineGraphView) graphView).setDrawBackground(true);
}
graphView.addSeries(exampleSeries); // data
That displays the date like "Sept 16, Sept 20" Ect etc... Is there possible change this code and display hour per hour? Like "06.00, 07.00, 08.00" etc etc?
You shoud use SimpleDateFormat for date formatting:
SimpleDateFormat hoursDateFormat = new SimpleDateFormat("h.mm");
for (int i=0; i<size; i++) {
data[i] = new GraphViewData(hoursDateFormat.format(now+(i*60*60*24*1000)), rand.nextInt(20)); // next day
}
I want to plot a XY line graph with some double values on Y axis and some String values on X axis. But the XYSeries takes only double/long values. So,is there any way I can use a string array on the X axis?
Thanks for any suggestions.
code:
//fDates are strings
XYSeries fPriceseries = new XYSeries("Fuel prices");
for(int i=0;i<fDates.length;i++)
{
long fDate = Long.parseLong(fDates[i]);
fPriceseries.add(fDate, fPrice[i]);
}
XYSeries fMileageSeries = new XYSeries("Mileage");
for(int i=0;i<fDates.length;i++)
{
long fDate = Long.parseLong(fDates[i]);
fMileageSeries.add(fDate, fMileage[i]);
}
Use TimeSeries:
fDates as Date array
TimeSeries fPriceseries = new TimeSeries("Fuel prices");
for(int i=0;i<fDates.length;i++)
{
fPriceseries.add(fDates[i], fPrice[i]);
}
TimeSeries fMileageSeries = new TimeSeries("Mileage");
for(int i=0;i<fDates.length;i++)
{
fMileageSeries.add(fDates[i], fMileage[i]);
}
fDates as String array - Using SimpleDateFormat.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
TimeSeries fPriceseries = new TimeSeries("Fuel prices");
for(int i=0;i<fDates.length;i++)
{
fPriceseries.add(sdf.parse(fDates[i]), fPrice[i]);
}
TimeSeries fMileageSeries = new TimeSeries("Mileage");
for(int i=0;i<fDates.length;i++)
{
fMileageSeries.add(sdf.parse(fDates[i]), fMileage[i]);
}
Referencies:
http://www.achartengine.org/content/javadoc/org/achartengine/model/TimeSeries.html
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
You cannot plot a graph using string on any axis.
Explanation:
When we plot a graph we compare two values... as in 3,5 or 7,22 or 12.3,10000..
Plotting string with respect to an integer or double,is like comparing apples and oranges.
So m sorry friend but its not possible.. unless you convert the string or create a reference for its contents..
I am trying to display a date in descending order in listview in android... I have written a program... It is showing it correctly, but when the first date of the month coming, the last month date are not displaying only one date is showing... What is the reason? How do I improve my code? Please guide me..
my code is here...
public void datesadd()
{
listview.setAdapter(new ListAdapter(this));
cc1=Calendar.getInstance();
int mon1=cc1.getTime().getDate();
Date dd=new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
while(mon1>=count)
{ pos=0;
line=new HashMap<String,String>();
String cdat=String.valueOf(cc1.get(Calendar.DATE));
#SuppressWarnings("deprecation")
String mons=String.valueOf(cc1.get(Calendar.MONTH));
String day1=String.valueOf(cc1.getTime().getDay());
#SuppressWarnings("deprecation")
String year1=String.valueOf(cc1.get(Calendar.YEAR));
try {
dd=format.parse(year1+"-"+mons+"-"+cdat);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
line.put("yeari", year1);
line.put("mont",mons);
line.put("dayi",dd.toString().substring(0, 3));
line.put("datei",cdat);
mon1--;
cc1.add(Calendar.DATE, -1);
Log.v("", "line");
disp.add(line);
// here disp is ArrayList<Hashmap<String,String>> object, i was declared it on top of my main program
}
}
I don't think you're going about date iteration right -- you're just iterating over the value in miliseconds.
Consider this:
/* From your code I'm not sure what count is, but you get the idea, you need
* a Date object here or you can just use a for() loop if you know the number
* |
* V */
while (cc1.getTime().after(count)) {
cc1.add(Calendar.DAY_OF_YEAR /*or month, year, whatever*/, -1);
// and then continue with your own code
line = new HashMap<String,String>();
String cdat = String.valueOf(cc1.get(Calendar.DATE));
// ...
}
I have an activity where I take the input from edit text and store it in an list.
I also store in list the current date.
Then , I press the save button which saves the above.
The next day the user enter some data more and save and so on.
I want to make a plot with x-axis date format and y axis the values the user entered.
In one activity I have:
...
String filename = "data.csv";
List<Double> mydata=new ArrayList<Double>();
List<Date> mydate=new ArrayList<Date>();
....value=(EditText) findViewById(R.id.enter_data);
...
switch (v.getId()){
case R.id.savebtn:
savefunc();
break;
case R.id.graphicsbtn:
Intent i = new Intent();
i.setClassName(this,LineGraph.class.getName());
this.startActivity(i);
break;
public void savefunc(){
SimpleDateFormat thedate = new SimpleDateFormat("dd/MM/yyyy");
Date d=new Date();
try{
d=thedate.parse(filename);
mydate.add(d);
}
catch (ParseException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
double thedata=Double.parseDouble(value.getText().toString().trim());
mydata.add(thedata);
..
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
for (int i=0;i<mydate.size();i++){
bw.write(mydate.get(i)+","+mydata.get(i)+"\n");
...
In the LineGraph Activity:
public class LineGraph extends Activity {
private static List<Date> date = new ArrayList<Date>();
private static List<Double> data = new ArrayList<Double>();
public Intent getIntent(Context context){
readfunc();
TimeSeries series = new TimeSeries("Showing data");
for (int i=0;i<date.size();i++){
series.add(date.get(i),data.get(i));
}
The read function:
public void readfunc(){
SimpleDateFormat thedate = new SimpleDateFormat("dd/MM/yyyy");
Date d=new Date();
try{
d=thedate.parse(filename);
}
catch..
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
do {
s = br.readLine();
if (s != null ){
String[] splitLine = s.split(",");
date.add(d);//Double.parseDouble(splitLine[0]));
data.add(Double.parseDouble(splitLine[1]));
I have these problems:
1) The file I receive is empty (some problem with the Date because the method for saving and reading from a file works).
2) At the graph screen appears a white background (of course no data because the file is empty) ,but why white background?I use the same code for other purposes and I don't receive a whitebackground.
3) I am not sure how to use Dates in x axis.Should I use List ? List ? .
------------------------UPDATE---------------------------------------------------------
Ok ,finally!(After user 'Dan' suggestion)
I used ChartFactory.getTimeChartView(this, dataset, mRenderer,"dd/MM/yyyy");
instead of ChartFactory.getLineChartIntent(context, dataset, mRenderer,"dd/MM/yyyy");
and you don't need to use String List , just Date List
The code that deal with your file must be something like this (not compiled):
public void savefunc(){
List<String> myDate = new ArrayList<String>(); //To store the formatted dates
SimpleDateFormat thedate = new SimpleDateFormat("dd/MM/yyyy");
Date d=new Date(); //the current date
String sd = thedate.format(d); // sd contains "16/04/2013", the formatted date
myDate.add(sd);
double thedata=Double.parseDouble(value.getText().toString().trim());
mydata.add(thedata);
...
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
for (int i=0;i<mydate.size();i++){
bw.write(mydate.get(i)+","+mydata.get(i)+"\n");
}
}
public void readfunc(){
SimpleDateFormat thedate = new SimpleDateFormat("dd/MM/yyyy");
Date d;
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
do {
s = br.readLine();
if (s != null ){
String[] splitLine = s.split(","); //first substring is the formatted date
date.add(thedate.parse(splitLine[0])); //do something with exception
data.add(Double.parseDouble(splitLine[1]));
...
Hope it helps.
for dynamic plots use GraphicalView rather then intent::
public GraphicalView mChartView;
creat a xml::
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:id="#+id/graph"
android:layout_width="fill_parent"
android:layout_height="145dip" >
</LinearLayout>
</RelativeLayout>
then in ur code :
LinearLayout layout = (LinearLayout) findViewById(R.id.graph);
mChartView = ChartFactory.mChartView = ChartFactory.getLineChartView(getBaseContext(), dataset, renderer)
layout.addView(mChartView);
After entering values you read from edit text fields right:
then you are passing the new values to add in respective arraylists
then you should call the code for linegraph again after adding new values and remember to clear series before reading arraylists (ie. dataset.clear();) ie. when line code function starts at beginning add dataset.clear(); because if u dont clear data will overlap and may through exception or line may look thick at old data ...
then call mChartView.repaint(); to refresh graph
these links too ll help u link1 link2