我使用的是Cursor
獲取存儲在我的SQLite
數據庫中的一些數據。當我的Cursor
有一些來自數據庫的數據時,代碼工作正常。但是當Cursor
不包含任何數據時,我得到一個NullPointerException
在cursor.movetofirst()
方法。我在其他地方使用了類似的代碼,但movetofirst()
方法在其他地方沒有給出NullPointerException
。自從幾天後我正在嘗試此操作,但無法找出問題所在。請幫助。光標movetofirst()空指針異常
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;
}
那麼你的問題是什麼? –
我不知道爲什麼我得到一個空指針異常。我想避免發生這種異常。 – ambit
檢查當你的查詢沒有找到任何行時,'fetchCntNotes()'返回什麼?,如果查詢觸發錯誤或沒有數據顯示,似乎你返回'null'。 –