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;
Related
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]);
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!
Hi can some one suggest me a sample example of how i can sort the textviews based on the numbers in textviews. I am able to get the text from the TextViews need to sort and place the lowest number first.
Thank you.
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
for (int i = 0; i < intValues.length; i++) {
Integer intValue = intValues[i];
//here I want to assign sorted numberes to the TextViews
}
}
So I have followed Jeffrey's advice. Here is the code which still doesn't work properly. What could be wrong?
Created an array of TextViews:
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
tvs[2] = textView43;
tvs[3] = textView53;
tvs[4] = textView63;
tvs[5] = textView73;
tvs[6] = textView83;
Sorted the array and assinged new values to the TextViews:
Arrays.sort(tvs, new TVTextComparator());
textView23.setText(tvs[0].getText().toString());
textView33.setText(tvs[1].getText().toString());
textView43.setText(tvs[2].getText().toString());
textView53.setText(tvs[3].getText().toString());
textView63.setText(tvs[4].getText().toString());
textView73.setText(tvs[5].getText().toString());
textView83.setText(tvs[6].getText().toString());
And here is the Comporator class:
public class TVTextComparator implements Comparator<TextView> {
public int compare(TextView lhs, TextView rhs) {
Integer oneInt = Integer.parseInt(lhs.getText().toString());
Integer twoInt = Integer.parseInt(rhs.getText().toString());
return oneInt.compareTo(twoInt);
}
}
to sort your textViews, first put them in an array,
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
// and so on
note that if you have handle to the parent container, you could easily build the array by using ViewGroup.getChildCount() and getChildAt().
now write a comparator for a text view,
class TVTextComparator implements Comparator<TextView> {
#Override
public int compare(TextView lhs, TextView rhs) {
return lhs.getText().toString().compareTo(rhs.getText().toString());
// should check for nulls here, this is NOT a robust impl of compare()
}
}
now use the comparator to sort the array,
Arrays.sort(tvs, 0, tvs.length, new TVTextComparator());
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
textView23.setText(intValues[0]);
textView33.setText(intValues[1]);
textView43.setText(intValues[2]);
textView53.setText(intValues[3]);
textView63.setText(intValues[4]);
textView73.setText(intValues[5]);
textView83.setText(intValues[6]);
}
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.
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;
}