Dates on X-axis are not plotted achartengine line graph - android

I am stuck with this problem where I take date values from the sqlite database and try to plot them on X axis against some other values.But even after trying different solutions on SO I am unable to solve this.
Instead of my values I get random dates (1/30/1970) and the same date everywhere.
Please help me with this.
heres the code for getting the dates:
public Date[] getReportDates(ReportGraph reportGraph)
{
// TODO Auto-generated method stub
String [] columns = new String[]{KEY_ROW_ID, KEY_KM, KEY_FUEL_QTY, KEY_FUEL_PRICE, KEY_TOTAL_COST, KEY_MILEAGE, KEY_DATE,KEY_TANK_FULL};
String selectQuery = "SELECT _date FROM fuel_table";
reportCursor = ourDatabase.rawQuery(selectQuery, null);
int i = 0;
int count = reportCursor.getCount();
Date[] reportList = new Date[count];
if(reportCursor.moveToFirst())
{
do
{
reportList[i] = new Date(reportCursor.getLong(0));
i++;
} while(reportCursor.moveToNext());
}
reportCursor.close();
return reportList;
FOr graph plotting
double[] fPrice;
double[] fMileage;
Date[] fDates;
XYMultipleSeriesRenderer rRenderer;
XYMultipleSeriesDataset dataset;
XYSeriesRenderer priceRenderer, mileageRenderer,dateRenderer;
public Intent getIntent(Context context)
{
FuelStoredInfo reportInfo =new FuelStoredInfo(context);
reportInfo.open();
fPrice=reportInfo.getReportData(this);
fMileage = reportInfo.getReportMileage(this);
fDates = reportInfo.getReportDates(this);
reportInfo.close();
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]);
}
dataset = new XYMultipleSeriesDataset();
dataset.addSeries(fPriceseries);
dataset.addSeries(fMileageSeries);
}

Try to add date to the series in this way, may it works for you
long value = Math.abs(date.getTime() - 3* TimeChart.DAY);
series.add(new Date(value+ 3* TimeChart.DAY), x[i]);

Related

how to use graph view to represent sqlite data?

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;

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!

Error "Dataset and renderer should be not null and should have the same number of series" in Android

