Android:如何使用父表Sqlite联接子表 [英] Android : How to Join the Child Table With Parent Table Sqlite

查看:95
本文介绍了Android:如何使用父表Sqlite联接子表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android新手,出于学习目的创建了一个简单应用程序,该应用程序的主意是我正在显示学生信息,例如 Parent Table College Name (列表视图中的大学名称列表)-> Child Table Student Names (显示该学院的学生姓名)

I am New to Android, I created a Simple App for my Learning purpose, the app idea is i am displaying a student informations like Parent Table was College Name(List of College Names in listview) -> Child Table was Student Names(Displaying Students name of that College)

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

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

For that i Created a Two Tables(College Name and Students Name) in SQlite in Single Datbase called "Details.db"

首次活动中,我获得大学名称的用户输入并存储在SQlite中并在Listview中显示

in First Activity I get the User Input of College Name and Stored in SQlite and Display that in Listview

单击 First Activity ListViewitem 时,将在其中调用自定义对话框,用户将其存储在第二个表中的该学院的学生姓名输入并在以及CheckBox

When the First Activity ListViewitem is Clciked a Custom Dialog is Called there User enter the Students Name of that College it stored in to the Second Table and Display that in Second Activityof Listview along with CheckBox

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

The Problem is the Students Names are Stored inside the Second Table and it doesn't display according to the college name also Not Showing in listview of second activity ex : Inside AnnaUniversity Parent Table i Add Some Names(child table) it Stored into the Database But It Doesnt Display According to the Names of the parent

数据库帮助器

     // 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;
    }

推荐答案

您可以在学生表中使用学院名称作为外键确保您的两个列表都具有不同的列名只要确保COLUMN_ID ="id",比COLUMN_ID ="s_id"

you can use the college name as a foreign key in the student table make sure your both column table have different column name just make sure COLUMN_ID = "id" than COLUMN_ID ="s_id"

//数据库名称公共静态最终字符串DATABASE_NAME ="details.db";

// 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 = "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);

    }

这篇关于Android:如何使用父表Sqlite联接子表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