3

I need to create pie chart using chartengine for my app, there I need to draw pie-chart for categories and their expenses.I need to get the categories inside pie chart, so I took categories into an arraylist from database and then I put them into an array.

Now it's giving 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);
    }



    }
3
  • 1
    category != String. Fetch the class member whose value you want in the pie chart from each element of your arraylist. Add that to the string array. If its a number append it with "". Commented Oct 29, 2015 at 16:23
  • ArrayList<category> bud = new DBhelper(this).getCategories(); String[] code = bud.toArray(new String[bud.size()]); You are trying to make an array of String out of a list of category. Commented Oct 29, 2015 at 16:24
  • please help me,how can I change my coding now Commented Oct 29, 2015 at 17:06

1 Answer 1

4

You are retrieving the list of Category object instances, but your array called code, declared as the array of String objects. The exception you get, is about the fact, that you are trying to strore Category objects in the array of strings.

Suppose, that Code is one of the fields of the Category and you've provided getter method for it, in this case you need no itarate the categories and get it's codes, adding them into the array, like:

String[] code = new String[bud.size()];
for (int i = 0; i < bud.size(); i++) {
    code[i] = bud.get(i).getCode();
}
Sign up to request clarification or add additional context in comments.

2 Comments

ll.size mean what?until the categories there I need to run the loop know,so if I put bud.size instead of ll.size is it okey?
Java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.username.weddingplanning/com.example.username.weddingplanning.pie}: java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3,I just hardcode the value for ll.size,it's giving error like this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.