【问题标题】:Why doesn't my SQL query select any row from the sqllite database为什么我的 SQL 查询没有从 sqlite 数据库中选择任何行
【发布时间】:2018-03-05 21:19:08
【问题描述】:

在我的数据库中,我有两个表“classes”和“classes_sessions”,我创建了一个链接这两个表的外键。我正在尝试使用下面的查询从这些表中检索数据

代码

String selectQuery = "SELECT * FROM " +
            TABLE_CLASSES +
            " INNER JOIN " + TABLE_CLASSES_SECTIONS +
            " ON " +
            TABLE_CLASSES_SECTIONS + "." + COLUMN_CLASSES_SECTIONS_ID +
            " = " + TABLE_CLASSES + "." + COLUMN_CLASSES_SECTIONS +
            " WHERE " +
            TABLE_CLASSES + "." + COLUMN_CLASSES_ID +
            " = " + String.valueOf(id); 

在下面的getAllSectionsByClassesID()方法中

 public ArrayList<SectionsBean> getAllSectionsByClassesID(long id){

    String selectQuery = "SELECT * FROM " +
            TABLE_CLASSES +
            " INNER JOIN " + TABLE_CLASSES_SECTIONS +
            " ON " +
            TABLE_CLASSES_SECTIONS + "." + COLUMN_CLASSES_SECTIONS_ID +
            " = " + TABLE_CLASSES + "." + COLUMN_CLASSES_SECTIONS +
            " WHERE " +
            TABLE_CLASSES + "." + COLUMN_CLASSES_ID +
            " = " + String.valueOf(id);

    SQLiteDatabase db = this.getReadableDatabase();

    ArrayList<SectionsBean> sectionsBeanList = new ArrayList<SectionsBean>();

   Cursor cursor = db.rawQuery(selectQuery,null);


    Log.i("Query details", String.valueOf(cursor));
    Log.d("DataDetails", DatabaseUtils.dumpCursorToString(cursor));

    while (cursor.moveToNext()) {


        ClassesBean classesBean = new ClassesBean();
        classesBean.setId(cursor.getLong(cursor.getColumnIndex(COLUMN_CLASSES_ID)));
        classesBean.setClasses_name(cursor.getString(cursor.getColumnIndex(COLUMN_CLASSES_NAME)));


        SectionsBean sectionsBean = new SectionsBean();
        sectionsBean.setSectionsID(cursor.getLong(cursor.getColumnIndex(COLUMN_CLASSES_SECTIONS_ID)));
        sectionsBean.setSections_name(cursor.getString(cursor.getColumnIndex(COLUMN_CLASSES_SECTIONS_NAME)));



        sectionsBean.setClassesBean(classesBean);
        sectionsBeanList.add(sectionsBean);

    }
    return sectionsBeanList;

}

但它不返回任何东西。我正在使用该行检查数据库Log.d("DataDetails", DatabaseUtils.dumpCursorToString(cursor));中游标返回的数据,结果为空白。两个表都有内容如下所示

数据库内容

类表

-05 22:06:23.728 31258-31310/com.example.demeainc.demea D/DataC: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@88a8264
                                                                     0 {
                                                                        classes_id=1
                                                                        class_item_index=null
                                                                        classes_name=jss1
                                                                        classes_codename=null
                                                                        classes_sections_id=null
                                                                        classes_teachers=null
                                                                        classes_students=null
                                                                     }
                                                                     1 {
                                                                        classes_id=2
                                                                        class_item_index=null
                                                                        classes_name=villa
                                                                        classes_codename=null
                                                                        classes_sections_id=null
                                                                        classes_teachers=null
                                                                        classes_students=null
                                                                     }
                                                                     2 {
                                                                        classes_id=3
                                                                        class_item_index=null
                                                                        classes_name=two
                                                                        classes_codename=null
                                                                        classes_sections_id=null
                                                                        classes_teachers=null
                                                                        classes_students=null
                                                                     }
                                                                     <<<<<

会话表的数据库内容