I am trying to display a graph with the data in the sqlitedatabase using AChartEngine library. I am having two records in database. BarChart graph displayed when there is one record. But with two records of data, it says, "Dataset and renderer should be not null and should have the same number of series". I dont understand this.
My code is,
Button ReportGraph = (Button) findViewById(R.id.ReportGraph);
ReportGraph.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GraphicalView GraphChartView = ChartFactory.getBarChartView(
getApplicationContext(), getWaterElectricityReading(),
getDemoRenderer(), Type.DEFAULT);
// Intent intent=ChartFactory.getLineChartIntent(this,
// getDemoDataset(), getDemoRenderer());
// startActivity(intent);
if (GraphChartView != null) {
GraphChartView.repaint();
}
relChartView.addView(GraphChartView);
mainLayout.setVisibility(View.GONE);
relChartView.setVisibility(View.VISIBLE);
}
});
private XYMultipleSeriesDataset getWaterElectricityReading() {
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd", Locale.US);
SimpleDateFormat df2 = new SimpleDateFormat("MMM dd yyyy");
Date StartDate;
Date EndDate;
String Pastdateformat = "";
String CurrentDateFormat = "";
SQLiteDatabase DB = Context
.openOrCreateDatabase("WaterElectricityReadingDataBase.db",
MODE_WORLD_READABLE, null);
Cursor c = DB
.rawQuery(
"select ReadingValue,strftime('%m/%d/%Y',StartDateTime) StartDateTime,strftime('%m/%d/%Y',EndDateTime) EndDateTime from WaterElectricity order by StartDateTime desc ",
null);
int rowCount = c.getCount();
if (c != null) {
if (rowCount > 0) {
if (c.moveToFirst()) {
do {
String ReadingValue = c.getString(c
.getColumnIndex("ReadingValue"));
String PastDate = c.getString(c
.getColumnIndex("StartDateTime"));
String CurrentDate = c.getString(c
.getColumnIndex("EndDateTime"));
try {
StartDate = df2.parse(PastDate);
Pastdateformat = sdf1.format(StartDate);
EndDate = df2.parse(CurrentDate);
CurrentDateFormat = sdf1.format(EndDate);
} catch (Exception e) {
}
XYSeries series = new XYSeries(
"WaterElectricityReading");
double ReadingVal = Double.parseDouble(ReadingValue);
series.add(rowCount, ReadingVal);
XYMultipleSeriesRenderer render = new XYMultipleSeriesRenderer();
dataset.addSeries(series);
rowCount++;
} while (c.moveToNext());
}
}
}
return dataset;
}
private XYMultipleSeriesRenderer getDemoRenderer() {
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
renderer.setAxisTitleTextSize(12);
renderer.setChartTitleTextSize(12);
renderer.setLabelsTextSize(15);
renderer.setLegendTextSize(15);
renderer.setPointSize(5f);
renderer.setMargins(new int[] { 20, 30, 15, 0 });
XYSeriesRenderer r = new XYSeriesRenderer();
r.setColor(Color.GREEN);
r.setPointStyle(PointStyle.DIAMOND);
r.setFillBelowLine(false);
r.setFillPoints(true);
renderer.addSeriesRenderer(r);
setChartSettings(renderer);
return renderer;
}
private void setChartSettings(XYMultipleSeriesRenderer renderer) {
renderer.setChartTitle("Chart demo");
renderer.setXTitle("x values");
renderer.setYTitle("y values");
renderer.setApplyBackgroundColor(false);
renderer.setRange(new double[] { 0, 6, -70, 40 });
renderer.setFitLegend(false);
renderer.setAxesColor(Color.BLACK);
renderer.setShowGrid(true);
renderer.setXAxisMin(0);
renderer.setXAxisMax(10.5);
renderer.setYAxisMin(0);
renderer.setZoomEnabled(false);
renderer.setYAxisMax(1000);
}
For two records, I want two bars to be displayed.
Can anyone please point out the Mistake.
Any Help will be appreciated!!
Thanks.
Your chart should be built using one single XYMultipleSeriesDataset and one single XYMultipleSeriesRenderer.
The XYMultipleSeriesDataset should contain as many XYSeries as there are XYSeriesRenderer in XYMultipleSeriesRenderer.
In your code you are creating an XYSeries for each record, which is probably wrong. The data should be in the same series unless you have a good reason not to do that. However, if you add multiple XYSeries then you will need one XYSeriesRenderer for each XYSeries.

need help in integrating achart-engine with database for android

