gpt4 book ai didi

android - 光标 movetofirst() 和空指针异常

转载 作者:行者123 更新时间:2023-12-02 14:12:33 27 4
gpt4 key购买 nike

我正在使用 Cursor 来获取存储在我的 SQLite 数据库中的一些数据。当我的光标有数据库中的一些数据时,代码可以正常工作。但是,当 Cursor 不包含任何数据时,我在 Cursor.movetofirst() 方法中收到 NullPointerException 。我在其他地方使用了类似的代码,但 movetofirst() 方法在其他地方没有给出 NullPointerException 。我几天来一直在尝试这个,但我无法弄清楚问题是什么。请帮忙。

    public class Country extends Activity {

private DbAdapter mDb;
private Cursor mCurSugCnt;
String country=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.country);

mDb=new DbAdapter(this);
mDb.open();

country= this.getIntent().getExtras().getString("country");
fillSugCntData(country);

}

private void fillSugCntData(String cnt) {
//I have tried multiple methods. The problem occurs when there is no data returned by any of the methods called
//mCurSugCnt=mDb.fetchCatNotes("abc");
mCurSugCnt=mDb.fetchCntNotes(cnt);

//This is where I called the null pointer exception in case no data is returned by the cursor
mCurSugCnt.moveToFirst();

}


---------------------

public Cursor fetchCntNotes(String cnt){

int id;
Cursor appfinlist=null;
Cursor temp=mDb.query(CNT_TABLE, new String[]{KEY_ROWID}, KEY_CNTNM + "=\"" + cnt + "\"", null, null , null, null);
Cursor applist;

if(temp.moveToFirst()){
id=temp.getInt(temp.getColumnIndexOrThrow(DbAdapter.KEY_ROWID));

applist=mDb.rawQuery("SELECT appcntid FROM appcntlist WHERE cntappid = "+id, null);
if(applist.moveToFirst()){
String[] cntin=new String[applist.getCount()];
for(int i=0;i<applist.getCount();i++){
cntin[i]=""+applist.getInt(applist.getColumnIndexOrThrow(DbAdapter.KEY_APPCNTID));
Log.d("amit","countryname id cnt var: " + cntin[i]);
applist.moveToNext();
}

String query = "SELECT * FROM applist"
+ " WHERE _id IN (" + makePlaceholders(applist.getCount()) + ")";

appfinlist = mDb.rawQuery(query, cntin);
Log.d("amit","countryname id get count: " + appfinlist.getCount());
}
}
return appfinlist;
}

private String makePlaceholders(int count) {
String toRet="?";

for (int i=1;i<count;i++){
toRet=toRet + ",?";
}
return toRet;
}

最佳答案

始终检查getCount使用前。

if(mCurSugCnt!=null && mCurSugCnt.getCount()>0 )
{
mCurSugCnt.moveToFirst();
}

关于android - 光标 movetofirst() 和空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14099938/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com