Application crashes while reading an empty table in android

只愿长相守 提交于 2019-12-13 08:34:23

问题


The issue is purely with the contents inside the tables. If the table is not empty (with one or more records), application works perfectly. I am deleting the contents of table and immediately after that reading the same table, it throws exception and app force closes.

I tried searching for it but couldn't conclude. The key point is : index out of bound exception which is thrown at movetofirst() method of cursor when i am going to read the table, i suppose... Please help.

public List<TableData> readForPaymentDetais()
    {
        List<TableData> paymentDetails = new ArrayList<TableData>();
        try
        {
            String selectQuery = "select * from PaymentDetails";
            SQLiteDatabase database = this.getWritableDatabase();
            Cursor cursor = database.rawQuery(selectQuery, null);
            if(cursor.getCount() !=0)
            {
                if(cursor.moveToFirst())
                {
                    do
                    {
                        TableData data = new TableData();
                        data.setPaymentMade(Float.valueOf(cursor.getString(0).toString()));
                        data.setDateOfPayment(cursor.getString(1));

                        paymentDetails.add(data);               
                    }
                    while(cursor.moveToNext());
                }               
            }

            return paymentDetails;
        }
        catch(Exception exc)
        {
            return null;
        }       
    }

回答1:


Before executing moveToFirst method of cursor please check whether cursor is empty. For that you can use code like:

if (mCursor.getCount() == 0) {
    // cursor is empty
}

If cursor is not empty put your stuff in else part.



来源:https://stackoverflow.com/questions/30011426/application-crashes-while-reading-an-empty-table-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!