Can u please help me in creating a simple bar chart (for android) where the values are got from sqlite database. for eg consider the following table
year Units Sold
2001 2000
2002 2100
2003 1900
I need to create a bar graph with x-axis as year and y-axis as units sold . Can u Plz consider this as a request . I dont know how to import data from database .
first you have to fetch the values from the data base and stored into array with corresponding data type . Do like this.....
List<int[]> initial;
int[] my_year;
int[] my_units_sold;
public void onCreate()
{
int Column1 = net_db_cur.getColumnIndex("Year");
int Column2 = net_db_cur.getColumnIndex("Units Sold");
cur = sampleDB.rawQuery("SELECT * FROM " + Table_Name , null);
my_year = new int[columncount];
my_units_sold = new int[columncount];
if (cur.moveToFirst())
{
for (int i = 0; i < columncount; i++)
{
my_year [i] = net_db_cur.getInt(Column1);
my_units_sold[i] = net_db_cur.getInt(Column2);
cur.moveToNext();
}
}
initial = new ArrayList<int[]>();
initial1.add(my_year);
initial1.add(my_units_sold);
ll.addView(createBarChart(initial ,Color.BLUE,10,0,14,2000000,20000000,1,x_axis_labels1,x_axis_labels2,y_axis_labels1, y_axis_net_labels2,Color.parseColor("#ffffff")));
}
public View createBarChart(int[] values,int[] colors,int lable_text_size,int xMin,int xMax,int yMin,int yMax,double bar_space,double[] x_axis_lables1,String[] x_axis_lables2,double[] y_axis_lables1,String[] y_axis_lables2, int lable_color)
{
XYMultipleSeriesRenderer mrenderer = new XYMultipleSeriesRenderer();
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
/*for (int i = 0; i <values.length; i++)
{*/
CategorySeries series = new CategorySeries("");
/*double[] v = values.get(i);
int seriesLength = v.length;*/
for (int k = 0; k < values.length; k++)
{
series.add(values[k]);
}
dataset.addSeries(series.toXYSeries());
//}
//mrenderer.setMargins(new int[] { 10, 65, 10, 15 });
int color_length = colors.length;
for (int i = 0; i < color_length; i++)
{
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(colors[i]);
r.setChartValuesSpacing(15);
mrenderer.addSeriesRenderer(r);
}
mrenderer.setOrientation(Orientation.HORIZONTAL);
mrenderer.setInScroll(false);
mrenderer.setGridColor(Color.BLACK);
mrenderer.setYLabelsAlign(Align.RIGHT);
mrenderer.setPanEnabled(false, false);
mrenderer.setZoomEnabled(false, false);
mrenderer.setBarSpacing(bar_space);
mrenderer.setLabelsTextSize(lable_text_size);
mrenderer.setAxesColor(Color.BLACK);
mrenderer.setXAxisMin(xMin);
mrenderer.setXAxisMax(xMax);
for(int i=0;i<x_axis_lables2.length;i++)
{
mrenderer.addXTextLabel(x_axis_lables1[i],x_axis_lables2[i]);
}
mrenderer.setYAxisMin(yMin);
mrenderer.setYAxisMax(yMax);
for(int j=0;j<y_axis_lables1.length;j++)
{
mrenderer.addYTextLabel(y_axis_lables1[j],y_axis_lables2[j]);
}
mrenderer.setLabelsColor(lable_color);
return (ChartFactory.getBarChartView(Income.this, dataset, mrenderer, Type.DEFAULT));
}
You will get the bar chart for with data base values. All the best.

Add value from Array to an XY Series

I want to add a value from SQLite to an XY series to create a diagram. Here is what I've done so far:
Double a, b;
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
Cursor notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor);
ArrayList x = new ArrayList();
ArrayList y = new ArrayList();
notesCursor.moveToFirst();
for(int i = 0; i<notesCursor.getCount();i++){
a = notesCursor.getDouble(notesCursor.getColumnIndex(mDbHelper.KEY_ROWID));
b = notesCursor.getDouble(notesCursor.getColumnIndex(mDbHelper.KEY_RESULT));
}
x.add(a);
y.add(b);
notesCursor.moveToNext();
mCurrentSeries.add(x, y);
if (mChartView != null) {
mChartView.repaint();
}
But I've got a problem at the line:
mCurrentSeries.add(x, y);
How I can add an Array to an XY series? Any suggestions?
not sure what library you are using here to create your diagram (chart?). I use aChartEngine which is pretty good. The code I use to get a dataset containing a time series in aChartEngine is:
public static XYMultipleSeriesDataset getDemoDataset(Cursor c,
String title, String... columnName) {
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
TimeSeries series = new TimeSeries(title);
try {
if (c.moveToFirst()) {
do {
int mins = c.getInt(c.getColumnIndex(columnName[0]));
java.util.Date date =null;
try{
date = DateFactory.stringToDate(c.getString(c.getColumnIndex(columnName[1])));
}catch(Exception e){
}
if(date==null){
continue;
}
series.add(date, mins);
} while (c.moveToNext());
} else {
Log.d(TAG, "There were no values in the cursor.");
}
} finally {
Log.d(TAG, "finally from getDemoDataset being called");
c.close();
}
dataset.addSeries(series);
return dataset;
}

Categories

Resources