Java – An exception occurred while storing arraylist into an array

An exception occurred while storing arraylist into an array… here is a solution to the problem.

An exception occurred while storing arraylist into an array

I need to

use ChartEngine to create a pie chart for my application, and I need to draw a pie chart for categories and their costs. I need to get the categories in a pie chart, so I put the categories into an array list from the database, and then I put them into an array.

Now it gives an exception.

10-29 21:41:22.720 878-878/com.example.username.weddingplanning
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.username.weddingplanning/com.example.username.weddingplanning.pie}:
java.lang.ArrayStoreException: source[0] of type
com.example.username.weddingplanning.category cannot be stored in
destination array of type java.lang.String[]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2250)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2304)
at android.app.ActivityThread.access$700(ActivityThread.java:152)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ArrayStoreException: source[0] of type com.example.username.weddingplanning.category cannot be stored in
destination array of type java.lang.String[]
at java.lang.System.arraycopy(Native Method)
at java.util.ArrayList.toArray(ArrayList.java:519)
at com.example.username.weddingplanning.pie.onCreate(pie.java:33)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2213)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2304)
            at android.app.ActivityThread.access$700(ActivityThread.java:152)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
            at dalvik.system.NativeStart.main(Native Method)

This is my DBhelper class

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;
    }

}

This is my pie chart class

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);
    }

}

Solution

You are retrieving a list of instances of the Category object, but your array named code is declared as an array of String objects. The exception you get is about the fact that you tried to store a Category object in an array of strings.

Suppose Code is one of the fields of Category, and you have provided a getter method for it, in which case you don’t need to iterate over the category and get it to code, add them to the array, for example:

String[] code = new String[bud.size()];
for (int i = 0; i < bud.size(); i++) {
    code[i] = bud.get(i).getCode();
}

Related Problems and Solutions