gpt4 book ai didi

java - 如何在抽屉导航中的 fragment 上显示 SQLite 数据库数据?

转载 作者:太空宇宙 更新时间:2023-11-04 10:58:31 24 4
gpt4 key购买 nike

我正在努力使用抽屉导航显示内容。基本上我有一个显示五类面条的数据库。每个类别都作为抽屉导航中的 fragment 列出。但我不知道如何将 Activity (例如面条列表)连接到这样的 fragment 。有人可以帮忙吗?这是我的代码:

五个 fragment 类之一:

public class KoreanFragment extends Fragment {
public KoreanFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_korean, container, false);

}
}
主 Activity 类显示抽屉:

public class NoodleActivity extends AppCompatActivity {
private Cursor cursor;
private SQLiteDatabase database;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_noodle);
//set up toolbar as the normal app bar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

ListView noodleListPerCategory = findViewById(R.id.selected_noodleList);
SQLiteOpenHelper databaseHelper = new DatabaseHelper(this);
try {
database = databaseHelper.getReadableDatabase();
cursor = database.query("NOODLE", new String[]{"_id", "NAME"}, null, null, null, null, null);
//create the cursor adapter to fill the list view with values from the database
SimpleCursorAdapter listAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[]{"NAME"},
new int[]{android.R.id.text2}, 0);
noodleListPerCategory.setAdapter(listAdapter);
} catch (SQLiteException e) {
Toast toast = Toast.makeText(this, "Database error", Toast.LENGTH_SHORT);
toast.show();
}

//show item detail using the listener when an item is clicked
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//starts DetailActivity
Intent intent = new Intent(NoodleActivity.this, DetailActivity.class);
intent.putExtra(DetailActivity.CHOSEN_NOODLE_ITEM, (int) id);
startActivity(intent);
}
};
//connects the listener to the list view
noodleListPerCategory.setOnItemClickListener(itemClickListener);
}

/**
*This method is called when the database and cursor need to be closed.
* They are closed when the cursor adapter doesn't need them anymore.
* */
@Override
public void onDestroy(){
super.onDestroy();
cursor.close();
database.close();
}
}

显示数据库中面条列表的类:

public class DatabaseHelper extends SQLiteOpenHelper {
//the name for the database
private static final String DATABASENAME = "NoodleDB";
//the initial version of the database
private static final int DATABASEVERSION = 1;
private Noodle noodle;

DatabaseHelper(Context context) {
super(context, DATABASENAME, null, DATABASEVERSION);

}

@Override
public void onCreate(SQLiteDatabase db) {
updateDatabase(db, 0, DATABASEVERSION);

}

/**
* this method updates the database if the db helper's version number is higher than the version number on the db.
*
* @param db The SQLite database
* @param currentVersion The user's version number of the database
* @param updatedVersion The new version of the database written in the helper's code
*/

@Override
public void onUpgrade(SQLiteDatabase db, int currentVersion, int updatedVersion) {
updateDatabase(db, currentVersion, updatedVersion);
}

/**
* This method is called when you want to set the database back to its previous version
*
* @param db The SQLite database
* @param currentVersion The user's version number of the database
* @param updatedVersion The new version of the database written in the helper's code
*/
public void onDowngrade(SQLiteDatabase db, int currentVersion, int updatedVersion) {

}

/**
* This method is for adding new noodle dish to the database
*/
private static void addNoodle(SQLiteDatabase database, Noodle noodle) {
ContentValues noodleValues = new ContentValues();
noodleValues.put("NAME", noodle.getName());
noodleValues.put("DESCRIPTION", noodle.getDescription());
noodleValues.put("IMAGEID", noodle.getPhotoID());
noodleValues.put("RESTAURANT", noodle.getSuggestedRestaurant());
database.insert("NOODLE", null, noodleValues);
database.close();

}

private void updateDatabase(SQLiteDatabase db, int currentVersion, int updatedVersion) {
if(currentVersion >= 1 || currentVersion < 1 ) {
//execute SQL on the db and create a new NOODLE table
db.execSQL("CREATE TABLE NOODLE ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "NAME TEXT, "
+ "DESCRIPTION TEXT, "
+ "IMAGEID INTEGER, "
+ "RESTAURANT TEXT, "
+ "FAVORITE NUMERIC, "
+ "CATEGORY TEXT);");
addNoodle(db, new Noodle("Spicy Ramen", "Chicken broth, marinated pork, chilli and bean sprouts", R.drawable.spicyramen, "Totemo", "japanese"));
addNoodle(db, new Noodle("Tokyo Ramen", "Dashi-based broth, marinated pork and fermented bamboo shoots", R.drawable.tokyo, "Totemo", "japanese"));
addNoodle(db, new Noodle("Vegetarian Ramen", "Mushroom dashi-based broth, tofu, pak choi, miso and corn", R.drawable.vegetarianramen, "Ramen Manga", "japanese"));
addNoodle(db, new Noodle("Miso Ramen", "Miso broth, marinated pork, egg, spring onion and bean sprouts", R.drawable.miso, "Cafe Steigman", "japanese"));
addNoodle(db, new Noodle("Tonkatsu Ramen", "Pork bone based broth, grilled pork, spicy garlic with miso", R.drawable.tonkatsu, "Blue Light Yokohama", "japanese"));
addNoodle(db, new Noodle("Shio Ramen", "Seasalt broth, pork, egg, quail and vegetable", R.drawable.shio, "Ai Ramen", "japanese"));
addNoodle(db, new Noodle("Nabeyaki Udon", "Udon noodles in fish broth with chicken, shrimp, egg and leek", R.drawable.udon, "Ki-mama Ramen", "japanese"));
}
if(currentVersion <=2) {

}
}
}

