当前位置: 首页 > 知识库问答 >
问题:

将arraylist存储到数组中时出现异常

范楚
2023-03-14

我需要使用chartengine为我的应用程序创建饼图,在那里我需要为类别及其费用绘制饼图。我需要在饼图中获得类别,所以我从数据库中将类别放入arraylist中,然后将它们放入数组中。

现在它给出了例外。

10-29 21:41:22.720 878-878/com.example.username.weddingplanning e/AndroidRuntime:致命异常:main java.lang.runtimeException:无法启动活动ComponentInfo{com.example.username.weddingPlanning/com.example.username.weddingPlanning.pie}:java.lang.ArrayStoreException:com.example.username.weddingPlanning.Category类型的源[0]不能存储在.java:2304)在Android.app.activityThread.Access$700(activityThread.java:152),Android.app.activityThread.h.h.h.handleMessage(activityThread.java:1284),Android.os.handler.dispatchMessage(handler.java:99),Android.os.handler.dispatchMessage(handler.java:176),Android.app.activityThread.maingoteinit$methodandargscaller.run(zygoteinit.java:1102)在com.android.internal.os.zygoteinit.main(zygoteinit.java:869)在dalvik.system.nativestart.main(原生方法)在dalvik.system.nativestart.main(原生方法)由:java.lang.arraystoreException:com.example.username.weddingplanning.category引起:com.example.username.weddingplanning.category.app.activity.performcreate(activity.java:5326)在Android.app.instrumentation.callactivityoncreate(instrumentation.java:1097)在Android.app.activitythread.performlaunchactivity(activitythread.java:2213)在Android.app.activitythread.performlaunchactivity(activitythread.java:2213)              在Android.app.activitythread.handlelaunchactivity2)             在Android.app.activitythread$H.handlemessage(activitythread.java:1284)           在Android.os.handler.dispatchmessage(handler.java:99)            在Android.os.looper.loop(looper.java:176)           在Android.app.activitythread.main(activitythread.java:5299),          在 · 在java.lang.reflect.Method.invoke(Method.java:511) · · · · · · · · · · · 在com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:1102) · · · · · · · 和NBSp;在com.android.internal.os.zygoteinit.main(zygoteinit.java:869) · · · · · · · · · · · 在dalvik.system.nativeStart.main(原生方法)

这是我的DBhelper类

public class DBhelper extends SQLiteOpenHelper {

    static final String DATABASE = "wedding9.db";
    static final int VERSION = 9;
    static final String TABLE1 = "Category";
    static final String TABLE2 = "Budget";
    static final String TABLE3 = "Expenses";

    static final String C_ID = "_id";
    static final String Name = "name";
    static final String B_ID = "_id";
    static final String Description = "description";
    static final String Amount = "amount";

    public static final String ID1 = "_id";
    public static final String DATE_T1 = "date1";
    public static final String CATEGORY = "category";
    public static final String DETAIL = "detail";
    public static final String AMOUNT1 = "amount1";
    public static final String STATUS = "status";
    public static final String EX_YEAR = "exyear";
    public static final String EX_MONTH = "exmonth";

    public DBhelper(Context context) {
        super(context, DATABASE, null, VERSION);
    }

    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE " + TABLE1 + "(" + C_ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT," + Name + " text unique not null)");

        db.execSQL("CREATE TABLE " + TABLE2 + "(" + B_ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT," + Description + " text,"
                + Amount + " text, FOREIGN KEY (" + Description + ") REFERENCES " + TABLE1 + "(" + Name + "));");

