在textView中仅显示SQLite数据库中的相关信息

问题描述 投票:0回答:3

我已经设置了一个简单的主题信息表,其中包含3列:id(自动增量),主题和级别。级别范围介于1和3之间。如果在某个活动中我想在单独的textViews中显示级别2的所有主题,我将如何实现此操作?

下面是我的数据库活动代码:

public class DatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "NCEA_app";
private static final int DATABASE_VERSION = 1;



//table
public static final String TABLE_NAME = "subject_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "SUBJECT";
public static final String COL_3 = "LEVEL";

public static final String CREATE_TABLE = "create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,SUBJECT TEXT,LEVEL INTEGER)";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);
}

public boolean insertSubject(String subject,String level) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_2,subject);
    contentValues.put(COL_3,level);
    long result = db.insert(TABLE_NAME,null ,contentValues);
    if(result == -1)
        return false;
    else
        return true;
}

public Cursor getAllData() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
    return res;
}
}

我想我需要循环遍历整个数据库并找到具有正确级别的每个主题,但我是SQL新手,不知道如何完成。

android sqlite android-sqlite
3个回答
1
投票

您可以创建这样的方法,以便从DatabaseHelper类中的数据库中获取主题数据

public Cursor getSubjectDataForParticularLevel(int level){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT SUBJECT"+TABLE_NAME+" WHERE COL_3 = "+level, null);
        return cursor;
    }

你可以像这样在Activity中获取你的数据

 DatabaseHelper mDatabaseHelper = DatabaseHelper(this);
    ArrayList<String> subjectList = new ArrayList<String>();
    Cursor cursor = mDatabaseHelper.getSubjectDataForParticularLevel(2); 
    if (cursor.moveToFirst()) {
      do{
        //your Subject list
        subjectList.add(cursor.getString(cursor.getColumnIndex("SUBJECT")));
        } while (cursor.moveToNext());
    }

1
投票

你只需要使用以下内容获得级别的结果:

public Cursor getLevel2Data(int level) {
         SQLiteDatabase db = this.getWritableDatabase();
         Cursor res = db.rawQuery("select * from "+TABLE_NAME + " where " + COL_3 + "="+level,null);
         return res;
}

0
投票

在Database类中编写一个单独的函数,仅查询Level 2条目。 SQL查询应该是这样的

Select * From Table_name WHERE LEVEL = 2;
© www.soinside.com 2019 - 2024. All rights reserved.