【问题标题】:How to display SQLite database data on a fragment from a navigation drawer?如何在导航抽屉的片段上显示 SQLite 数据库数据?
【发布时间】:2018-04-18 23:00:07
【问题描述】:

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

五个片段类之一:

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);

        }
    }
主活动类显示抽屉:

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

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

【问题讨论】:

  • 这需要大量代码。如果您将源代码缩小到基本内容,您将获得更好的答案。
  • 对不起,你把 200 行代码丢给我们了?!请阅读有关创建最小可行完整示例的信息(stackoverflow.com/help/mcve)

标签: java android sqlite android-fragments


【解决方案1】:

我相信您所要做的就是创建一个 DatabaseHelper 实例,然后通过 SQLiteDatabase 实例或通过 DatabaseHelper 中的方法或通过 DatabaseHelper 访问数据库,就像您从活动中一样。你确实需要一个Context,可以通过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();
        }

您可能希望使用列表,例如如果它是 longClicked,则删除该行。

这可以通过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();

注意事项

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

【讨论】:

  • 谢谢!但我试图在片段中实现你的代码,但现在应用程序甚至不再启动:')
猜你喜欢
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多