DatabaseHelper 类

public class NoodleActivity extends AppCompatActivity {
private Cursor cursor;
private SQLiteDatabase database;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_noodle);
//set up toolbar as the normal app bar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

ListView noodleListPerCategory = findViewById(R.id.selected_noodleList);
SQLiteOpenHelper databaseHelper = new DatabaseHelper(this);
try {
database = databaseHelper.getReadableDatabase();
cursor = database.query("NOODLE", new String[]{"_id", "NAME"}, null, null, null, null, null);
//create the cursor adapter to fill the list view with values from the database
SimpleCursorAdapter listAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[]{"NAME"},
new int[]{android.R.id.text2}, 0);
noodleListPerCategory.setAdapter(listAdapter);
} catch (SQLiteException e) {
Toast toast = Toast.makeText(this, "Database error", Toast.LENGTH_SHORT);
toast.show();
}

//show item detail using the listener when an item is clicked
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//starts DetailActivity
Intent intent = new Intent(NoodleActivity.this, DetailActivity.class);
intent.putExtra(DetailActivity.CHOSEN_NOODLE_ITEM, (int) id);
startActivity(intent);
}
};
//connects the listener to the list view
noodleListPerCategory.setOnItemClickListener(itemClickListener);
}

/**
*This method is called when the database and cursor need to be closed.
* They are closed when the cursor adapter doesn't need them anymore.
* */
@Override
public void onDestroy(){
super.onDestroy();
cursor.close();
database.close();
}
}

现在......数据库尚未创建,我不知道如何在 fragment 上显示数据,更不用说按类别过滤了。 :(

最佳答案

我相信您所要做的就是创建 DatabaseHelper 的实例,然后通过 SQLiteDatabase 实例或通过 DatabaseHelper 内的方法或通过 DatabaseHelper 访问数据库,就像从 Activity 中一样。您确实需要一个上下文,可以通过 getActivity 获取方法或 getContext方法。

例如(假设您的 KoreanFragment 是您希望访问数据库并显示数据的位置;并且数据将通过 ListView 显示):-

    public class KoreanFragment extends Fragment {

Databasehelper mDBHlpr = new DatabaseHelper(getContext()); //<<<<<<<<
SQLiteDatabase mDatabase = mDBHlpr.getWriteableDatabase(); //<<<<<<<<
ListView mMyListView; //<<<<<<<<
SimpleCursorAdpater mSCA; //<<<<<<<<
Cursor mCsr; //<<<<<<<<

//????????Alternative SQLiteDatabase = new DatabaseHelper(getActivity()).getWriteableDatabase();

public KoreanFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_korean, container, false); //<<<<<<<< don't return as yet
mMyListView = view.findViewByid(R.id.mylistview); //<<<<<<<< get the Listview to be populated

mCsr = getAllRows(); //<<<<<<<< get data as cursor
mSCA = new SimpleCursorAdapter(getContext(),android.R.layout.simple_list_item_1,mCsr,new String[]{"NAME"},new int[]{android.R.id.text1},0); //<<<<<<<< prepare adapater for ListView
mMyListView.setAdapter(mSCA); //<<<<<<<< attach the adapter to the ListView
return view; //<<<<<<<<

}

//<<<<<<<< new method to query the database an extract all rows from the NOODLE table
private Cursor getAllRows() {
return mDatabase.query("NOODLE",null,null,null,null,null,null);
}
}

完成后您应该真正关闭游标,以便您可以添加以下内容来覆盖 onDetach 方法:-

        @Override
public void onDetach() {
super.onDetach();
mCsr.close();
}

您可能希望使用该列表,例如如果长单击一行,则删除该行。

这可以通过1)添加以下方法来完成:-

        private void setItemLongClickListener() {
mMyListview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
mDatabase.delete("NOODLE","_id=?",new String[]{Long.toString(id)});
mCsr = getAllRows();
mSCA.swapCursor(mCsr);
return true;
}
});

2)mMyListView.setAdapter(mSCA); 行之后立即添加以下行:-

        setItemLongClickListener();

注释

  • 我已使用 //<<<<<<<< 指示新的/更改的代码
  • 以上是原理/理论代码,而不是经过测试的代码,因此可能存在拼写错误或错误。
  • mylistview mMyListView = view.findViewByid(R.id. <强> mylistview );很可能必须添加到布局中,并且名称可能适合您的命名约定。

关于java - 如何在抽屉导航中的 fragment 上显示 SQLite 数据库数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47142745/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com