samedi 2 janvier 2016

Multiple sql and cursor to the same Android Sqlite database

This is the original code which has only one sql and cursor. I would like to add second sql2 and cursor2 but I faced difficulty.

public List<Bean> getWords(String englishWord) {
        if(englishWord.equals(""))
            return new ArrayList<Bean>();

        String sql = "SELECT * FROM " + TABLE_NAME +
                " WHERE " + ENGLISH + " LIKE ? ORDER BY LENGTH(" + ENGLISH + ") LIMIT 100";

//I added sql2 here
        String sql2 = "SELECT * FROM " + TABLE_NAME +
                " WHERE " + ENGLISH + " LIKE ? ORDER BY " + ENGLISH + " LIMIT 100";

        SQLiteDatabase db = initializer.getReadableDatabase();

        Cursor cursor = null;
        try {
            cursor = db.rawQuery(sql, new String[]{"%" + englishWord + "%"});

            List<Bean> wordList = new ArrayList<Bean>();
            while(cursor.moveToNext()) {
                int id = cursor.getInt(0);
                String english = cursor.getString(1);
                String bangla = cursor.getString(2);
                String status = cursor.getString(3);
                wordList.add(new Bean(id, english, bangla, status));
            }

            return wordList;
        } catch (SQLiteException exception) {
            exception.printStackTrace();
            return null;
        } finally {
            if (cursor != null)
                cursor.close();
        }

//I added cursor2 here    
        Cursor cursor2 = null;
        try {
            cursor2 = db.rawQuery(sql2, new String[]{englishWord + "%"});

            List<Bean> wordList = new ArrayList<Bean>();
            while(cursor2.moveToNext()) {
                int id = cursor2.getInt(0);
                String english = cursor2.getString(1);
                String bangla = cursor2.getString(2);
                String status = cursor2.getString(3);
                wordList.add(new Bean(id, english, bangla, status));
            }

            return wordList;
        } catch (SQLiteException exception) {
            exception.printStackTrace();
            return null;
        } finally {
            if (cursor2 != null)
                cursor2.close();
        }
    }

I got unreachable statement error in Cursor cursor2 = null;. What should be the correct code?

Aucun commentaire:

Enregistrer un commentaire