使用RecyclerView和Fragments检索数据库信息

时间:2016-11-19 11:29:11

标签: android sqlite android-fragments

  1. 如何使用' getCategories()在CategoryListFragment中检索数据?' 我在MyDBHelper中使用GetAllValues()函数,但不知道如何使用它@fragments类,因为我在尝试时无法正确初始化MyDBHelper对象。
  2. MyDBHelper.class

    public class MyDatabaseHelper extends SQLiteOpenHelper {
    
    private static final String DATABASE_NAME="CategoryDatabase";
    
    public MyDatabaseHelper(Context context) {
    
        super(context, DATABASE_NAME, null, 1);
    
    }
    
    @Override
    
    public void onCreate(SQLiteDatabase database) {
    
        database.execSQL("CREATE TABLE Category (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);");
    
    }
    
    @Override
    
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
        db.execSQL("DROP TABLE IF EXISTS Category");
    
        onCreate(db);
    
    }
    
    public void addCategory(String name)
    
    {
    
        ContentValues values=new ContentValues(1);
    
        values.put("name", name);
    
        getWritableDatabase().insert("Category", "name", values);
    
    }
    
    public Cursor getCategories()
    
    {
    
        Cursor cursor = getReadableDatabase().rawQuery("select * from Category", null);
    
        return cursor;
    
    }
    
    public ArrayList<String> GetAllValues()
    {
        String aTable = "Category"; // Table's name
        ArrayList<String> list = new ArrayList<String>();
        Cursor cursor =  getCategories();
        if (cursor.moveToFirst())
        {
            do
            {
                list.add(cursor.getString(0));
            }
            while (cursor.moveToNext());
        }
        if (cursor != null && !cursor.isClosed())
        {
            cursor.close();
        }
    
        return list;
    }
    }
    

1 个答案:

答案 0 :(得分:0)

在你的fragment类中,像这样初始化MyDatabaseHelper对象

MyDatabaseHelper dbHelper = new MyDatabaseHelper(getActivity()); 

并在getCategories方法中像这样获取它

ArrayList<String> list = dbHelper.GetAllValues();

修改

public ArrayList<String> GetAllValues()
{
String aTable = "Category"; // Table's name
ArrayList<Category> list = new ArrayList<>();
Cursor cursor =  getCategories();
if (cursor.moveToFirst())
{
    do
    {
       Category cat  = new Category(cursor.getString(0));
        list.add(cat);
    }
    while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed())
{
    cursor.close();
}

return list;
}

编辑2: 尝试添加像这样的片段

getSupportFragmentManager().beginTransaction().replace(R.id.test_container, fragment, "CategoryFragment").commit();