android布局index: 0, size: 0,android.database.CursorIndexOutOfBoundsException: Index 0 requested, with...

可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):

问题:

I am using custom adapter extending cursor adapter for displaying data in listview, to display particular phone number i have passed the id to a method in database class but it is showing errorandroid.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

while placing debugger in the the method it is not going after the line num = cursor.getString(cursor.getColumnIndex("ContactNumber"));

Can any one help me to solve it. This is the code: public String getNumberFromId(int id) { String num; db= this.getReadableDatabase(); Cursor cursor = db.query(scheduletable, new String[] { "ContactNumber" },"_id="+id, null, null, null, null); cursor.moveToFirst(); num = cursor.getString(cursor.getColumnIndex("ContactNumber")); cursor.close(); db.close(); return num; }

回答1:

Whenever you are dealing with Cursors, ALWAYS check for null and check for moveToFirst() without fail. if( cursor != null && cursor.moveToFirst() ){ num = cursor.getString(cursor.getColumnIndex("ContactNumber")); cursor.close(); }

Place logs appropriately to see whether it is returning null or an empty cursor. According to that check your query.

Update Put both the checks in a single statement as mentioned by Jon in the comment below.

Update 2 Put the close() call within the valid cursor scope.

回答2:

try this.. this will avoid an Exception being thrown when the cursor is empty.. if(cursor != null && cursor.moveToFirst()){ num = cursor.getString(cursor.getColumnIndex("ContactNumber")); cursor.close(); }

回答3:

First check this Condition before fetching data if(cursor!=null && cursor.getCount()>0){ cursor.moveToFirst(); num = cursor.getString(cursor.getColumnIndex("ContactNumber")); }

回答4:

Check the return value from moveToFirst(), before you try to read anything from the cursor. It looks as if no results are being returned.

回答5:

a save schema to query Cursors is // just one Cursor cursor = db.query(...); if (cursor != null) { if (cursor.moveToFirst()) { value = cursor.getSomething(); } cursor.close(); } // multiple columns Cursor cursor = db.query(...); if (cursor != null) { while (cursor.moveToNext()) { values.add(cursor.getSomething()); } cursor.close(); }

回答6:

In case people are still looking:

Instead of searching for "ContactNumber" try searching for Phone.NUMBER. The tutorial has the code with more details: http://developer.android.com/training/basics/intents/result.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值