Not able to plot line graph using aChartEngine.I am reading(Temperature and time in milliseconds) from SQLite database

StackOverflow https://stackoverflow.com/questions/23196063

  •  06-07-2023
  •  | 
  •  

Question

I would like to plot a line graph using aChartEngine.I am reading temperature and time from my SQLite database. The values are being stored and also are being read from the DB successfully but the linear layout where the graph should be displayed is empty. kindly help. Thank you in advance.

MainActivity.java

package com.database_trial;
import java.util.List;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import trial.helper.DBHelper;
import trial.model.Temperature;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
    DBHelper db;
    private GraphicalView mChart;
     //arrays for x and y axis of graph


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);// deleting old data
        db = new DBHelper(getApplicationContext());
        Log.d("ans1", "fyn here");
        db.deleteTempReadings();
        // inserting data to temp table
        Log.i("insert", "Inserting Records...");
        db.insertTemperature(new Temperature("12.35"));
        db.insertTemperature(new Temperature("25.36"));
        db.insertTemperature(new Temperature("35.34"));
        // reading data from db
        Log.i("Reading", "Reading Records...");

        List<Temperature> temp = db.getAllTempReadings();

        int arraySize=temp.size();
        double tempArray[]=new double[arraySize];
        int timeArray[]=new int [arraySize];


        //Log.d("ans", String.valueOf(temp.size()));


        for (Temperature t : temp) {

            String log="SENSOR ID: "+t.getSensorId()+"TEMPERATURE: "+t.getTemperature()+"TIME: "+t.getTimestamp();
            Log.d("Record"+t, log);
        }
            // Reading values into the array!

            for(int i=0;i<arraySize;i++){

                tempArray[i]=Double.parseDouble(temp.get(i).getTemperature());

                timeArray[i]=Integer.parseInt(temp.get(i).getTimestamp());
                System.out.println("i: "+ tempArray[i]+" ,"+timeArray[i]);
        }
            TimeSeries series=new TimeSeries("Line1");

            for(int i=0;i<tempArray.length;i++){
                series.add(tempArray[i],timeArray[i]);
            }
            XYMultipleSeriesDataset dataset=new XYMultipleSeriesDataset();
            dataset.addSeries(series);

             //properties of line 
            XYSeriesRenderer renderer =new XYSeriesRenderer();
            renderer.setColor(Color.YELLOW);
            renderer.setPointStyle(PointStyle.DIAMOND);
            renderer.setFillPoints(true);

            XYMultipleSeriesRenderer mRenderer=new XYMultipleSeriesRenderer();

            mRenderer.addSeriesRenderer(renderer);
            mRenderer.setBackgroundColor(Color.BLACK);
            mRenderer.setChartTitle("TEMPERATURE LINE GRAPH");
            mRenderer.setAxesColor(Color.YELLOW);
            mRenderer.setApplyBackgroundColor(true);
            mRenderer.setXTitle("TEMPERATURE");
            mRenderer.setYTitle("TIME");
            mRenderer.setZoomButtonsVisible(true);
             for(int i=0;i<tempArray.length;i++)
                {
                 mRenderer.addXTextLabel(i, " :temp");

                }
             LinearLayout chart_container=(LinearLayout)findViewById(R.id.lineGraph);
             mChart = ChartFactory.getLineChartView(this, dataset,mRenderer);
             if(mChart==null){
                 Log.i("mChart: ", "null");
             }
             else{
                 Log.i("mChart: ", "not null but not displaying graph");
             }


        }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

/* DBHelper.java */

