使用SQLite在recyclerView中显示字符串数组

时间:2017-05-26 13:17:43

标签: android sqlite android-recyclerview

我已经创建了一个SQLite数据库并在其中存储了字符串,并希望它在recyclelerView中的textview中显示。我应该如何初始化数组?

DatabaseHelper:

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "Student.db";
    public static final String TABLE_NAME = "student_table";
    public static final String Col_1 = "ID";
    public static final String Col_2 = "Title";
    public static final String Col_3 = "Content";
    public static final String Col_4 = "Remarks";


    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
        SQLiteDatabase db = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " +TABLE_NAME+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, Title TEXT, Content TEXT, Remarks TEXT )");

    }

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

    }
}

这就是我初始化cardView的方式:

   private void initializeCardItemList(){
        CardItemModel cardItemModel;
        /*String[] cardTitles = getResources().getStringArray(R.array.cat1_cards);
        String[] cardContents = getResources().getStringArray(R.array.cat1_cards_content); */
        final int length = cardTitles.length;
        for(int i=0;i<length;i++){
            cardItemModel = new CardItemModel(cardTitles[i],cardContents[i]);
            cardItems.add(cardItemModel);
        }
    }

3 个答案:

答案 0 :(得分:0)

在这里初始化:

DatabaseHelper=new DataBaseAdapter(...);// initialize here
    recyclerView.setAdapter(new RecycleViewAdapter(
               DataBaseHelper.getData(),R.layout.rec_layout));

答案 1 :(得分:0)

假设您使用SQLiteDatabase.query()来查询数据库中的字符串。在初始化c:

之后,您可以这样做
ArrayList<String> mStrings = new ArrayList<>();
while (mCursor.moveToNext()) {
    int columnIndex = cursor.getColumnIndex("column_name");
    mStrings.add(cursor.getString(columnIndex);
}

这会将mCursor中的所有字符串添加到mStrings。您可以使用ArrayList<>.get()方法访问字符串。

修改:然后,您可以通过ArrayList<String>构造函数传递RecyclerView.Adapter对象,并将其设置为在TextView期间由RecyclerView.Adapter.onBindViewHolder()显示

答案 2 :(得分:0)