        db.execSQL("CREATE TABLE " + TABLE3 + " ( "
                + ID1 + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + DATE_T1 + " text, "
                + CATEGORY + " text, "
                + DETAIL + " text, "
                + STATUS + " text, "
                + EX_YEAR + " text, "
                + EX_MONTH + " text, "
                + AMOUNT1 + " text, FOREIGN KEY (" + CATEGORY + ") REFERENCES " + TABLE1 + "(" + Name + "));");


    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("drop table " + TABLE1);
        onCreate(db);
    }


    public ArrayList<category> getCategories() {
        ArrayList<category> arrayList = new ArrayList<category>();
        SQLiteDatabase db = getReadableDatabase();
        Cursor c = db.query(DBhelper.TABLE1, null, null, null, null, null, null);
        while (c.moveToNext()) {
            category cat = new category(c.getInt(0), c.getString(1));
            arrayList.add(cat);

        }

        return arrayList;
    }

    public boolean checkIdExist(String name) {
        SQLiteDatabase db = getReadableDatabase();
        Cursor c = db.query(DBhelper.TABLE1, null, null, null, null, null, null);
        while (c.moveToNext()) {
            if (c.getString(1).equals(name))
                return false;
        }

        return true;
    }

    public double getTotalbudget() {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT SUM(Amount) FROM " + TABLE2;

        Cursor c = db.rawQuery(query, null);
        //Add in the movetofirst etc here? see SO
        c.moveToFirst();
        double i = 0;
        i = c.getDouble(0);

        return i;
    }

    public double getTotalexpenses() {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT SUM(AMOUNT1) FROM " + TABLE3;

        Cursor c = db.rawQuery(query, null);
        c.moveToFirst();
        double e = 0;
        e = c.getDouble(0);

        return e;
    }


    public boolean checkBudget(String cat) {
        SQLiteDatabase db = this.getReadableDatabase();
        String query = "SELECT e.category " +
                "FROM expenses e, budget b " +
                "WHERE e.category=b.description and e.category='" + cat +
                "' GROUP BY e.category " +
                "HAVING sum(amount1)>b.amount";

//        ArrayList<String> results = new ArrayList<String>();
        Cursor c = db.rawQuery(query, null);
        if (c.moveToNext()) {
            return true;
            //results.add(c.getString(0));
        }

        return false;
    }

    //get the category expenses
    public ArrayList<Expence> getCategoryExpences(String category) {
        ArrayList<Expence> expences = new ArrayList<Expence>();

        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int tmonth = c.get(Calendar.MONTH);
        int month = tmonth + 1;

        String query = "SELECT * FROM " + TABLE3 + " WHERE " + EX_YEAR + "='" + year + "' and " + EX_MONTH + "='" + month + "' and " + CATEGORY + "='" + category + "'";

        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.rawQuery(query, null);
        if (cursor.moveToFirst()) {
            do {
                Expence ex = new Expence();
                ex.setCategory(category);
                ex.setDate(cursor.getString(1));
                ex.setDescription(cursor.getString(3));
                ex.setStatus(cursor.getString(4));
                ex.setYear(cursor.getString(5));
                ex.setMonth(cursor.getString(6));
                ex.setAmount(cursor.getString(7));
                expences.add(ex);
            }
            while (cursor.moveToNext());
        } else {
            return null;
        }
        return expences;
    }


}

这是我的饼图类

