java - 使用 SQLite 填充饼图

标签 java android database sqlite pie-chart

我需要使用 SQLite 数据库中的数据填充饼图,但我不知道如何执行此操作。我目前是 Android 开发的初学者。

我希望此查询成为我将放入饼图中的内容的来源:

Cursor cursor = db.rawQuery("SELECT COUNT(label), label, SUM(amount) FROM " + ItemEntry.TABLE_NAME + " GROUP BY Label ORDER BY Amount DESC;", null);

标签当然就是标签,按标签分组的值的总和将是我想要放入饼图中的金额..

问题是我不知道该怎么做/怎么做..请有人帮忙.. 顺便说一句,我正在使用 AnimatedPieView...请帮忙

这是我的图表 JAVA 代码

package com.example.admin.test2;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.ListView;
import android.widget.TextView;

import com.razerdp.widget.animatedpieview.AnimatedPieView;
import com.razerdp.widget.animatedpieview.AnimatedPieViewConfig;
import com.razerdp.widget.animatedpieview.data.IPieInfo;
import com.razerdp.widget.animatedpieview.data.SimplePieInfo;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class Charts extends Fragment {

    public SQLiteDatabase mDatabase;

    AnimatedPieView mAnimatedPieView;
    ListView itemList;
    ArrayList <ChartItems> arrayList;
    ChartItemAdapter chartItemAdapter;
    ItemDBHelper dbHelper;
    TextView expense;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_charts, container, false);

        expense = (TextView) view.findViewById(R.id.totalExpns);
        expenseSum();

        mAnimatedPieView = view.findViewById(R.id.animatedPieChart);
        drawPie();

        dbHelper = new ItemDBHelper(getActivity());

        itemList = (ListView) view.findViewById(R.id.itemListView);
        loadDataInListView();


        return view;
    }

    public void loadDataInListView() {
        arrayList = dbHelper.getChartData();
        chartItemAdapter = new ChartItemAdapter(getContext(), arrayList);
        itemList.setAdapter(chartItemAdapter);
        chartItemAdapter.notifyDataSetChanged();
        Helper.getListViewSize(itemList);

    }

    public void expenseSum() {

        ItemDBHelper dbHelper = new ItemDBHelper(getActivity());
        mDatabase = dbHelper.getWritableDatabase();
        Cursor cur = mDatabase.rawQuery("SELECT SUM(" + ItemContract.ItemEntry.COLUMN_AMOUNT + ") as Total FROM " + ItemContract.ItemEntry.TABLE_NAME
                , null);

        if (cur.moveToFirst()) {

            int total = cur.getInt(cur.getColumnIndex("Total"));// get final total
        }

        int total = cur.getInt(cur.getColumnIndex("Total"));
        expense.setText("-₱ " + total);
    }

    public void drawPie() {

        AnimatedPieViewConfig config = new AnimatedPieViewConfig();
        config.startAngle(-90)// Starting angle offset
                .addData(new SimplePieInfo(30, Color.parseColor("#77dd77"), "Sample lang"))//Data (bean that implements the IPieInfo interface)
                .addData(new SimplePieInfo(18.0f, Color.parseColor("#ff6961"), "Sample ulet"))
                .duration(3000);// draw pie animation duration
        config.floatShadowRadius(18f);
        config.floatUpDuration(500);
        config.interpolator(new DecelerateInterpolator(4f));

// The following two sentences can be replace directly 'mAnimatedPieView.start (config); '
        mAnimatedPieView.applyConfig(config);
        mAnimatedPieView.start();
    }

}

