游标movetofirst()和空指针异常

amb*_*bit 2 android android-cursor

我正在使用Cursor来获取存储在SQLite数据库中的一些数据。当我Cursor从数据库中获取一些数据时,代码可以正常工作。但是当Cursor不包含任何数据时,我得到了NullPointerExceptionat cursor.movetofirst()方法。我在其他地方使用过类似的代码,但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;
    }
Run Code Online (Sandbox Code Playgroud)

Nir*_*tel 6

使用前请务必检查getCount

if(mCurSugCnt!=null && mCurSugCnt.getCount()>0 )
{
 mCurSugCnt.moveToFirst();
}
Run Code Online (Sandbox Code Playgroud)

  • @PareshMayani我敢肯定,如果没有数据,那么光标没有任何行,但它不是null (2认同)