代码之家  ›  专栏  ›  技术社区  ›  sagar shetty

如何根据存储在sqlite中的个别值更改mpandroidcharts中的条形图颜色?

  •  0
  • sagar shetty  · 技术社区  · 8 年前

    如果有一个sqlite,它存储3个值:名称、学分、床铺。我有一个带有x轴:名称,y轴:床铺的MPandroid条形图。我想更改单个条形图的颜色,或者根据每个条目的学分添加限制线,存储在sqlite中。这有可能吗? 我是新来的,请帮帮我。

    public class Myhelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME="mydatabase.db";
        public static final String TABLE_NAME="mytable";
        public static final String COLUMN_ID="_id";
        public static final String COL_1="NAME";
        public static  final String COL_2="CREDIT";
        public  static final String COL_3="BUNKS";
        public static final String[] COLUMNS ={COLUMN_ID,COL_1,COL_2,COL_3};
        Context con;
    
        public Myhelper(Context context) {
            super(context, DATABASE_NAME, null, 1);
            con = context;
        }
    
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            String createTable= "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID +" INTEGER PRIMARY KEY AUTOINCREMENT, " + " NAME TEXT, CREDIT TEXT, BUNKS INTEGER )";
            db.execSQL(createTable);
            Toast.makeText(con,"table created",Toast.LENGTH_SHORT).show();
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
            onCreate(db);
    
        }
        public boolean insertData(String x,String y,int z){
            SQLiteDatabase db=this.getWritableDatabase();
            ContentValues contentValues = new ContentValues();
            contentValues.put(COL_1, String.valueOf(x));
            contentValues.put(COL_2,String.valueOf(y));
           contentValues.put(COL_3,z);
            long result = db.insert(TABLE_NAME, null, contentValues);
            if (result == -1) {
                return false;
            } else {
                return true;
            }
        }
    
        public ArrayList<String> queryXdata(){
            ArrayList<String> xnewdata= new ArrayList<String>();
            String query = "SELECT "+ COL_1 + " FROM " + TABLE_NAME;
            SQLiteDatabase db=this.getWritableDatabase();
            Cursor cursor= db.rawQuery(query,null);
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
                xnewdata.add(cursor.getString(cursor.getColumnIndex(COL_1)));
            }
            cursor.close();
            return xnewdata;
    
        }
        public ArrayList<Integer> queryYdata(){
            ArrayList<Integer> ynewdata= new ArrayList<Integer>();
            String query = "SELECT "+ COL_3+ " FROM " + TABLE_NAME;
            SQLiteDatabase db=this.getWritableDatabase();
            Cursor cursor= db.rawQuery(query,null);
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
                ynewdata.add(cursor.getInt(cursor.getColumnIndex(COL_3)));
            }
            cursor.close();
            return ynewdata;
    
        }
        public  ArrayList<Integer> queryZdata(){
           ArrayList<Integer> znewdata= new ArrayList<Integer>();
            String query = "SELECT "+ COL_2+ " FROM " + TABLE_NAME;
            SQLiteDatabase db=this.getWritableDatabase();
            Cursor cursor= db.rawQuery(query,null);
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
                znewdata.add(((cursor.getColumnIndex(COL_2))));
            }
            cursor.close();
            return znewdata;
        }
    
        public attendence getdetails(long id){
            SQLiteDatabase db = this.getWritableDatabase();
            String query= "SELECT" + COL_2+" FROM " + TABLE_NAME +" WHERE _id=" + id;
            Cursor cursor= db.rawQuery(query,null);
            attendence attendence1= new attendence();
            if (cursor.getCount()>0){
                cursor.moveToFirst();
                attendence1.setSubname(cursor.getString(cursor.getColumnIndex(COL_1)));
                attendence1.setCredit(cursor.getString(cursor.getColumnIndex(COL_2)));
                attendence1.setBunks(cursor.getInt(cursor.getColumnIndex(COL_3)));
            }
            return attendence1;
        }
    
        public void delete(long id,Context context){
            SQLiteDatabase db=this.getWritableDatabase();
            db.execSQL("DELETE FROM "+TABLE_NAME+" WHERE _id='"+id+"'");
            Toast.makeText(context,"delted",Toast.LENGTH_SHORT).show();
        }
        public List<attendence> list(String  filter){
            String query;
            if (filter.equals("")){
                query = "SELECT * FROM " + TABLE_NAME ;
    
            }
            else {
                query= " SELECT * FROM " + TABLE_NAME ;
    
            }
            List<attendence> linkedlist = new LinkedList<>();
            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(query,null);
            attendence attendence;
            if (cursor.moveToFirst()){
                do {
                    attendence = new attendence();
                    attendence.setId(cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
                    attendence.setSubname(cursor.getString(cursor.getColumnIndex(COL_1)));
                    attendence.setCredit(cursor.getString(cursor.getColumnIndex(COL_2)));
                    attendence.setBunks(cursor.getInt(cursor.getColumnIndex(COL_3)));
                    linkedlist.add(attendence);
                }
                while (cursor.moveToNext());
            }
            return linkedlist;
        }
    
    
        public int getbunk(long id) {
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + " = " + String.valueOf(id), null);
            int output = -1;
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    output = cursor.getInt(cursor.getColumnIndex(COL_3));
                }
                cursor.close();
            }
            return output;
    
        }
        public int updatebunk(long id){
            SQLiteDatabase db = this.getWritableDatabase();
            int bunk = getbunk(id);
            if (bunk<0){
                Log.i("error", "updatebunk:below 0 ");
    
            }
            int bunkinc= ++bunk;
            ContentValues contentValues= new ContentValues();
            contentValues.put(COL_3, bunkinc);
            db.update(TABLE_NAME,contentValues,COLUMN_ID+ "=?",new String[]{String.valueOf(id)});
            db.close();
    
            return bunkinc;
        }
        public int updatebunkdelete(long id){
            SQLiteDatabase db = this.getWritableDatabase();
            int bunk = getbunk(id);
            int bunkdec= --bunk;
            ContentValues contentValues= new ContentValues();
            contentValues.put(COL_3,bunkdec);
            db.update(TABLE_NAME,contentValues,COLUMN_ID+ "=?",new String[]{String.valueOf(id)});
            db.close();
            return bunkdec;
        }
    }
    

    我的活动(条形图)

    public  void addData(){
            ArrayList<BarEntry> yVals = new ArrayList<>();
            for (int i=0; i<myhelper.queryYdata().size(); i++){
                yVals.add(new BarEntry((((myhelper.queryYdata().get(i)))),i));
            }
            ArrayList<String> xvals= new ArrayList<>();
        for (int i=0;i<myhelper.queryXdata().size();i++){
            xvals.add(myhelper.queryXdata().get(i));
        }
    
    
        MyBarDataset dataSet= new MyBarDataset(yVals,"");
        dataSet.setColors(new int[]{ContextCompat.getColor(mcontext,R.color.green),
        ContextCompat.getColor(mcontext,R.color.yellow),
        ContextCompat.getColor(mcontext,R.color.red)});
        BarData data = new BarData(xvals,dataSet);
        mychart.setData(data);
        //bar custamization
        mychart.animateY(1000);
        mychart.setDrawGridBackground(false);
        mychart.setBackgroundColor(Color.WHITE);
        mychart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
        mychart.getAxisRight().setEnabled(false);
        mychart.setDescription("");
        mychart.getLegend().setEnabled(false);
        mychart.getXAxis().setDrawGridLines(false);
        mychart.getAxisLeft().setDrawGridLines(false);
        mychart.getAxisLeft().setStartAtZero(true);
        mychart.getAxisLeft().setAxisMinValue(0);
    
    
    }
    public class MyBarDataset extends BarDataSet{
    
        public MyBarDataset(List<BarEntry> yVals, String label) {
            super(yVals, label);
        }
    
        @Override
        public int getColor(int index){
    
    
            if (getEntryForXIndex(index).getVal()<8){
                return mColors.get(0);
            }
            else if (getEntryForXIndex(index).getVal()<13)
                return mColors.get(1);
            else
                return mColors.get(2);
    
        }
    }
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Tyler V    8 年前

    据我所知,您希望基于 bunk绘制条形图,但基于 credits对其进行着色。使用自定义条形数据集是正确的方法,只需要稍微修改一下。下面的代码得到了您正在描述的内容。

    我所做的更改:

    • 无法将名称列表传递给 bardata,请改用axis-value格式化程序
    • 已更改自定义条形数据集以同时保存 credits array。不确定您的 getEntryForXIndex method是否在其他地方定义,但它不在您发布的代码中。
    • 删除了不推荐使用的调用和无效语法(can't call setdescription(“”); )。

    如果这不是你要找的,请用更多关于你所看到的内容等细节更新问题…据我所知,问题是关于图表,而不是关于SQL数据库。

    覆盖 创建时受保护的void(bundle savedinstanceState){ super.oncreate(保存的状态); setContentView(r.layout.activity_-main); 条形图=findViewByID(r.id.test_chart); //一些组合数据-用 //queryydata、queryxdata和queryzdata方法 string[]name=new string[]“foo”、“bar”、“fiz”、“bam”、“boo” list<float>credits=new arraylist<>(arrays.aslist(1f,9f,2.5f,15f,50f)); 浮动[]铺位=新浮动[]10F、15F、16F、20F、5F; list<barentry>entries=new arraylist<>(); 对于(int i=0;i<bunks.length;+i){ 添加(新的barentry(i,bunks[i]); } float textsize=16F; mybardataset dataset=new mybardataset(entries,“data”,credits); dataset.setcolors(contextcompat.getcolor(this,r.color.green)), contextcompat.getcolor(此,r.color.yellow), contextcompat.getcolor(this,r.color.red)); bardata data=新的bardata(数据集); data.setdrawvalues(假); 数据。设定杆宽度(0.9f); chart.setdata(数据); 图表.设置条(真); chart.getxaxis().setValueFormatter(new indexaxisValueForMatter(name)); chart.getxaxis().setposition(xaxis.xaxisposition.bottom); chart.getxaxis().settextsize(文本大小); chart.getaxisleft().settextSize(文本大小); chart.setExtraBottomOffset(10f)图表; chart.getaxisright().setEnabled(假); description desc=new description(); desc.settext(“”); chart.setdescription(描述); chart.getLegend().setEnabled(假); chart.getxaxis().setDrawGridLines(false); chart.getaxisleft().setDrawGridLines(false); chart.invalidate(); } 公共类MyBardataset扩展Bardataset{ 私有列表<float>credits; mybardataset(list<barentry>yvals,string label,list<float>credits){ 超级(YVAL,标签); this.credits=学分; } @重写 public int getcolor(int索引){ float c=credits.get(索引); 如果(C & lt;8){ 返回mcolors.get(0); } 否则,如果(c<13){ 返回mcolors.get(1); } 否则{ 返回mcolors.get(2); } } } < /代码>

    edit: an aside about the SQL database-don't call queryxdata and queryydata inside the loop!这将在每次循环迭代中提取整个数据数组,然后在循环本身内部提取(非常昂贵)。用这样的东西代替:

    arraylist<barentry>yvals=new arraylist<>();
    arrayList<integer>ydata=myHelper.queryydata();
    对于(int i=0;i<ydata.size();i++){
    yvals.add(新barentry(i,ydata.get(i)));
    }
    
    arraylist<string>xdata=myhelper.queryxdata();
    < /代码> 
    正确的方法,只需要稍微修改一下。下面的代码得到了您正在描述的内容。

    我所做的改变:

    • 无法将名称列表传递给BarData,请改用轴值格式化程序
    • 已更改自定义条形数据集以同时保留信用数组。不确定您的getEntryForXIndex方法在其他地方定义,但它不在您发布的代码中。
    • 删除了不推荐使用的调用和无效语法(无法调用setDescription("");)

    如果这不是你要找的,请用更多关于你所看到的内容等细节更新问题…据我所知,这个问题是关于图表的,而不是关于SQL数据库的。

    Screenshot of example chart

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        BarChart chart = findViewById(R.id.test_chart);
    
        // Some made up data - replace these with your
        //  queryYdata, queryXdata, and queryZdata methods
        String[] names = new String[]{"foo","bar","fiz","bam","boo"};
        List<Float> credits = new ArrayList<>(Arrays.asList(1f,9f,2.5f,15f,50f));
        float[] bunks = new float[]{10f,15f,16f,20f,5f};
    
        List<BarEntry> entries = new ArrayList<>();
        for(int i = 0; i < bunks.length; ++i) {
            entries.add(new BarEntry(i, bunks[i]));
        }
    
        float textSize = 16f;
    
        MyBarDataset dataSet = new MyBarDataset(entries, "data", credits);
        dataSet.setColors(ContextCompat.getColor(this,R.color.green),
                ContextCompat.getColor(this,R.color.yellow),
                ContextCompat.getColor(this,R.color.red));
        BarData data = new BarData(dataSet);
        data.setDrawValues(false);
        data.setBarWidth(0.9f);
    
        chart.setData(data);
        chart.setFitBars(true);
        chart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(names));
        chart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
        chart.getXAxis().setTextSize(textSize);
        chart.getAxisLeft().setTextSize(textSize);
        chart.setExtraBottomOffset(10f);
    
        chart.getAxisRight().setEnabled(false);
        Description desc = new Description();
        desc.setText("");
        chart.setDescription(desc);
        chart.getLegend().setEnabled(false);
        chart.getXAxis().setDrawGridLines(false);
        chart.getAxisLeft().setDrawGridLines(false);
    
        chart.invalidate();
    }
    
    public class MyBarDataset extends BarDataSet{
    
        private List<Float> credits;
    
        MyBarDataset(List<BarEntry> yVals, String label, List<Float> credits) {
            super(yVals, label);
            this.credits = credits;
        }
    
        @Override
        public int getColor(int index){
            float c = credits.get(index);
    
            if (c < 8){
                return mColors.get(0);
            }
            else if (c < 13) {
                return mColors.get(1);
            }
            else {
                return mColors.get(2);
            }
        }
    }
    

    编辑:关于SQL数据库的旁白-不要调用queryXData和queryYData在环里面!这将在每次循环迭代中提取整个数据数组,然后在循环本身内部提取(非常昂贵)。用这样的方法代替:

    ArrayList<BarEntry> yVals = new ArrayList<>();
    ArrayList<Integer> yData = myhelper.queryYdata();
    for (int i=0; i<yData.size(); i++){
        yVals.add(new BarEntry(i,yData.get(i)));
    }
    
    ArrayList<String> xData = myhelper.queryXdata();