03-05 22:09:03.943 31258-31258/com.example.demeainc.demea D/DataS: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@eaadf23
                                                                     0 {
                                                                        classes_sections_ids=1
                                                                        classes_sections_name=cooolanet
                                                                        classes_sections_description=bbdbn
                                                                     }
                                                                     1 {
                                                                        classes_sections_ids=2
                                                                        classes_sections_name=morrals
                                                                        classes_sections_description=mills
                                                                     }
                                                                     2 {
                                                                        classes_sections_ids=3
                                                                        classes_sections_name=live
                                                                        classes_sections_description=bxn
                                                                     }
                                                                     3 {
                                                                        classes_sections_ids=4
                                                                        classes_sections_name=testing2
                                                                        classes_sections_description=coll
                                                                     }
                                                                     4 {
                                                                        classes_sections_ids=5
                                                                        classes_sections_name=tool
                                                                        classes_sections_description=vi
                                                                     }
                                                                     5 {
                                                                        classes_sections_ids=6
                                                                        classes_sections_name=colls
                                                                        classes_sections_description=
                                                                     }
                                                                     6 {
                                                                        classes_sections_ids=7
                                                                        classes_sections_name=more
                                                                        classes_sections_description=coll
                                                                     }
                                                                     7 {
                                                                        classes_sections_ids=8
                                                                        classes_sections_name=testing
                                                                        classes_sections_description=ttt
                                                                     }
                                                                     8 {
                                                                        classes_sections_ids=9
                                                                        classes_sections_name=threevill
                                                                        classes_sections_description=cool
                                                                     }
                                                                     <<<<<

有关表创建的更多详细信息。

// create classes_table sql query
private String CREATE_CLASSES_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_CLASSES + "("
        + COLUMN_CLASSES_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_CLASS_ITEM_INDEX + " NUMBER,"
        + COLUMN_CLASSES_NAME + " VARCHAR," + COLUMN_CLASSES_CODENAME + " VARCHAR, " + COLUMN_CLASSES_SECTIONS + " INTEGER," + COLUMN_CLASSES_TEACHERS
        + " VARCHAR," + COLUMN_CLASSES_STUDENTS + " VARCHAR,"
        + "FOREIGN KEY(" + COLUMN_CLASSES_SECTIONS + ") REFERENCES " + TABLE_CLASSES_SECTIONS  + "(" + COLUMN_CLASSES_SECTIONS_ID + ")  ON DELETE CASCADE  " + ");";

//create sections sql query
private String CREATE_CLASSES_SECTIONS_TABLE =  "CREATE TABLE IF NOT EXISTS " + TABLE_CLASSES_SECTIONS + "("
        + COLUMN_CLASSES_SECTIONS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_CLASSES_SECTIONS_NAME + " VARCHAR,"
        + COLUMN_CLASSES_SECTIONS_DESCRIPTION + " VARCHAR" + ")";

可能是什么问题。外键实际上是链接两个表。我在上面的代码中有什么问题。

