2012-12-27 112 views
0

正如標題所示,當我嘗試從數據庫獲取列表時,出現NullPointerException。下面是代碼:調用數據庫時出現NullPointerException

public List<String> getAllRockBands() { 
    List<String> bandList = new ArrayList<String>(); 

    String selection = BAND_GENRE + "=1"; 

    SQLiteDatabase db = sqLiteHelper.getReadableDatabase(); 
    Cursor cursor = db.query(BANDDATABASE_TABLE,new String[]{BAND_NAME}, selection, null, null, null, BAND_NAME); 

    int index = cursor.getColumnIndex(BAND_NAME); 

    if (cursor.moveToFirst()) { 
     do { 
      String bandName = cursor.getString(index); 
      bandList.add(bandName); 
     } while (cursor.moveToNext()); 
    } 

    return bandList; 
} 

`

public class RockAllFragment extends SherlockListFragment { 

    private BandDatabaseAdapter mySQLiteAdapter; 
    private List<String> bandList = mySQLiteAdapter.getAllRockBands(); 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 

    return inflater.inflate(R.layout.my_list, null); 
    } 

    @Override 
    public void onViewCreated(View view, Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onViewCreated(view, savedInstanceState); 

    setListAdapter(new ArrayAdapter<String>(getSherlockActivity(), android.R.layout.simple_list_item_multiple_choice, android.R.id.text1, bandList)); 
    } 
} 

我仍然在學習代碼在這樣的環境中,所以我想這只是一些初學者的錯誤?

編輯:(這是一個有點多,但你問)

public class BandDatabaseAdapter { 

private static final String TAG = "BandDatabase"; 

private static final String BANDDATABASE_NAME = "BAND_DATABASE"; 
private static final String BANDDATABASE_TABLE = "BAND_TABLE"; 
private static final int BANDDATABASE_VERSION = 1; 
public static final String BAND_NAME = "name"; 
public static final String BAND_GENRE = "genre"; 
public static final String BAND_POPULAR = "popular"; 
public static final String BAND_SELECTED = "selected"; 

private static final String BANDDATABASE_CREATE="CREATE TABLE IF NOT EXISTS " + BANDDATABASE_TABLE 
+ " (_id integer primary key autoincrement, " + BAND_NAME 
+ " TEXT NOT NULL, " + BAND_GENRE + " TEXT NOT NULL, " + BAND_POPULAR 
+ " TEXT NOT NULL, " + BAND_SELECTED + " TEXT NOT NULL)"; 

private SQLiteHelper sqLiteHelper; 
private SQLiteDatabase sqLiteDatabase; 
private final Context context; 

public BandDatabaseAdapter(Context c) { 
     sqLiteHelper = new SQLiteHelper(c, BANDDATABASE_NAME, null, BANDDATABASE_VERSION); 
     context = c; 
    } 

public BandDatabaseAdapter openToRead() throws android.database.SQLException { 
    sqLiteDatabase = sqLiteHelper.getReadableDatabase(); 
    return this; 
} 

public BandDatabaseAdapter openToWrite() throws android.database.SQLException { 
    sqLiteDatabase = sqLiteHelper.getWritableDatabase(); 
    return this; 
} 

public void close(){ 
    sqLiteHelper.close(); 
} 

public void updateBand(String name, String selected) { 
    ContentValues contentValues = new ContentValues(); 
    contentValues.put(BAND_SELECTED, selected); 
    sqLiteDatabase.update(BANDDATABASE_TABLE, contentValues, "BAND_NAME=" + name, null); 
    close(); 
} 

public List<String> getAllRockBands() { 
    List<String> bandList = new ArrayList<String>(); 

    String selection = BAND_GENRE + "=1"; 

    SQLiteDatabase db = sqLiteHelper.getReadableDatabase(); 
    Cursor cursor = db.query(BANDDATABASE_TABLE,new String[]{BAND_NAME}, selection, null, null, null, BAND_NAME); 

    if(cursor!=null) 
    { 
    int index = cursor.getColumnIndex(BAND_NAME); 

    if (cursor.moveToFirst()) { 
     do { 
      String bandName = cursor.getString(index); 
      bandList.add(bandName); 
     } while (cursor.moveToNext()); 
    } 
    } 
    return bandList; 
} 

public List<String> getMyList() { 
    List<String> myList = new ArrayList<String>(); 

    String selection = BAND_SELECTED + "=1"; 

    SQLiteDatabase db = sqLiteHelper.getReadableDatabase(); 
    Cursor cursor = db.query(BANDDATABASE_TABLE,new String[]{BAND_NAME}, selection, null, null, null, BAND_NAME); 

    int index = cursor.getColumnIndex(BAND_NAME); 

    if (cursor.moveToFirst()) { 
     do { 
      String bandName = cursor.getString(index); 
      myList.add(bandName); 
     } while (cursor.moveToNext()); 
    } 

    return myList; 
} 

public class SQLiteHelper extends SQLiteOpenHelper { 

    public SQLiteHelper(Context context, String name, 
    CursorFactory factory, int version) { 
    super(context, name, factory, version); 
    } 

    private boolean doesDatabaseExist(Context context, String dbName) { 
     File dbFile=context.getDatabasePath(dbName); 
     return dbFile.exists(); 
    } 

    @Override 
    public void onCreate(SQLiteDatabase db) { 
    // TODO Auto-generated method stub 
    if(!(doesDatabaseExist(context,BANDDATABASE_NAME))) 
    { 
     db.execSQL(BANDDATABASE_CREATE); 
     loadDatabase(); 
    } 
    } 

    /** 
    * Starts a thread to load the database table with bands 
    */ 
    private void loadDatabase() { 
     new Thread(new Runnable() { 
      public void run() { 
       try { 
        loadBands(); 
       } catch (IOException e) { 
        throw new RuntimeException(e); 
       } 
      } 
     }).start(); 
    } 

    //loads a database from a txt file 
    private void loadBands() throws IOException { 
     Log.d(TAG, "Loading bands..."); 
     final Resources resources = context.getResources(); 
     InputStream inputStream = resources.openRawResource(R.raw.bands); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 

     try { 
      String line; 
      while ((line = reader.readLine()) != null) { 
       String[] strings = TextUtils.split(line, "^"); 
       if (strings.length < 4) continue; 
       long id = addBand(strings[0].trim(), strings[1].trim(), strings[2].trim()); 
       if (id < 0) { 
        Log.e(TAG, "unable to add band: " + strings[0].trim()); 
       } 
      } 
     } finally { 
      reader.close(); 
     } 
     Log.d(TAG, "DONE loading words."); 
    } 

    public long addBand(String name, String genre, String popular) { 
     ContentValues initialValues = new ContentValues(); 
     initialValues.put(BAND_NAME, name); 
     initialValues.put(BAND_GENRE, genre); 
     initialValues.put(BAND_POPULAR, popular); 
     initialValues.put(BAND_SELECTED, "0"); 

     return sqLiteDatabase.insert(BANDDATABASE_TABLE, null, initialValues); 
    } 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    // TODO Auto-generated method stub 
    // Drop older table if existed 
     db.execSQL("DROP TABLE IF EXISTS " + BANDDATABASE_TABLE); 

     // Create tables again 
     onCreate(db); 
    } 

} 

} 

附加信息:有人告訴我使用SimpleCursorAdapter,但它說,它已被棄用。另外請注意,我的列表超過了15萬行,如果需要,我會大大減少。 :)

+0

你可以發佈Logcat,所以我們可以幫助你嗎? –

+0

後BandDatabaseAdapter類代碼也 –

+0

看來,這是此行中導致錯誤: '私有列表 bandList = mySQLiteAdapter.getAllRockBands();' – murtaugh

回答

1

它看起來像你有沒有打電話getAllRockBands()請檢查一次即可,否則發表您的SqliteHelper類構造函數代碼

這裏更改你的代碼檢查之前創建SqliteHelper Class對象。

public class RockAllFragment extends SherlockListFragment { 

    private BandDatabaseAdapter mySQLiteAdapter; 
    private List<String> bandList; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 

    return inflater.inflate(R.layout.my_list, null); 
    } 

    @Override 
    public void onViewCreated(View view, Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onViewCreated(view, savedInstanceState); 
    mySQLiteAdapter= new BandDatabaseAdapter(getSherlockActivity()); 
    bandList = mySQLiteAdapter.getAllRockBands(); 

    setListAdapter(new ArrayAdapter<String>(getSherlockActivity(), android.R.layout.simple_list_item_multiple_choice, android.R.id.text1, bandList)); 
    } 
} 

你得到了NullPointerException,因爲你已經聲明瞭BandDatabaseAdapter但沒有創建它的實例。你需要創建它的實例然後調用它。在上面的代碼中,我先創建了對象然後調用。希望它可以幫助你。

+0

這應該創建一個類的對象,對不對? '私人SQLiteHelper sqLiteHelper; \t private SQLiteDatabase sqLiteDatabase; \t private final Context context; \t \t 公共BandDatabaseAdapter(上下文C){ \t \t sqLiteHelper =新SQLiteHelper(C,BANDDATABASE_NAME,NULL,BANDDATABASE_VERSION); \t \t context = c; \t}' (該死的,爲什麼代碼中沒有代碼縮進?) – murtaugh

+0

btw,當幫助者創建數據庫時,它應該彈出'Log.d(TAG,「Loading bands ...」);'但是它從不出現。 – murtaugh

+0

就是這樣,數據庫不會被創建。你得到的SqliteDatabase爲null,拋出NullPointerException。如果你添加完整的代碼,那麼我可以幫你 – TNR

0

「的選擇」 參數定義:

的過濾器聲明返回哪些行,格式化爲SQL WHERE子句(不包括WHERE本身)。傳遞null將返回給定表的所有行。

做之前:

int index = cursor.getColumnIndex(BAND_NAME); 

,你應該檢查一下光標爲null。同樣的事情爲:

if (cursor.moveToFirst()) 
+0

如果您正在考慮檢查數據庫中是否沒有任何內容,則不需要它,因爲它將始終填充。 – murtaugh

+0

如果您在調用行「int index = cursor.getColumnIndex(BAND_NAME);」之前沒有檢查遊標是否爲空,並且遊標爲空,那麼您將會提到它時會出現NullPointerException。 – gezdy

+0

好吧,現在我檢查了,它仍然造成同樣的問題。 – murtaugh

相關問題