4

私は次の2つの方法があります

方法1

public String[] getSongIds(String whereClause) 
    {
        String countQuery = "SELECT  songid FROM TABLE_INDEX WHERE " + whereClause;
        Cursor cursor = db.rawQuery(countQuery, null);
        int cursorSize = cursor.getCount();

        int[] songIds = new int[cursorSize];
        int count=0;
        if (cursor != null ) {
            if (cursor.moveToFirst()){
                   do{
                       songIds[count] = cursor.getInt(cursor.getColumnIndex("songid"));
                      count++;
                   }while(cursor.moveToNext());
                }
        }
        cursor.close();
        db.close();
        return getSongTitles(songIds);
    }

方法2

private String[] getSongTitles(int[] songIds) {

    /some algorithm
    return songTitles;

}

メソッド1は別のパッケージから呼び出されます。方法1は、SQLiteデータベースに対してクエリを実行し、2番目のメソッドを呼び出します。メソッド1でSQLiteクエリを実行することでよく発生する例外をキャッチする必要があります。できれば、これらのメソッドが最初に呼び出されたパッケージからユーザーにメッセージを表示できるように、(-1)などを返します。したがって、(間違った入力の)SQL例外が発生した場合にメソッド1がメソッド2を呼び出さないようにし、代わりに他のパッケージに何かを返します。

psこの例外をキャッチする方法をいくつか見ましたが、それらのアプローチに満足していませんでした。これに対処するための最良の方法を知りたい。乾杯

4

1 に答える 1

3

例外をキャッチし、カスタムでラップして、スローします。

public String[] getSongIds(String whereClause) throws FetchSongException {
  String countQuery = "SELECT  songid FROM TABLE_INDEX WHERE " + whereClause;
  try {
    Cursor cursor = db.rawQuery(countQuery, null);
    int cursorSize = cursor.getCount();

    int[] songIds = new int[cursorSize];
    int count=0;
    if (cursor != null) {
      if (cursor.moveToFirst()) {
        do {
          songIds[count] = cursor.getInt(cursor.getColumnIndex("songid"));
          count++;
        } while(cursor.moveToNext());
      }
      cursor.close(); // you should put this in a finally block
      db.close();
      return getSongTitles(songIds);
    }
  } catch (SQLException sqle) {
    throw new FetchSongException("Unable to fetch song ids.", sqle);
  }
}

次に、呼び出す人は誰でもgetSongIdsこの新しい例外をキャッチする必要があります。

try {
  String[] result = getSongsIds("something");
} catch (FetchSongException e) {
  // Display user message with e.getMessage();
}
于 2012-08-25T02:41:03.840 に答える