Android:如何将子表与父表 Sqlite 连接起来

Posted

技术标签:

【中文标题】Android:如何将子表与父表 Sqlite 连接起来【英文标题】:Android : How to Join the Child Table With Parent Table Sqlite 【发布时间】:2020-12-29 00:09:55 【问题描述】:

我是 android 新手,我为我的学习目的创建了一个简单的应用程序,应用程序的想法是我显示学生信息,如 Parent TableCollege Name(列表视图中的大学名称列表)-> Child TableStudent Names(显示该学院的学生姓名)

1.AnnaUniversity 2.MGRUniversity---->Parent Table
 --------------    --------------
1.arun               1.Raja
2.visnu              2.Bharathi     
3.vihal                          ---->Child Table

为此,我在名为“Details.db”的单个数据库中的 SQlite 中创建了两个表(学院名称和学生名称)

First Activity我得到了大学名称的用户输入并存储在SQlite中并在Listview中显示

First Activity ListViewitem is Clciked 调用自定义对话框时,用户将存储在第二个表中的该学院的学生姓名输入到第二个表中,并在 Second Activityof Listview 和 CheckBox 中显示该名称

问题是学生姓名存储在第二个表中,它不会根据学院名称显示也没有显示在第二个活动的列表视图中例如:在 AnnaUniversity 父表中我添加了一些名称(子表)它存储到数据库中,但它不根据父名称显示

数据库助手

     // Database Name
            public static final String DATABASE_NAME = "details.db";
        
            // Table 1
            public static final String TABLE_NAME = "CollegeName";
            public static final String COLUMN_ID = "ID";
            public static final String COLUMN_TITLE = "college_NAME";
            private static final String COLUMN_IMAGE = "image_bitmap";
        
            // Table 2
            private static final String TABLE2_NAME = "studentsName";
            public static final String COLUMN1_ID = "ID";
            public static final String COLUMN2_TITLE = "students_NAME";


    public void onCreate(SQLiteDatabase sqLiteDatabase) 
    
            String query =
                    "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "("
                            + COLUMN_ID + " INTEGER PRIMARY KEY  ,"
                             + COLUMN_TITLE + " TEXT, "
                    + COLUMN_IMAGE + " BLOB )";
    
            sqLiteDatabase.execSQL(query);
    
            String query1 =
                    "CREATE TABLE IF NOT EXISTS " + TABLE2_NAME + "("
                            + COLUMN1_ID + " INTEGER PRIMARY KEY ,"
                            + COLUMN2_TITLE + "  TEXT )";
    
            sqLiteDatabase.execSQL(query1);
    
    
        
 /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Creating a College Name ( College Name was Saved in College table  ) 

    void createlist(String title, byte[] image) 
        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        cv.put(COLUMN_TITLE, title);
        cv.put(COLUMN_IMAGE, image);
        Long result = sqLiteDatabase.insert(TABLE_NAME, null, cv);
        if (result == -1) 
            Toast.makeText(context, "Failed to create", Toast.LENGTH_SHORT).show();
         else 
            Toast.makeText(context, "College Name Created Sucessfully", Toast.LENGTH_SHORT).show();
        
    


    // Read ( Displaying the saved  College Names)


    Cursor readAllData() 
        String query = "SELECT * FROM " + TABLE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = null;
        if (db != null) 
            cursor = db.rawQuery(query, null);
        
        return cursor;
    


    // Creating a second table Students Name ( Students Name was Saved in student table ) 

        void itemlist(String items) 
            SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
            ContentValues cv = new ContentValues();

            cv.put(COLUMN2_TITLE, items);

            Long result = sqLiteDatabase.insert(TABLE2_NAME, null, cv);
            if (result == -1) 
                Toast.makeText(context, "Failed to create", Toast.LENGTH_SHORT).show();
             else 
                Toast.makeText(context, "Students name Added Sucessfully", Toast.LENGTH_SHORT).show();
            
        

    // Read ( Displaying the saved  students Names)

    Cursor readlistAllData() 
        String query = "SELECT * FROM " + TABLE2_NAME;
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = null;
        if (db != null) 
            cursor = db.rawQuery(query, null);
        
        return cursor;
    

添加学生:

public class AddStudents extends AppCompatActivity 

   
    private LinearLayout linearLayout;
    DatabaseHelper myDB;
    ArrayList<String> listitems;
    StudentsCustomAdapter sca;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_items);

        

      FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_button);



        fab.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 

         // Custom Dialog is Called when Plus Button is Clicked to add Students Name inside the Selected College Name
                ShowPopup();

            
        );


        myDB = new DatabaseHelper(AddStudents.this);

        listitems = new ArrayList<>();

        DisplayList();

        sca = new StudentsCustomAdapter(AddStudents.this,listitems);
    


  // Displaying the Students Name 

    private void DisplayList()

        Cursor cursor = myDB.readlistAllData();
        if (cursor.getCount() == 0) 

            Toast.makeText(this, "No Data.", Toast.LENGTH_SHORT).show();

         else 
            while (cursor.moveToNext()) 

                listitems.add(cursor.getString(1));
            
        
    