图表的 XML 文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f6f6f6"
    tools:context=".Charts">

    <View
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:background="@color/pastelPink"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView18"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginTop="3dp"
        android:layout_marginBottom="3dp"
        android:fontFamily="@font/montserrat"
        android:text="Distribution Chart"
        android:textColor="#fefefe"
        android:textSize="25dp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="@+id/view"
        app:layout_constraintEnd_toEndOf="@+id/view"
        app:layout_constraintStart_toStartOf="@+id/view"
        app:layout_constraintTop_toTopOf="@+id/view" />

    <ScrollView
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <View

                android:id="@+id/view9"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="8dp"
                android:background="@drawable/sections"
                app:layout_constraintBottom_toBottomOf="@+id/itemListView"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/textView6"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:fontFamily="@font/montserrat"
                android:text="Total Expenses"
                android:textSize="13dp"
                app:layout_constraintEnd_toEndOf="@+id/view9"
                app:layout_constraintStart_toStartOf="@+id/view9"
                app:layout_constraintTop_toTopOf="@+id/view9" />

            <TextView
                android:id="@+id/totalExpns"
                android:layout_width="250dp"
                android:layout_height="28dp"
                android:layout_marginStart="8dp"
                android:layout_marginEnd="8dp"
                android:autoSizeTextType="uniform"
                android:fontFamily="@font/montserrat"
                android:text="₱ 0"
                android:textAlignment="center"
                android:textColor="@color/pastelRed"
                android:textSize="18dp"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="@+id/view9"
                app:layout_constraintStart_toStartOf="@+id/view9"
                app:layout_constraintTop_toBottomOf="@+id/textView6" />

            <com.razerdp.widget.animatedpieview.AnimatedPieView
                android:id="@+id/animatedPieChart"
                android:layout_width="0dp"
                android:layout_height="300dp"
                android:layout_marginStart="8dp"
                android:layout_marginEnd="8dp"
                app:layout_constraintEnd_toEndOf="@+id/view9"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintStart_toStartOf="@+id/view9"
                app:layout_constraintTop_toBottomOf="@+id/totalExpns" />

            <ListView
                android:id="@+id/itemListView"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginBottom="60dp"
                android:background="@android:color/transparent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="@+id/view9"
                app:layout_constraintStart_toStartOf="@+id/view9"
                app:layout_constraintTop_toBottomOf="@+id/animatedPieChart" />

        </android.support.constraint.ConstraintLayout>


    </ScrollView>

</android.support.constraint.ConstraintLayout>

我的 DBHELPER:使用我用于填充图表布局中的 ListView 的代码。

package com.example.admin.test2;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.admin.test2.ItemContract.*;

import java.util.ArrayList;


public class ItemDBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "itemlist.db";
    public static final int DATABASE_VERSION = 4;

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        final String SQL_CREATE_ITEMLIST_TABLE = "CREATE TABLE " + ItemEntry.TABLE_NAME + " (" +
                ItemEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                ItemEntry.COLUMN_LABEL + " TEXT NOT NULL, " +
                ItemEntry.COLUMN_DETAIL + " TEXT, " +
                ItemEntry.COLUMN_AMOUNT + " INTEGER NOT NULL, " +
                ItemEntry.COLUMN_DATE + " TEXT " +
                ");";

        db.execSQL(SQL_CREATE_ITEMLIST_TABLE);
    }

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

    public ArrayList<ChartItems> getChartData() {
        ArrayList<ChartItems> arrayList = new ArrayList <>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT COUNT(label), label, SUM(amount) FROM " + ItemEntry.TABLE_NAME +
                " GROUP BY Label ORDER BY Amount DESC;", null);

        while (cursor.moveToNext()) {
            String label = cursor.getString(1);
            double amount = cursor.getDouble(2);
            int count = cursor.getInt(0);
            ChartItems chartItems = new ChartItems(count,label,amount);

            arrayList.add(chartItems);
        }
        return arrayList;
    }
}

最佳答案

从Sqlite获取数据后,调用drawPie()函数,而不是在onCreate()方法中调用

 fun drawPie() {

    val config = AnimatedPieViewConfig()

    for(chartItem in arrayList){     // arrayList -> List from sqlite
        config.addData( SimplePieInfo(
            chartItem.count,
            Color.parseColor("//colour you wish"),
            chartItem.label
        ))
    }

    config.startAngle(-90f)// Starting angle offset
        .duration(2000)// draw pie animation duration
    config.floatShadowRadius(18f)
    config.floatUpDuration(500)
    config.interpolator(DecelerateInterpolator(4f))
    config.drawText(true)
    config.textSize(36f)

    // The following two sentences can be replace directly 
    mAnimatedPieView.start (config)
    mAnimatedPieView.applyConfig(config)
    mAnimatedPieView.start()
}

关于java - 使用 SQLite 填充饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54884436/

相关文章:

java - 将第二个 Fragment 添加到 ActionBarActivity 时出现 "Duplicate id, tag null, or parent id 0x0 with another fragment"

android - surfaceChanged() 中的运行时异常 startPreview 失败 1

sql-server - 从 ntext 转移到 nvarchar(max) 有什么问题吗

java - android 中的 BasicAuthentication for webview 不起作用

android - JSON 字符串数组(无对象),提取数据

database - 水平数据库和垂直数据库

mysql - 在 mySQL 中获取 CSV 值

java - 删除 weka 实例的特定属性(列)

java - Eclipse 新文件夹需要父文件夹

java - 从独立程序连接 IBM MQ |错误 : ('MQRC_NOT_AUTHORIZED' )