【问题讨论】:

    标签: java android sqlite foreign-keys


    【解决方案1】:

    您的问题是 class_sections_id 列为 null,因此 classes_sections_table(会话表)中永远没有匹配的条目,因此没有进行 JOIN,因此没有可显示的内容。

    以下面的类表为例说明其工作原理:-

    现在是 classes_sections 表:-

    对于英语,您会看到 classes_sections_id 的值为 1 这可以对应(也称为关联/引用等)值为 的 classes_sections_ids 列1.

    查询

    SELECT * FROM classes 
        INNER JOIN classes_sections 
            ON classes_sections.classes_sections_ids = classes.classes_sections_id 
        WHERE classes.classes_id =1
    

    会导致:-

    但是,如果在 classes 表中添加了以下行(请注意对 classes_sections_id 列的引用的值为 700,并且 classes_sections 表中没有这样的行):-

    如果查询更改为获取 id 4,则不会返回任何行,因为即使 classes 表中确实存在 id 4(化学),也没有关联classes_sections 行(classes_sections_ids700),因此没有 JOIN,因此没有要返回的行。

    简而言之,您需要将 sections_id 列引用/关联/链接到 classes_sections_ids 列以检索任何数据。

    外键实际上是链接两个表吗?

    指定 FOREIGN KEY 仅指定存在约束(注意ON DELETE CASCADE 限制了约束)。它不会自动定义链接,您必须这样做。

    您可能会以编程方式执行此操作(我手动创建了上述链接),例如添加类时,您将选择一个可用部分,可能通过微调器(也称为下拉选择器)呈现。然后插入具有所选部分 id 的类。


    附加

    我相信您的设计最终会遇到问题,主要是由于您的引用/链接方式。

    例如,您的设计有一个 classes 表,其中包含一个链接到sections 表的列。这不会引入在单个列中处理链接列表的复杂性,从而将班级限制为只有一个部分(教师和学生同样适用)。

    基于一个班级可能有多个部分的假设,那么还有一个进一步的考虑,一个部分是否可以被许多班级使用(一个例子可能是所有班级都必须从疏散程序开始)。

    如果后者不适用,那么类和部分之间的关​​系可能是一对多(或者可以通过多对多关系处理)。

    • 在这种情况下,一个部分可以有一个列作为类的链接。

    如果后者适用,那么类和部分之间的关​​系将/应该是多对多关系。

    • 在这种情况下,将使用链接表(也称为关联表、引用表、映射表......)。
    • 这样的表至少有两列,每列都包含指向相关表的链接(该组合应该/应该是唯一的)。

    因此,我建议您考虑以下设计(可能还会有更多):-

    DROP TABLE IF EXISTS classes;
    CREATE TABLE IF NOT EXISTS classes ( class_id INTEGER PRIMARY KEY, class_name TEXT, class_codename TEXT );
    DROP TABLE IF EXISTS sections;
    CREATE TABLE IF NOT EXISTS sections ( section_id INTEGER PRIMARY KEY, section_name TEXT, section_description TEXT);
    DROP TABLE IF EXISTS teachers;
    CREATE TABLE IF NOT EXISTS teachers ( teacher_id INTEGER PRIMARY KEY, teacher_name TEXT);
    DROP TABLE IF EXISTS students;
    CREATE TABLE IF NOT EXISTS students ( student_id INTEGER PRIMARY KEY, student_name TEXT);
    -- LINK TABLES 
    -- Note usess column constraints to define foreign keys i.e. REFERENCES
    DROP TABLE IF EXISTS class_section_links;
    CREATE TABLE IF NOT EXISTS class_section_links (
        class_link INTEGER NOT NULL REFERENCES classes (class_id), 
        section_link INTEGER NOT NULL REFERENCES sections (section_id), 
        PRIMARY KEY (class_link, section_link));
    DROP TABLE IF EXISTS class_teacher_links;
    CREATE TABLE IF NOT EXISTS class_teacher_links (
        class_link INTEGER NOT NULL REFERENCES classes (class_id), 
        teacher_link INTEGER NOT NULL REFERENCES teachers (teacher_id), 
        PRIMARY KEY (class_link, teacher_link));
    DROP TABLE IF EXISTS class_student_links;
    CREATE TABLE IF NOT EXISTS class_student_links (
        class_link INTEGER NOT NULL REFERENCES classes (class_id),
        student_link INTEGER NOT NULL REFERENCES students (student_id),
        PRIMARY KEY (class_link, student_link));
    

    这将加载一些数据,包括类和部分之间的一些基本链接:-

    -- LOAD some data
    -- CLASSES
    INSERT INTO classes (class_name, class_codename) VALUES('English Language','EL100');
    INSERT INTO classes (class_name, class_codename) VALUES('English Literature','EL101');
    INSERT INTO classes (class_name, class_codename) VALUES('Applied Mathermatics','MA200');
    INSERT INTO classes (class_name, class_codename) VALUES('Pure Mathematics','MA201');
    INSERT INTO classes (class_name, class_codename) VALUES('Chemistry','SC300');
    INSERT INTO classes (class_name, class_codename) VALUES('Physics','SC301');
    INSERT INTO classes (class_name, class_codename) VALUES('Biology','SC302');
    INSERT INTO classes (class_name, class_codename) VALUES('GEOGRAPHY','GE400');
    -- SECTIONS
    INSERT INTO sections (section_name, section_description) VALUES('Class Introduction','Evacuation procedures, amenities etc..');
    INSERT INTO sections (section_name, section_description) VALUES('Sentence Construction','Blah');
    INSERT INTO sections (section_name, section_description) VALUES('Word types','Basic word types such as VERB, ADJECTIVE etc');
    INSERT INTO sections (section_name, section_description) VALUES('Puntuation','Blah');
    INSERT INTO sections (section_name, section_description) VALUES('Under Milk Wood','Blah');
    INSERT INTO sections (section_name, section_description) VALUES('Catcher in the Rye','Blah');
    INSERT INTO sections (section_name, section_description) VALUES('The War of the Worlds','Blah');
    -- CLASS SECTION LINKS (note assumes ID's of classes/sections in order 1,2,3......)
    -- a) All classes have Class Introduction
    INSERT INTO class_section_links VALUES(1,1); -- Class 1 English language
    INSERT INTO class_section_links VALUES(2,1); -- Class 2 English Lit
    INSERT INTO class_section_links VALUES(3,1);
    INSERT INTO class_section_links VALUES(4,1);
    INSERT INTO class_section_links VALUES(5,1);
    INSERT INTO class_section_links VALUES(6,1);
    INSERT INTO class_section_links VALUES(7,1);
    INSERT INTO class_section_links VALUES(8,1);
    -- b) specific sections
    INSERT INTO class_section_links VALUES(1,2); -- Class 1 has section 2
    INSERT INTO class_section_links VALUES(1,3); -- Class 1 has section 3
    INSERT INTO class_section_links VALUES(2,4);
    INSERT INTO class_section_links VALUES(2,5);
    INSERT INTO class_section_links VALUES(2,6);
    INSERT INTO class_section_links VALUES(2,7);
    

    一个查询,例如:-

    SELECT class_name, class_codename, section_name, section_description 
    FROM class_section_links 
        JOIN classes ON class_link = class_id 
        JOIN sections ON section_link = section_id 
    ORDER BY class_name, section_name;
    

    会导致:-

    如果您查看类介绍,您会发现只有一个部分被多次使用,因此只需要一组数据。因此,如果有一个指令将 Class Introduction 改为 Introduction,那么只需一次更改即可更新所有类。

    例如使用以下内容执行更新:-

    UPDATE sections SET section_name = 'Introduction' WHERE section_name = 'Class Introduction';
    

    并运行相同的查询结果:-

    【讨论】:

    • 好的。很好的插图。但是你的答案。 “简而言之,您需要将sections_id 列引用/关联/链接到classes_sections_ids 列以检索任何数据。”我将如何完成这项工作?由于 JOIN 我们没有执行它的功能。还有其他功能可以提供帮助吗? @MikeT
    • 您需要以编程方式制作/定义链接。 JOIN 所做的就是说根据选择(ON)从另一个表中获取行。例如,在获取某个类的数据时,您可以列出(例如通过微调器)classes_section。将选择一个,然后您将插入具有 classes_sections 表的相应 id 的类。在上面我是手动完成的。
    • 好的。意思是,在加入两个表@MikeT 之后,您无法根据类 ID 检索类部分
    • 意思是这只能使用微调器来实现? @MikeT
    • a) 您可以从各个部分的角度来看它。例如(未测试)SELECT * FROM sections JOIN classes ON classes_sections_ids = classes_section_id WHERE classes_id = 1 然后你会得到该类的部分列表。 b)微调器可能是理想的,但某种列表(如果通过用户界面进行)。但是,我即将更新有关设计的答案,这可能不像您需要的那样灵活。
    【解决方案2】:

    虽然不能回答这个可能有用的问题。

    这里有一个快速汇总的演示,展示了如何在应用中实现链接表。请注意,它非常简陋。

    应用程序最初会允许输入一个class(要求两个字段都有数据),点击按钮Add Class将尝试添加一个类(如果两个输入都至少有 1 个字符)。

    添加类后,三个额外的输入可用(可见),另外添加的类将被列出。新的输入是:-

    • 编辑节名称的文本
    • 部分描述的编辑文本
    • 链接类的微调器(只提供单个链接,稍后会出现多个)

    添加部分后,该部分将列在右侧,另外,组合的链接数据将列在列和部分列表下方。

    例如

    代码

    布局 - activity_main.xml

    • (注意包名需要改)

      <TextView
          android:id="@+id/heading"
          android:layout_width="match_parent"
          android:layout_height="wrap_content" />
      
      <EditText
          android:id="@+id/class_name"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" />
      <EditText
          android:id="@+id/class_codename"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" />
      <Button
          android:id="@+id/addclass"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Add Class"/>
      <EditText
          android:id="@+id/section_name"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" />
      <EditText
          android:id="@+id/section_description"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" />
      <Spinner
          android:id="@+id/classselection"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content">
      </Spinner>
      <Button
          android:id="@+id/addsection"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Add Section"/>
      <LinearLayout
          android:orientation="horizontal"
          android:id="@+id/lists"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">
          <ListView
              android:id="@+id/classlist"
              android:layout_width="0dp"
              android:layout_weight="1"
              android:layout_height="wrap_content">
          </ListView>
          <ListView
              android:id="@+id/sectionlist"
              android:layout_width="0dp"
              android:layout_weight="1"
              android:layout_height="wrap_content"></ListView>
      </LinearLayout>
      <ListView
          android:id="@+id/classsectionsinfo"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content">
      </ListView>
      

    数据库助手 - DBHelper.java

    public class DBHelper extends SQLiteOpenHelper {
    
        public static final String DBNAME = "educator";
        public static final  int DBVERSION = 1;
    
        public static final String TB_CLASSES = "classes";
        public static final String TB_SECTIONS = "sections";
        public static final String TB_CLASS_SECTION_LINKS = "class_section_links";
    
    
        public static final String COL_CLASSID = BaseColumns._ID;
        public static final String COl_CLASSNAME = "class_name";
        public static final String COl_CLASSCODENAME = "class_codename";
        public static final String COL_SECTIONID = BaseColumns._ID;
        public static final String COL_SECTIONNAME = "section_name";
        public static final String COL_SECTIONDESCRIPTION = "section_description";
        public static final String COL_CLASSLINK = "class_link";
        public static final String COL_SECTIONLINK = "section_link";
        public static final String COL_COMBINED = "info";
    
        SQLiteDatabase mDB;
    
        public DBHelper(Context context) {
            super(context, DBNAME, null, DBVERSION);
            mDB = this.getWritableDatabase();
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            String crttab = "CREATE TABLE IF NOT EXISTS ";
            String crtclasses = crttab + TB_CLASSES +
                    "(" +
                    COL_CLASSID + " INTEGER PRIMARY KEY, " +
                    COl_CLASSNAME + " TEXT, " +
                    COl_CLASSCODENAME + " TEXT " +
                    ")";
            String crtsections = crttab + TB_SECTIONS +
                    "(" +
                    COL_SECTIONID + " INTEGER PRIMARY KEY, " +
                    COL_SECTIONNAME + " TEXT, " +
                    COL_SECTIONDESCRIPTION + " TEXT " +
                    ")";
            String crtclasssectionlink = crttab + TB_CLASS_SECTION_LINKS +
                    "(" +
                    COL_CLASSLINK + " INTEGER " +
                    " REFERENCES " + TB_CLASSES + "(" + COL_CLASSID + ")," +
                    COL_SECTIONLINK + " INTEGER " +
                    " REFERENCES " + TB_SECTIONS + "(" + COL_SECTIONID + ") " +
                    ")";
            db.execSQL(crtclasses);
            db.execSQL(crtsections);
            db.execSQL(crtclasssectionlink);
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
        }
        public long addClass(String classname, String classcode) {
            if (classname.length() < 1 || classcode.length() < 1) {
                return -1;
            }
            ContentValues cv = new ContentValues();
            cv.put(COl_CLASSNAME,classname);
            cv.put(COl_CLASSCODENAME,classcode);
            return mDB.insert(TB_CLASSES,null, cv);
        }
    
        public long addSection(String sectioname, String sectiondescription, long baseclass) {
            long sectionid = -1;
            if (sectioname.length() < 1 || sectiondescription.length() < 1) {
                return -1;
            }
            ContentValues cv = new ContentValues();
            cv.put(COL_SECTIONNAME,sectioname);
            cv.put(COL_SECTIONDESCRIPTION,sectiondescription);
            sectionid = mDB.insert(TB_SECTIONS,null,cv);
            if (sectionid > 0 && baseclass > 0) {
                cv.clear();
                cv.put(COL_CLASSLINK,baseclass);
                cv.put(COL_SECTIONLINK,sectionid);
                mDB.insert(TB_CLASS_SECTION_LINKS,null,cv);
            }
            return sectionid;
        }
    
        public Cursor getClassAndSectionDetailsCombined() {
            //SELECT class_name||class_codename||section_name||section_description AS info
            // FROM class_section_links
            // JOIN classes ON class_link = classes._id
            // JOIN sections ON section_link = sections._id
            // ORDER BY class_name, section_name;
    
            return mDB.query(
                    TB_CLASS_SECTION_LINKS +
                            " JOIN " + TB_CLASSES + " ON " +
                            COL_CLASSLINK + " = " + TB_CLASSES + "." + COL_CLASSID +
                            " JOIN " + TB_SECTIONS + " ON " +
                            COL_SECTIONLINK + " = " + TB_SECTIONS + "." + COL_SECTIONID,
                    new String[] {
                            COl_CLASSNAME + "||" +
                                    COl_CLASSCODENAME + "||" +
                                    COL_SECTIONNAME + "||" +
                                    COL_SECTIONDESCRIPTION +
                                    " AS " + COL_COMBINED,
                    "1 AS " + BaseColumns._ID},
                    null,null,null, null,
                    COl_CLASSNAME + "," + COL_SECTIONNAME
            );
        }
    
        public Cursor getClasses() {
            return mDB.query(TB_CLASSES,null,null,null,null,null,null);
        }
    
        public Cursor getSections() {
            return mDB.query(TB_SECTIONS,null,null,null,null,null,null);
        }
        public long getSectionsCount() {
            return DatabaseUtils.queryNumEntries(mDB,TB_SECTIONS);
        }
        public long getClassesCount() {
            return DatabaseUtils.queryNumEntries(mDB,TB_CLASSES);
        }
    }
    
    • getClassAndSectionDetailsCombined 与注释 SQL 略有不同,因为游标有两列,一列是 _id,这是为了方便使用需要 _id 列的 CursorAdapters。
      • 这是一个快速/肮脏/简单的修复,因为 _id 将始终为 1

    Activity - MainActivity.java

    public class MainActivity extends AppCompatActivity {
    
        EditText mClassName, mClassCode, mSectionName, mSectionDescription;
        Button mAddClass, mAddSection;
        ListView mClassList, mSectionList, mClassSectionInfoList;
        Spinner mClassSelection;
        DBHelper mDBHlpr;
        Cursor mClasses, mSections, mCLassSectionInfo;
        SimpleCursorAdapter mSCAClasses, mSCASections, mSCAClassSecInfo;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mClassName = (EditText) this.findViewById(R.id.class_name);
            mClassCode = (EditText) this.findViewById(R.id.class_codename);
            mSectionName = (EditText) this.findViewById(R.id.section_name);
            mSectionDescription = (EditText) this.findViewById(R.id.section_description);
            mAddClass = (Button) this.findViewById(R.id.addclass);
            mAddSection = (Button) this.findViewById(R.id.addsection);
            mClassList = (ListView) this.findViewById(R.id.classlist);
            mSectionList = (ListView) this.findViewById(R.id.sectionlist);
            mClassSectionInfoList = (ListView) this.findViewById(R.id.classsectionsinfo);
            mClassSelection = (Spinner) this.findViewById(R.id.classselection);
            mDBHlpr = new DBHelper(this);
            refreshDisplay();
            handleButtons();
        }
    
        private void handleButtons() {
            mAddClass.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if ((mClassName.getText().toString().length() > 0) &&
                            mClassCode.getText().toString().length() > 0) {
                        mDBHlpr.addClass(
                                mClassName.getText().toString(),
                                mClassCode.getText().toString()
                        );
                        refreshDisplay();
                    }
                }
            });
            mAddSection.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if ((mSectionName.getText().toString().length() > 0) &&
                            (mSectionDescription.getText().toString().length() > 0)) {
                        mDBHlpr.addSection(
                                mSectionName.getText().toString(),
                                mSectionDescription.getText().toString(),
                                mClassSelection.getSelectedItemId()
                        );
                        refreshDisplay();
                    }
                }
            });
        }
    
        private void refreshDisplay() {
            // Only allow sections to be added if at least one Class exists
            if (mDBHlpr.getClassesCount() < 1) {
                mSectionName.setVisibility(View.GONE);
                mSectionDescription.setVisibility(View.GONE);
                mAddSection.setVisibility(View.GONE);
            } else {
                mSectionName.setVisibility(View.VISIBLE);
                mSectionDescription.setVisibility(View.VISIBLE);
                mAddSection.setVisibility(View.VISIBLE);
            }
            // Get Cursors from DB
            mClasses = mDBHlpr.getClasses();
            mSections = mDBHlpr.getSections();
            mCLassSectionInfo = mDBHlpr.getClassAndSectionDetailsCombined();
    
            // Prepare the Classes List Adapter or swap the cursor
            if (mSCAClasses == null) {
                mSCAClasses = new SimpleCursorAdapter(this,
                        android.R.layout.simple_list_item_1,
                        mClasses,new String[]{DBHelper.COl_CLASSNAME},
                        new int[]{android.R.id.text1},
                        0
                );
            } else {
                mSCAClasses.swapCursor(mClasses);
            }
            // Prepare the Sections List Adapter
            if (mSCASections == null) {
                mSCASections = new SimpleCursorAdapter(this,
                        android.R.layout.simple_list_item_1,
                        mSections,
                        new String[]{DBHelper.COL_SECTIONNAME},
                        new int[]{android.R.id.text1},
                        0
                );
            } else {
                mSCASections.swapCursor(mSections);
            }
            if (mSCAClassSecInfo == null) {
                mSCAClassSecInfo = new SimpleCursorAdapter(this,
                        android.R.layout.simple_list_item_1,
                        mCLassSectionInfo,
                        new String[]{DBHelper.COL_COMBINED},
                        new int[]{android.R.id.text1},
                        0
                );
            } else {
                mSCAClassSecInfo.swapCursor(mCLassSectionInfo);
            }
            mClassList.setAdapter(mSCAClasses);
            mClassList.setBackgroundColor(0xFF5555ff);
            mSectionList.setAdapter(mSCASections);
            mSectionList.setBackgroundColor(0xFF55FF55);
            mClassSelection.setAdapter(mSCAClasses);
            mClassSectionInfoList.setAdapter(mSCAClassSecInfo);
            mClassSectionInfoList.setBackgroundColor(0xFFFFFFDD);
        }
    }
    

    【讨论】:

    • 经过我们无数次的考验,轰隆隆!!它就像魔术一样工作。我研究了你的代码,我花了很多时间来理解它。我真的很感谢你的时间。
    • 陡峭的学习曲线,但我相信您具备达到目标所需的条件。如果您将此帖子标记为有帮助,那就太好了,如果确实如此的话。
    • 但是我有几个问题,从我的应用程序 UI 的图表中,我猜你最注意到我使用了 recyclerview。因此,我使用getItemId(position) 方法来获取要传递给数据库的ID getClassAndSectionDetailsCombined 方法。在selectQuery 中,我使用了Where clause,即where classes_id = id,其中id 是从适配器类中的getItemId(position) 传递的id。
    • 但是,class_sections 只添加到两个 id,而与我创建的类的数量无关。例如,如果我创建类 1 ,2 和 3 并将 class_sections 添加到所有 3. 部分被添加到 1 和 2 当前,任何尝试将部分添加到 3 或任何其他类之后都不起作用,相反,@ 987654336@ 被添加到 1 或 2 中,而 3 仍然没有 classes_session。只是似乎会话放错了位置
    • 想一想在我的情况下可能导致此问题的原因。
    猜你喜欢
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 2011-05-12
    相关资源
    最近更新 更多