public class pie extends ActionBarActivity {


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pie);



        // Pie Chart Section Names


        ArrayList<category> bud = new DBhelper(this).getCategories();
        String[] code = bud.toArray(new String[bud.size()]);
        // Pie Chart Section Value
        double[] distribution = new double[code.length];
        for (int i=0; i<distribution.length; i++) {
            System.out.println(i);
            ArrayList<Expence> expences = new DBhelper(this).getCategoryExpences(code[i]);
            if(expences!=null){
                double total = 0.0;
                for (Expence ex : expences) {
                    total = total + Double.parseDouble(ex.getAmount());
                }
                distribution[i]=total;
            }
            else{
                distribution[i]=0.0;
            }
        }


        // Color of each Pie Chart Sections
        int[] colors = { Color.BLUE, Color.MAGENTA, Color.GREEN, Color.CYAN,Color.YELLOW,
                Color.RED };

        // Instantiating CategorySeries to plot Pie Chart
        CategorySeries distributionSeries = new CategorySeries("Expenses Graph");
        for (int i = 0; i < distribution.length; i++) {
            // Adding a slice with its values and name to the Pie Chart
            distributionSeries.add(code[i], distribution[i]);
        }

        // Instantiating a renderer for the Pie Chart
        DefaultRenderer defaultRenderer = new DefaultRenderer();
        for (int i = 0; i < distribution.length; i++) {
            SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
            seriesRenderer.setColor(colors[i]);
            seriesRenderer.setDisplayChartValues(true);
            // Adding a renderer for a slice
            defaultRenderer.addSeriesRenderer(seriesRenderer);
        }

        defaultRenderer.setChartTitle("Expenses Graph");
        defaultRenderer.setChartTitleTextSize(60);
        defaultRenderer.setLabelsTextSize(30);
        defaultRenderer.setLegendTextSize(30);
        defaultRenderer.setShowLegend(true);
        //defaultRenderer.setDisplayValues(true);
        defaultRenderer.setApplyBackgroundColor(true);
        defaultRenderer.setBackgroundColor(Color.BLACK);
        defaultRenderer.setLabelsColor(Color.WHITE);
        defaultRenderer.setZoomButtonsVisible(true);


        // Creating an intent to plot bar chart using dataset and multipleRenderer
        Intent intent = ChartFactory.getPieChartIntent(getBaseContext(), distributionSeries, defaultRenderer, "AChartEnginePieChartDemo");

        // Start Activity
        startActivity(intent);
    }



    }

共有1个答案

万高洁
2023-03-14

您正在检索category对象实例列表,但您的数组名为code,声明为string对象数组。您得到的异常是关于这样一个事实,即您试图在字符串数组中strorecategory对象。

假设codecategory的一个字段,并且您已经为它提供了getter方法,在这种情况下,您不需要对categories进行itarate并获取它的代码,将它们添加到数组中,例如:

String[] code = new String[bud.size()];
for (int i = 0; i < bud.size(); i++) {
    code[i] = bud.get(i).getCode();
}
 类似资料:
  • 问题内容: 如何将arrayList存储到Java中的数组中? 问题答案: 那取决于你想要什么: 现在,如果要将列表存储在数组中,则可以执行以下操作之一: 但是,如果要将列表 项 放在数组中,请执行以下一项操作: 参考:

  • 我正在尝试将一个图像存储到FireBase数据库中,我很确定所有的代码都可以很好地获取imagelink,因为它不再像以前那样显示错误。然而现在,当我上传图片时,出现了一个新问题。这与存储异常有关,我猜它在实际从存储中提取imagelink并将其插入数据库时遇到了问题。下面是我认为出现问题的代码: 如果需要,这是我的整个代码: } 错误消息: 2020-06-02 13:54:22.594 346

  • 我已经声明了数组列表,并在servlet中填充了它,我已经在servlet中打印了它,它运行得很好,但是当我转发到JSP时,我得到了下一个空指针异常: java.lang.NullPointerException: 无法调用 “java.util.ArrayList.iterator()” 因为 “miArray2” 为 null -Servlet代码: 索引.jsp代码:

  • 问题内容: 有没有一种方法可以将数组存储到mysql字段中?我正在创建一个评论评分系统,因此我想存储用户ID数组以防止进行多次投票。我将创建一个新表,其中包含评论ID和对此评论进行投票的用户ID数组。然后,我将加入评论表和该表,并检查当前用户ID是否存在于选民数组或注释中。如果是这样,将禁用投票图标。我想我会避免以这种方式在循环中使用mysql查询。 您碰巧知道更好的方法吗? 问题答案: 您始终可

  • 问题内容: 我知道这应该是简单的,我可能正直盯着问题,但我再次陷入困境,需要代码专家的帮助。 我试图从jdbc的一列中取出一行,并将它们放入数组中。 我这样做如下: creatConnection是已经定义的方法,可以执行其明显的工作。我在创建另一个结果集的同时创建了我的结果集,我将该列的字符串存储到一个数组中。然后打印出来以备不时之需。还要确保它在那里。 问题在于其将整个列存储到contactL