//adding a Students name in custom dialog 
    private void ShowPopup() 

        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.custom_dialog);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            dialog.show();
        final EditText lname = dialog.findViewById(R.id.list_Edit_txt);
        Button add = dialog.findViewById(R.id.add);
        Button cancel = dialog.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                dialog.dismiss();
            
        );


        add.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
               

                String name = lname.getText().toString();
                if (!TextUtils.isEmpty(lname.getText().toString())) 
                    DatabaseHelper db = new DatabaseHelper(getApplicationContext());
                    db.itemlist(name);
                    Toast.makeText(AddItems.this, "Students Added Sucessfully !", Toast.LENGTH_SHORT).show();

                 else
                    Toast.makeText(AddItems.this, "The name cannot be empty!", Toast.LENGTH_LONG).show();


            
        );
    

学生自定义适配器

public class StudentsCustomAdapter extends BaseAdapter 


    private LayoutInflater mInflater;
    private Context context;
    private ArrayList<String> listitem_name;


    public StudentsCustomAdapter(Context c, ArrayList<String> listnames)
    
        this.context=c;
        this.listitem_name=listnames;
        this.mInflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    

    @Override
    public int getCount() 
        return listitem_name.size();
    

    @Override
    public Object getItem(int i) 
        return null;
    

    @Override
    public long getItemId(int i) 
        return 0;
    

    @Override

    public View getView(int i, View view, ViewGroup viewGroup) 

        if (view == null) 
            view = mInflater.inflate(R.layout.custom_list_items, viewGroup, false);

        
        CheckBox checkBox = view.findViewById(R.id.cheeckbox);
        TextView listitemnames = view.findViewById(R.id.listitem_name);

        listitemnames.setText((CharSequence) listitem_name);

        return null;
    

【问题讨论】:

【参考方案1】:

您可以在学生表中使用大学名称作为外键 确保您的两个列表具有不同的列名 只需确保 COLUMN_ID = "id" 而不是 COLUMN_ID ="s_id"

// 数据库名称 public static final String DATABASE_NAME = "details.db";

        // Table 1
        public static final String TABLE_NAME = "CollegeName";
        public static final String COLUMN_ID = "c_ID";
        public static final String COLUMN_TITLE = "college_NAME";
        private static final String COLUMN_IMAGE = "image_bitmap";
    
        // Table 2
        private static final String TABLE2_NAME = "studentsName";
        public static final String COLUMN1_ID = "s_ID";
        public static final String COLUMN2_TITLE = "students_NAME";


public void onCreate(SQLiteDatabase sqLiteDatabase) 

        String query =
                "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "("
                        + COLUMN_ID + " INTEGER PRIMARY KEY  ,"
                         + COLUMN_TITLE + " TEXT, "
                + COLUMN_IMAGE + " BLOB );";

        sqLiteDatabase.execSQL(query);

        String query1 =
                "CREATE TABLE IF NOT EXISTS " + TABLE2_NAME + "("
                        + COLUMN1_ID + " INTEGER PRIMARY KEY ,"
                        + COLUMN2_TITLE + "  TEXT ,"
                        + COLUMN_C_ID + " INTEGER, " + "FOREIGN KEY("+ 
                   COLUMN_C_ID +") " 
     + "REFERENCES " + TABLE_NAME +"("+COLUMN_ID +")"+ ");";


        sqLiteDatabase.execSQL(query1);

    

【讨论】:

显示错误 TABLE_NAME.COLUMN_ID **无法解析 COLUMN_ID ** i.stack.imgur.com/Xz0Ig.jpg 第二个列名后缺少 + 并更改列名 public static final String SQL_CREATE = "CREATE TABLE "+ TABLE_RECORD +"("+ COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_RECORD_INFO + " TEXT," + COLUMN_RECORD_AMOUNT + " TEXT," + COLUMN_RECORD_DATE + " TEXT," + COLUMN_CATEGORY_ID + " INTEGER, " + "FOREIGN KEY("+ RecordCategoryTable.COLUMN_ID+") " + "REFERENCES " + TABLE_RECORD +"("+COLUMN_CATEGORY_ID+")"+ ");"; 我更改了 public static final String COLUMN_ID = "C_ID";public static final String COLUMN1_ID = "S_ID"; 更新后显示相同的错误 [链接] i.stack.imgur.com/aASoW.jpg 如果我使用"FOREIGN KEY("+ TABLE_NAME+") " + "REFERENCES " inisit of "FOREIGN KEY("+ TABLE_NAME.COLUMN_ID+") " + "REFERENCES "会发生什么

以上是关于Android:如何将子表与父表 Sqlite 连接起来的主要内容,如果未能解决你的问题,请参考以下文章

如何将嵌套的子表值与父表行关联并插入子表值对应于php中的父表行

使用 AJAX 的 DataTables 中的子行

子表,父表;一对多,多对一;主键,外键梳理。

为啥我需要将子表的主键作为父表的外键,而不是相反的 1:1 识别关系?

MS Access 2010 - 如何将子表中的孤立记录链接到新创建的父记录?

SQL如果建立子表