【问题标题】:Android : How to Join the Child Table With Parent Table SqliteAndroid:如何将子表与父表 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;
    }

【问题讨论】:

    标签: android android-listview android-sqlite


    【解决方案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 "会发生什么
    猜你喜欢
    • 2012-11-12
    • 2021-02-23
    • 2017-10-21
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    相关资源
    最近更新 更多