从数据库获取Shop时遇到问题:
Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
getShop函数
Shop getShop(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_SHOPS, new String[] { KEY_ID,
KEY_SHOP }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Shop shop = new Shop(Integer.parseInt(cursor.getString(0)), cursor.getString(1)); //first problem place
return shop;
}
和MainClass中的部分程序:
public void AddToList(View view)
{
EditText search = (EditText)findViewById(R.id.editTextsearch);
String SearchProduct = search.getText().toString();
int l = 0;
int p = 0;
ShopHandler sh = new ShopHandler(this);
String[] Shops = new String[sh.getShopCount()];
float[] prices = new float[sh.getShopCount()];
for(int i=0;i<=sh.getShopCount();i++)
{
Shop shop = sh.getShop(i); //hear is second problemplace
ShopName = shop.getShop();
ProductHandler ph = new ProductHandler(this);
for(int j=0;j<ph.getProductsCount();j++)
{
if(ph.getProduct(j).getName()==SearchProduct)
{
Shops[++l]=ShopName;
prices[++p]=ph.getProduct(j).price;
}
}
}
答案 0 :(得分:2)
光标为空。在访问行数据之前检查moveTo...()
返回值:
Shop shop = null;
if (cursor.moveToFirst()) {
shop = new Shop(Integer.parseInt(cursor.getString(0)), cursor.getString(1)); //first problem place
}
cursor.close();
return shop;
这会导致异常。为什么光标是空的可能是因为这里的一个一个:
for(int i=0;i<=sh.getShopCount();i++)
从1开始计数或将<=
更改为<
,具体取决于您的数据。
答案 1 :(得分:1)
这很可能就是问题所在:
for(int i=0;i<=sh.getShopCount();i++)
应为for(int i=0;i < sh.getShopCount();i++)
如果你让第一个循环停在sh.getShopCount()