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;
}
}
答案 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();