package trial.helper;


    import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import trial.model.Temperature;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

    public class DBHelper extends SQLiteOpenHelper {
        private static final String DATABASE_NAME = "SensorDB";
        private static final int DATABASE_VERSION = 1;
        private static final String LOG = DBHelper.class.getName();

        // TABLE NAMES
        private static final String TEMPERATURE_TABLE = "temp_table";

        // temperature class
        private static final String KEY_SENSOR_ID = "sensor_id";
        private static final String KEY_TEMPERATURE = "temperature";
        private static final String KEY_TIMESTAMP = "timestamp";

        String CREATE_TEMP_TABLE = "CREATE TABLE " + TEMPERATURE_TABLE + "("
                + KEY_SENSOR_ID + " TEXT ," + KEY_TEMPERATURE + " REAL, "
                + KEY_TIMESTAMP + " TEXT DEFAULT CURRENT_TIMESTAMP )";

        public DBHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_TEMP_TABLE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + TEMPERATURE_TABLE);
            onCreate(db);
        }

        // CRUD OPERATIONS
        // --TEMPERATURETABLE--//

        // INSERT RECORD INTO TEMPERATURE TABLE
        public void insertTemperature(Temperature temp) {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues values = new ContentValues();

            SimpleDateFormat dateFormat = new SimpleDateFormat(
                    "SSS", Locale.getDefault());
            Date date = new Date();

            values.put(KEY_SENSOR_ID, "MySensor");
            values.put(KEY_TEMPERATURE, temp.getTemperature());
            values.put(KEY_TIMESTAMP, dateFormat.format(date));

            try
            {
                db.insert(TEMPERATURE_TABLE, null, values);         
            }catch(Exception ex){
                Log.d("Exception in inserting data", ex.toString());
            }finally{
                db.close(); 
            }
        }

        // READ ALL RECORDS
        public List<Temperature> getAllTempReadings() {
            List<Temperature> temp = new ArrayList<Temperature>();
            SQLiteDatabase db = this.getReadableDatabase();
            String selectQuery = "SELECT * FROM " + TEMPERATURE_TABLE;

            Cursor c = db.rawQuery(selectQuery, null);
            if (c.moveToFirst()) {
                do {
                    Temperature t = new Temperature(); 
                    t.setSensorId(c.getString(0));
                    t.setTemperature(c.getString(1));
                    t.setTimestamp(c.getString(2));
                    temp.add(t);                
                } while (c.moveToNext());
            }

            return temp;
        }

        // DELETE All RECORDs
        public void deleteTempReadings() {
            SQLiteDatabase db = this.getWritableDatabase();
            String selectQuery = "Delete from " + TEMPERATURE_TABLE;
            db.execSQL(selectQuery);
            Log.d(LOG, selectQuery);
        }
}

/* **This is my model class for the database
Temperature.java** */

package trial.model;

import java.util.*;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class Temperature {


        String sensor_id;
        String temperature;
        String timestamp;

        public Temperature() {

        }

        public Temperature(String temperature) {
            this.temperature = temperature;
        }

        public Temperature(String sensor_id, String temperature, String timestamp) {
            this.sensor_id = sensor_id;
            this.temperature = temperature;
            this.timestamp = timestamp;

        }

        // getters

        public String getSensorId() {
            return this.sensor_id;
        }

        public String getTemperature() {
            return this.temperature;
        }


        public String getTimestamp() {
            return this.timestamp;
        }

        // setters
        public void setSensorId(String sensor_id) {
            this.sensor_id = sensor_id;
        }

        public void setTemperature(String temperature) {
            this.temperature = temperature;
        }

        public void setTimestamp(String timestamp) {
            this.timestamp = timestamp;
        }

    }

// activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="110dp"
        android:layout_marginTop="197dp"
        android:orientation="vertical" 
        android:id="@+id/lineGraph">
    </LinearLayout>

</RelativeLayout>

// logcat

04-21 06:48:19.974: D/dalvikvm(2386): Not late-enabling CheckJNI (already on)
04-21 06:48:21.545: D/ans1(2386): fyn here
04-21 06:48:21.833: D/trial.helper.DBHelper(2386): Delete from temp_table
04-21 06:48:21.864: I/insert(2386): Inserting Records...
04-21 06:48:22.023: I/Reading(2386): Reading Records...
04-21 06:48:22.054: D/Recordtrial.model.Temperature@41730cf8(2386): SENSOR ID: MySensor TEMPERATURE: 12.35 TIME: 967
04-21 06:48:22.054: D/Recordtrial.model.Temperature@41730e70(2386): SENSOR ID: MySensor TEMPERATURE: 25.36 TIME: 994
04-21 06:48:22.054: D/Recordtrial.model.Temperature@41730f50(2386): SENSOR ID: MySensor TEMPERATURE: 35.34 TIME: 022
04-21 06:48:22.063: I/System.out(2386): i: 12.35 ,967
04-21 06:48:22.063: I/System.out(2386): i: 25.36 ,994
04-21 06:48:22.063: I/System.out(2386): i: 35.34 ,22
04-21 06:48:22.554: D/dalvikvm(2386): GC_FOR_ALLOC freed 207K, 12% free 2810K/3176K, paused 39ms, total 45ms
04-21 06:48:22.623: I/mChart:(2386): not null but not displaying graph
04-21 06:48:22.943: D/gralloc_goldfish(2386): Emulator without GPU emulation detected.
04-21 06:48:23.053: I/ActivityManager(374): Displayed com.database_trial/.MainActivity: +3s220ms
Was it helpful?

Solution

check out this link Visit http://androidforbegineers.blogspot.in/2013/07/bar-chart-in-android-using-achartengine.html Also if you haven't added this line in android manifest add it as an activity

activity android:name="org.achartengine.GraphicalActivity"

it will be good if you add a button in the main activity to generate the graph (this is the method followed in the above link) also use bundle approach to pass the data from database to chart generation class (android - how to make plot with user data)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top