如何从数据库中取值来绘制条形图?

时间:2012-12-11 06:38:20

标签: android sqlite bar-chart achartengine

您好我是Android的新手,我正在开发一个应用程序,以显示使用achartengine的前10个旅游目的地。问题是我使用生成的随机值来绘制图形。我需要的是连接使用sqlite数据浏览器创建的数据库来绘制图形。我按照以下教程绘制图形http://www.youtube.com/watch?v=E9fozQ5NlSo。但我没有找到很多关于如何连接数据库来绘制条形图的教程。请发布以上链接。

package flu.solutions.travelsense;


import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer.Orientation;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;  
import android.view.Menu;
public class ChartActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        XYMultipleSeriesRenderer renderer = getBarDemoRenderer();
        setChartSettings(renderer);
        Intent intent = ChartFactory.getBarChartIntent(this, getBarDemoDataset(), renderer, Type.DEFAULT);
        startActivity(intent);
    }

    public Intent createIntent() 

     {

    String[] titles = new String[] { "Top 10 Destinations", " " };
    List<double[]> values = new ArrayList<double[]>();
    values.add(new double[] { 8, 6, 4, 6, 7, 7, 9, 5, 7, 8, 8 });
    values.add(new double[] {});

    int[] colors = new int[] { Color.RED, Color.BLACK};

    XYMultipleSeriesRenderer renderer = buildBarRenderer(colors);
    renderer.setOrientation(Orientation.HORIZONTAL);

    setChartSettings(renderer);

    renderer.setXLabels(1);
    renderer.setYLabels(10);

    renderer.addXTextLabel(1, "Bangalore");
    renderer.addXTextLabel(2, "Mysore");
    renderer.addXTextLabel(3, "Chennai");
    renderer.addXTextLabel(4, "Delhi");
    renderer.addXTextLabel(5, "Kolkatta");
    renderer.addXTextLabel(6, "Kashmir");
    renderer.addXTextLabel(7, "Hyderabad");
    renderer.addXTextLabel(8, "Mumbai");
    renderer.addXTextLabel(9, "Kerala");
    renderer.addXTextLabel(10, "Gujarat");

    int length = renderer.getSeriesRendererCount();
    for (int i = 0; i < length; i++) 
    {
      SimpleSeriesRenderer seriesRenderer = renderer.getSeriesRendererAt(i);
      seriesRenderer.setDisplayChartValues(false);
      }

    return ChartFactory.getBarChartIntent(this, buildBarDataset(titles, values), renderer,Type.DEFAULT);
    }

    public XYMultipleSeriesRenderer getBarDemoRenderer() {
        XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
        renderer.setAxisTitleTextSize(16);
        renderer.setChartTitleTextSize(20);
        renderer.setLabelsTextSize(15);
        renderer.setLegendTextSize(15);
        renderer.setMargins(new int[] {20, 30, 15, 0});
        SimpleSeriesRenderer r = new SimpleSeriesRenderer();
        r.setColor(Color.BLUE);
        renderer.addSeriesRenderer(r);
        r = new SimpleSeriesRenderer();
        r.setColor(Color.GREEN);
        renderer.addSeriesRenderer(r);
        return renderer;
      }

     private XYMultipleSeriesDataset getBarDemoDataset() {
        XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
        final int nr = 10;
        Random r = new Random();
        int SERIES_NR = 2;
        for (int i = 0; i < SERIES_NR; i++) {
          CategorySeries series = new CategorySeries("Demo series " + (i + 1));
          for (int k = 0; k < nr; k++) {
            series.add(100 + r.nextInt() % 100);
          }
          dataset.addSeries(series.toXYSeries());
        }
        return dataset;
      }



    private void setChartSettings(XYMultipleSeriesRenderer renderer) {
        renderer.setChartTitle("Chart demo");
        renderer.setXTitle("x values");
        renderer.setYTitle("y values");
        renderer.setXAxisMin(0);
        renderer.setXAxisMax(5);
        renderer.setYAxisMin(0);
        renderer.setYAxisMax(250);
      }
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_chart, menu);
        return true;
    }
      }

你能告诉我这里我做错了什么。

2 个答案:

答案 0 :(得分:2)

请参阅此链接,您可能会发现它很有用

Generating graph by using remote data from database on achartengine

并回答我的任何疑问。

答案 1 :(得分:1)

首先告诉我你的数据库在哪里 1 GT;它是您的应用程序的本地 2 - ;是在服务器中(有多种方法可以访问ex:你可以发送http请求从服务器获取数据) 3&gt;是数据库在您的手机中的另一个应用程序,您可以使用内容提供商来访问数据。

试试这段代码

public class DataBaseHelper extends SQLiteOpenHelper {
    private Context mycontext;

    //private String DB_PATH = mycontext.getApplicationContext().getPackageName()+"/databases/";
    private static String DB_NAME = "(datbasename).sqlite";//the extension may be .sqlite or .db
    public SQLiteDatabase myDataBase;
    /*private String DB_PATH = "/data/data/"
                        + mycontext.getApplicationContext().getPackageName()
                        + "/databases/";*/

    public DataBaseHelper(Context context) throws IOException {
        super(context,DB_NAME,null,1);
        this.mycontext=context;
        boolean dbexist = checkdatabase();
        if (dbexist) {
            //System.out.println("Database exists");
            opendatabase(); 
        } else {
            System.out.println("Database doesn't exist");
            createdatabase();
        }
    }

    public void createdatabase() throws IOException {
        boolean dbexist = checkdatabase();
        if(dbexist) {
            //System.out.println(" Database exists.");
        } else {
            this.getReadableDatabase();
            try {
                copydatabase();
            } catch(IOException e) {
                throw new Error("Error copying database");
            }
        }
    }   

    private boolean checkdatabase() {
        //SQLiteDatabase checkdb = null;
        boolean checkdb = false;
        try {
            String myPath = DB_PATH + DB_NAME;
            File dbfile = new File(myPath);
            //checkdb = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
            checkdb = dbfile.exists();
        } catch(SQLiteException e) {
            System.out.println("Database doesn't exist");
        }
        return checkdb;
    }

    private void copydatabase() throws IOException {
        //Open your local db as the input stream
        InputStream myinput = mycontext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outfilename = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myoutput = new FileOutputStream("/data/data/(packagename)/databases   /(datbasename).sqlite");

        // transfer byte to inputfile to outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myinput.read(buffer))>0) {
            myoutput.write(buffer,0,length);
        }

        //Close the streams
        myoutput.flush();
        myoutput.close();
        myinput.close();
    }

    public void opendatabase() throws SQLException {
        //Open the database
        String mypath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);
    }

    public synchronized void close() {
        if(myDataBase != null) {
            myDataBase.close();
        }
        super.close();
    }

}

从资产文件夹中读取数据库..