java - 如何使用sqlite制作android测验应用程序?

标签 java android sqlite android-sqlite

我正在研究android测验应用程序。我的目标是制作包含5个主题的多项选择题的测验应用程序。

每个主题有5章,每章有20个多项选择题。

到目前为止,我已经能够制作android应用程序,该应用程序开始对一个主题的所有章节的多项选择题进行测验。我通过在sqlite中制作一张桌子来做到这一点。

所有章节的多项选择题将在一项活动中显示。我希望我的应用程序分别开始每个章节的测验。我必须为每个活动创建单独的游标吗?如何进行?

我的代码

public class QuizDbHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "MyAwesomeQuiz.db";
    private static final int DATABASE_VERSION = 2;    
    private SQLiteDatabase db;

    public QuizDbHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);    
    }

    @Override    
    public void onCreate(SQLiteDatabase db) {
        this.db = db;

        final String SQL_CREATE_Current_Affairs_TABLE = "CREATE TABLE " +
                QuizContract.Questions_CurrentAffairs.TABLE_NAME + " ( " +
                QuizContract.Questions_CurrentAffairs._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                QuizContract.Questions_CurrentAffairs.COLUMN_QUESTION + " TEXT, " +
                QuizContract.Questions_CurrentAffairs.COLUMN_OPTIONA1 + " TEXT, " +
                QuizContract.Questions_CurrentAffairs.COLUMN_OPTIONB1 + " TEXT, " +
                QuizContract.Questions_CurrentAffairs.COLUMN_OPTIONC1 + " TEXT, " +
                QuizContract.Questions_CurrentAffairs.COLUMN_OPTIOND1 + " TEXT, " +
                QuizContract.Questions_CurrentAffairs.COLUMN_ANSWER_NR + " INTEGER" +
                ")";

        db.execSQL(SQL_CREATE_Current_Affairs_TABLE);
        CurrentAffairs_Questions();

        final String SQL_CREATE_Islamic_Studies_TABLE = "CREATE TABLE " +
                QuizContract.Questions_IslamicStudies.TABLE_NAME + " ( " +
                QuizContract.Questions_IslamicStudies._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                QuizContract.Questions_IslamicStudies.COLUMN_QUESTION + " TEXT, " +
                QuizContract.Questions_IslamicStudies.COLUMN_OPTIONA2 + " TEXT, " +
                QuizContract.Questions_IslamicStudies.COLUMN_OPTIONB2 + " TEXT, " +
                QuizContract.Questions_IslamicStudies.COLUMN_OPTIONC2 + " TEXT, " +
                QuizContract.Questions_IslamicStudies.COLUMN_OPTIOND2 + " TEXT, " +
                QuizContract.Questions_IslamicStudies.COLUMN_ANSWER_NR + " INTEGER" +
                ")";

        db.execSQL(SQL_CREATE_Islamic_Studies_TABLE);    
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        db.execSQL("DROP TABLE IF EXISTS " + QuizContract.Questions_CurrentAffairs.TABLE_NAME);
        onCreate(db);
         db.execSQL("DROP TABLE IF EXISTS " + QuizContract.Questions_IslamicStudies.TABLE_NAME);
        onCreate(db);   
    }

    private void CurrentAffairs_Questions() {
        Question q1 = new Question("The worlds oldest international human rights organization is?"," amnesty international ", " freedom house ", " anti slavery ","non of these ", 3);
        addQuestion(q1);

        Question q2 = new Question("The constitution of European union has not been ratified by?"," Italy ", "Netherlands ", " France ","non of these ",3);
                addQuestion(q2);

        Question q3 = new Question("After united states, the largest contributor in the united nations budget is? "," Germany "," France ", " UK "," none of these",3);
        addQuestion(q3);

        Question q4 = new Question("Ariana is an airlines of ?", "Australia ", " Egypt ", "Iran ","non of these ",4);
        addQuestion(q4);

        Question q5 = new Question("What percentage Pakistan produces electricity from thermal source ?"," 30% ", " 50% ", " 70% "," non of these ",3);
        addQuestion(q5);

        Question q6 = new Question("Chinas fastest growing economy is facing a major challenge of ?",
                " population explosion ", " shortage of electricity ", "challenges of WTO regime ","non of these ",1);
        addQuestion(q6);

        Question q7 = new Question("US president George bush has created ‘millennium challenge Account’ to ?", " improve national security ", " provide aid to iraq and afghanistan ", " help poor countries pursuing democratic ideals ","non of these ",1);
        addQuestion(q7);

        Question q8 = new Question("38th parallel is a boundary line between ?", " Canada and America ", " north and south Vietnam ", " greek and turkish port of Cyprus ","  non of these ",2);
        addQuestion(q8);

        Question q9 = new Question("In which month does the un general assembly usually meet every year ?", " January ", " march ", " September ","non of these ",3);
        addQuestion(q9);

        Question q10= new Question("Pakistan has recently been given observer status in ?", "OECD ", " gulf cooperation council (gcc) ", " shanghai cooperation organization(sco) "," non of these ",3);
        addQuestion(q10);

        // Year 2005

        Question q11 = new Question("The project to reduce water logging and salinity area in Pakistan has been financially supported by?", " world bank ", " IMF ", " Asian Development Bank "," non of these ",1);
        addQuestion(q11);

        Question q12 = new Question("Pakistan and US navies recently conducted joint exercises in the Arabian Sea by the name of?", " Optimum Impact ", " Divers Move ", " Inspired Union ","non of these ",3);
        addQuestion(q12);

        Question q13 = new Question("Which of the following internet search engine will introduce the worlds biggest digital library?", "yahoo ", " google ", " giga blast "," non of these ",2);
        addQuestion(q13);

        Question q14 = new Question("The recently appointed United nations high commissioner for refugees Antonio guterres is the former prime minister of?"," denmark ", " Romania ", " Canada "," non of these ",4);
        addQuestion(q14);

        Question q15 = new Question("When a country grants another country MFN (most favored nation) status in mutual trade, it implies?", " providing same trade concessions as are being given to other countries ", " trade will be through exchange of commodities rather than foreign exchange ", " imports and exports payments will be in local currencies only "," non of these ",1);
        addQuestion(q15);

        Question q16 = new Question("The programme ‘united nations millennium development goals’ is focusing on?", " eradicate extreme poverty and hunger ", "achieve universal primary education ", " promote gender equality and empower women "," all of the above ",4);
        addQuestion(q16);

        Question q17 = new Question("The largest agency of FATA (federally administered tribal areas) by area is?", " north waziristan ", " south waziristan ", " Khyber agency "," non of these ",2);
        addQuestion(q17);

        Question q18 = new Question("Reuter is the news agency of?", " USA ", " Germany ", " UK "," non of these ",3);
        addQuestion(q18);

        Question q19 = new Question("SAARC human resource development centre is located at?", " Delhi ", " Colombo ", " Karachi "," non of these ",4);
        addQuestion(q19);

        Question q20= new Question("Under Vision 2025 WAPDA will construct SATPARA Dam on Indus Rive in?", " Balochistan ", " NWFP ", " Northern Areas "," non of these ",3);
        addQuestion(q20);

        Question q21 = new Question("How many medals were won by Pakistan in the 18th Commonwealth games? ", " 3 ", " 5 ", " 7 "," None of these ",2);
        addQuestion(q21);

        Question q22 = new Question("The Currency of China is:?", "Rouble ", "Yen ", "Yuan ","None of these ",3);
        addQuestion(q22);

        Question q23 = new Question("In the absence of President, who becomes the acting President of Pakistan? ", "Speaker of the NA ", "Chairman Senate ", "Chief Justice of pakistan ","None of these ",2);
        addQuestion(q23);

        Question q24 = new Question("Han Myung has become the First Woman Prime Minister of:?", "South Korea ", "North Korea ", "Vietnam ","None of these ",1);
        addQuestion(q4);

        Question q25 = new Question("Zalmay Khalil is the US Ambassador to:?", "Iraq ", "Syria ", "Lebanon ","None of these ",1);
        addQuestion(q25);

        Question q26 = new Question("H3N1 is the name of a:?", " Medicine ", "Vaccine ", "Virus ","None of these ",3);
        addQuestion(q26);

        Question q27 = new Question("Biman is the AirLine of:?", " Sri Lanka ", "Nepal ", "Bangladesh ","None of these ",3);
        addQuestion(q27);

//        Question q28 = new Question(" Which country border with Pakistan is called Durand line:" ,"Iran"," Afghanistan ", "Pakistan ", "Iran ","None of these",2);
//        addQuestion(q28);

        Question q29 = new Question("Xinhua is the news agency of:?", "China ", "Russia ", "North Korea ","None of these ",1);
        addQuestion(q29);

        Question q30= new Question("The headquarters of the UN Security Council is located at:?", "Washington", "Paris ", "New York ","None of these ",3);
        addQuestion(q30);

        // Year 2006

        Question q31 = new Question("Who is the Governor of the State Bank of Pakistan? ?", "Dr. Shamshad Akhtar ", "Dr. Ishrat Hussain ", " Sulman Shah ","None of these ",1);
        addQuestion(q31);

        Question q32 = new Question("Nobel Peace Prize for the year 2005 was awarded to M. Elbardei together with: ?", "United Nations Educational Scientific and Cultural Organization (UNESCO) ", " International Atomic Energy Agency (IAEA) ", "World Health Organization (WHO) ","None of these ",2);
        addQuestion(q32);

        Question q33 = new Question("Who is the US Assistant Secretary of state for South Asian and Central Asian affairs? ", "Riyan C. Crocker ", "Nancy Powell ", "Richard A. Boucher ","none of these. ",3);
        addQuestion(q33);

        Question q34 = new Question("What was the magnitude of the Earthquake that shook northern Pakistan and Azad Kashmir on October, 8, 2005 ?", "5.7 ", "7.5 ", "7.7 ","None of these. ",4);
        addQuestion(q4);

        Question q35 = new Question("Rafiq Bahauddin al Harriri had been the Prime Minister of :?", "Libya  ", "Lebanon ", "Syria ","None of these.",2);
        addQuestion(q35);

        Question q36 = new Question("Angela Mekel is the?", " President of France", "First lady of Britain", "Chancellor of Germany","none of these ",3);
        addQuestion(q36);

        Question q37 = new Question("Fourth Estate applied to:?", " Executive ", "Secret Agency ", "Press ","None of these ",3);
        addQuestion(q37);

        Question q38 = new Question("The Spirit of Islam author is: ?", "Sir Syed Ahmad Khan ", "Syed Amir Ali ", "Allama Iqbal ","none of these ",2);
        addQuestion(q38);

        Question q39 = new Question("The South Asian Associan for regional cooperation (SAARC) Standing Committee had agreed in principle to grant an observer status to:?", "China and japan ", "Britain and France ", "US and Korea ","None of these ",3);
        addQuestion(q39);

        Question q40= new Question("George Washington was the first President of USA. Who is the incumbent Vice President of America? ", " George Bush ", "Gerald Ford ", "Dick Cheney ","None of these ",4);
        addQuestion(q40);

        Question q41 = new Question("Patronas towers are located in:", "Singapore ", " Chicago ", "Kaula Lumpur ","None of these ",3);
        addQuestion(q41);

        Question q42 = new Question("Name of the present Un secretary general is :?", "Kofi Annan ", "Bon ki Moon ", "Batrus Ghali ","None of these ",2);
        addQuestion(q42);

        Question q43 = new Question("The length of common border between India and Pakistan is:?", "900 miles ", "1000 miles ", "1100 miles ","None of these ",4);
        addQuestion(q43);

        Question q44 = new Question("Last SAARC conference was held in 2004 at: ?", "Islamabad ", "Kathmandu ", "Colombo ","None of these ",1);
        addQuestion(q44);

        Question q45 = new Question("China became the member of the World Trade Organization in ?", "1998 ", "2002 ", "2004","None of these ",4);
        addQuestion(q45);

        Question q46 = new Question("The number of players in each team of basketball game is:?", "5 ", "7 ", "9 ","None of these ",1);
        addQuestion(q46);

        Question q47 = new Question("Which is the largest Surah of Holy Quran: ?", "Surah Al-Imran ", "Sura Al-Baqarah ", "Surah Yaseen ","None of these ",2);
        addQuestion(q47);

        Question q48 = new Question("The Olympic games in 2004 were held in: ?", "Athens ", "Sydney ", "California ","None of these ",1);
        addQuestion(q48);

        Question q49 = new Question("How many members the National Security Council (Pakistan ) has:?", "11 ", "13 ", "15 ","None of these ",4);
        addQuestion(q49);
        Question q50= new Question("Nobel peace Prize for the year 2006 was awarede to:?", "Dr. Mahatir Mohammad ", " Dr Mohammad Yunus ", "Dr Abdul Kalam ","None of these ",2);
        addQuestion(q50);

        // Year 2007

        Question q51 = new Question("Denzil Washington is renowned as:?", "USA army general", "British Naval Commander ", "Hollywood actor ","None of these ",3);
        addQuestion(q51);

        Question q52 = new Question("The number of OIC member states is: ?", "55 ", "57 ", "59 ","None of these ",2);
        addQuestion(q52);

        Question q53 = new Question("Mahbub-ul-Haq Human Development Center is locates at:?", "Karachi ", "Lahore ", "Islamabad ","None of these ",3);
        addQuestion(q53);

        Question q54 = new Question("Hugo Chavez is the president of:?", "Venezuela ", "Brazil ", "Bolivia ","None of these ",1);
        addQuestion(q54);

        Question q55 = new Question("what is the name of the only Pakistani whi won the Nobel Prize:?", "Dr Ashfaq Ahmed ", "Dr. abdus- Salam ", "Dr. Abdul Qadeer ","None of these ",2);
        addQuestion(q55);

        Question q56 = new Question("Maple leaf is the National emblem of:?", "Germany ", "China ", "Canada ","None of these ",3);
        addQuestion(q56);

        Question q57 = new Question("Name of Bangladesh parliament is:?", "People National Assembbly ", "Majilis-I-Shoora ", "Jatia Sangsad ","None of these ",3);
        addQuestion(q57);

        Question q58 = new Question("India has constructed “Baglihar Dam” in occupied Kashmir`s district of:?", "Udhumpur ","Doda ", "Jammu ","None of these ",2);
        addQuestion(q58);

        Question q59 = new Question("“Hamas” was founded in 1987 by: ?", "Yasser Arfat ", "Ismail Haniye ", "Khalid Meshaal ","None of these ",4);
                addQuestion(q59) ;

        Question q60= new Question("which of the following regions of Balochistan will be irrigated through Kachi cannal project:?", "quetta ", "Zhob ", "Nasirabad "," None of these",3);
        addQuestion(q60);

        // Pakistan Affairs 2008


        Question q61 = new Question("Transparency International is based in:?", "New York ","London ", "Berlin ","None of these ",3);
        addQuestion(q61);

        Question q62 = new Question("The largest source of electricity generation in Pakistan comes through:?","Thermal ", "Hydel ", "Coal ","None of these ",1);
        addQuestion(q62);

        Question q63 = new Question("Pakistan’s largest export partner is:?","Saudi Arabia ", "America ", "Japan ","None of these ",2);
        addQuestion(q63);

        Question q64 = new Question("India is constructing Kishanganga Dam in:?", "Jammu ", "Sri nagar ", "Baramula ","None of these ",1);
        addQuestion(q64);

        Question q65 = new Question("WAFA is the news agency of:?", " Syria ", "Jordan ", "Egypt ","None of these ",4);
        addQuestion(q65);

        Question q66 = new Question("Former US Vice-President Al Gore has won Noble Peace Prize 2007 for his campaign against:?", "Child Labour ", "Human Rights Violations ", "Global Warming ","None of these ",3);
        addQuestion(q66);

        Question q67 = new Question("May 3, each year is Internationally observed as:?","World Environment Day ", "Human Rights Day ", "Press Freedom Day ","None of these ",3);
        addQuestion(q67);

        Question q68 = new Question("The World’s largest producer of Uranium is: ?", "Australia ", "Canada ", "South Africa ","None of these ",4);
        addQuestion(q68);

        Question q69 = new Question("The district of the country having lowest population density is:?", "Khuzdar ", "Kalat ", "Kharan ","None of these ",2);
        addQuestion(q69);

        Question q70= new Question("Qantas is an airline of:?",
                "USA ", "Australia ", "Singapore ","None of these ",2);
        addQuestion(q70);


        // Year 2008

        Question q71 = new Question("The first Muslim Nobel Laureate was:?", "Anwar Saadat of Egypt ", "Yasser Arafat of Palestine ", "Abdus Salam of Pakistan ","None of these ",3);
        addQuestion(q71);

        Question q72 = new Question("Darfur conflict is in:?", " Somalia ", "Sudan ", "Liberia ","None of these ",2);
        addQuestion(q72);

        Question q73 = new Question("Parachinar is the main town of: ?", "Khyber Agency ", "North Waziristan ", "South Waziristan ","None of these ",1);
        addQuestion(q73);

        Question q74 = new Question("One US Barrel oil is equal to:", "20 litres ", "30 litres ", "50 litres ","None of these ",4);
                addQuestion(q74);

        Question q75 = new Question("Ringgit is the currency unit of: ?", "Singapore ", "Philippines ", "Malaysia ","None of these ",3);
        addQuestion(q75);

        Question q76 = new Question("Pakistan is the Chairman of:?", "Non-Aligned Movement ", "SAARC ", "Group of 77","None of these ",2);
        addQuestion(q76);

        Question q77 = new Question("The First President of America who made an official visit to Pakistan was?", "Richard Nixon ", "Dwight D. Eishenhower ", "Lyndon B Johnson ","None of these ",2);
        addQuestion(q77);

        Question q78 = new Question("The ‘Aid to Pakistan Consortium” meet every year in: ?", "London ", "New York ", "Paris ","None of these ",3);
        addQuestion(q78);

        Question q79 = new Question("General Michael Hayden is the: ?", "President of Chile ", "Defense Secretary of United States "," Commander NATO’s force in Afghanistan ","None of these ",4);
        addQuestion(q79);

        Question q80= new Question("Which of the following International Organizations has no formal structure and Secretariat?", " Green Peace ", "D-8 ", "G-8 ","None of these ",3);
        addQuestion(q80);
        // Current Affairs 2009


        Question q81 = new Question("Who is Nicolas Sarkozy? ", "German Chancellor ", "Canadian President", "French President", "President of Georgia ",3);
        addQuestion(q81);

        Question q82 = new Question("What position Hu Jintao holds in China:?", "General Secretary of Communist Party ", "President of the country   ", "Both ‘a’ & ‘b’ ","Prime Minister of the country ",3);
        addQuestion(q82);

        Question q83 = new Question("Who is the president of World Bank? ", "Robert Brace Zorllick ", "Robert Bruce Gate ", "Robert Bruce Lohaf"," Bill Gates   ",1);
        addQuestion(q83);

        Question q84 = new Question("Where is the Headquarter of the Amnesty International located? ", "Geneva", "London", "Paris","New York ",2);
        addQuestion(q84);

        Question q85 = new Question("Asian Development Bank (ADB) was established in?", "1964", "196", "1968","None of these ",2);
        addQuestion(q85);

        Question q86 = new Question("Who were the three statesmen who formulated Non-Aligned Movement (NAM)? ", "Gandhi, Nasser, Tito", " Nehru, Nasser, Tito", "Chou-en-Lai, Bhutto, Nehru","Soe Karno, Nasser, Tito ",2);
        addQuestion(q86);

        Question q87 = new Question("The Permanent Secretariat of SAARC is established at:?", "Kathmandu", "Dhaka", "Dehli","Islamabad ",1);
        addQuestion(q87);

        Question q88 = new Question("Who was the founder of HAMAS in 1987:?", "Sheikh Ahmed Yassin", "Yasser Arafat", "Abu Nidal","None of these ",1);
        addQuestion(q88);

        Question q89 = new Question("How many official working languages are recognized by UNO? ", "8", "6", "4","None of these ",2);
        addQuestion(q89);

        Question q90= new Question("In which month does the UN General Assembly usually meet every year? ", "August", "September","   October","November ",2);
        addQuestion(q90);

        // Year 2009

        Question q91 = new Question("Which of the following countries have the power of veto in the General Assembly of UNO? ", "USA", "Russia   ", "China","All of these ",2);
        addQuestion(q91);

        Question q92 = new Question("The term of office of a judge of the International Court of Justice is? ", "5 years", "7 years ","9 years     ","None of these ",4);
        addQuestion(q92);

        Question q93 = new Question("Alliance among India, Germany, Japan and Brazil to support each other’s bid for permanent seat on UN Security Council is called:?","Alliance 4", "G 4 ", "Big 4 ","None of these ",3);
        addQuestion(q93);

        Question q94 = new Question("The Iran – Pakistan – India gas pipeline is also known as:?", "Friendly pipeline ", "Peace pipeline", "Great pipeline", "None of these",2);
        addQuestion(q94);

        Question q95 = new Question("The first parliamentary elections in Afghanistan were held in:?", "2004", "2005", "2006      ","None of these ",2);
        addQuestion(q95);

        Question q96 = new Question("Which is the National Flower of Pakistan? ", "Tulip ", "Rose", "Jasmine","None of these ",3);
        addQuestion(q96);

        Question q97 = new Question("After ‘Pushtuns’ the largest-ethnic group in Afghanistan is:?", "Uzbeks", "Hazaras", "Tajiks      ","None of these ",3);
        addQuestion(q97);

        Question q98 = new Question("The Capital of Argentina is:?", "Columbia", "Barcelona", "Buenos Aires","Peru ",3);
        addQuestion(q98);

        Question q99 = new Question("Which is the largest country in Africa:?", "Sudan", "Nigeria", "Libya","None of these ",1);
                addQuestion(q99);

        Question q100= new Question("Name the currency of Sri Lanka? ", "Rupiyah ", " Lek", "Ringgit","None of these ",1);
        addQuestion(q100);   
    }

    // Method to insert data
    private void addQuestion(Question question) {
        ContentValues cv = new ContentValues();
        cv.put(QuizContract.Questions_CurrentAffairs.COLUMN_QUESTION, question.getQuestion());
        cv.put(QuizContract.Questions_CurrentAffairs.COLUMN_OPTIONA1, question.getOption1());
        cv.put(QuizContract.Questions_CurrentAffairs.COLUMN_OPTIONB1, question.getOption2());
        cv.put(QuizContract.Questions_CurrentAffairs.COLUMN_OPTIONC1, question.getOption3());
        cv.put(QuizContract.Questions_CurrentAffairs.COLUMN_OPTIOND1, question.getOption4());
        cv.put(QuizContract.Questions_CurrentAffairs.COLUMN_ANSWER_NR, question.getAnswerNr());
        db.insert(QuizContract.Questions_CurrentAffairs.TABLE_NAME, null, cv);
    }

//      Gets all questions.   
//      Method to Retrieve multiple data from database;
    public List<Question> getAllQuestions() {
        List<Question> questionList = new ArrayList<>();
        db = getReadableDatabase();
        //Cursor c = db.rawQuery("SELECT * FROM " + QuizContract.QuestionsTable.TABLE_NAME, null);
        String table=QuizContract.Questions_CurrentAffairs.TABLE_NAME;
        String[] columns = null;
        String selection = null;
        String[] selectionArgs = null;
        String groupBy = null ;
        String having = null ;
        String orderBy = null ;
//        String limit= "0,20";
        String limit= null;   
        Cursor c = db.query(table,columns,selection,selectionArgs,groupBy,having,orderBy,limit);

        if (c.moveToFirst()) {
            do {
                Question question = new Question();
                question.setQuestion(c.getString(c.getColumnIndex(QuizContract.Questions_CurrentAffairs.COLUMN_QUESTION)));
                question.setOption1(c.getString(c.getColumnIndex(QuizContract.Questions_CurrentAffairs.COLUMN_OPTIONA1)));
                question.setOption2(c.getString(c.getColumnIndex(QuizContract.Questions_CurrentAffairs.COLUMN_OPTIONB1)));
                question.setOption3(c.getString(c.getColumnIndex(QuizContract.Questions_CurrentAffairs.COLUMN_OPTIONC1)));
                question.setOption4(c.getString(c.getColumnIndex(QuizContract.Questions_CurrentAffairs.COLUMN_OPTIOND1)));
                question.setAnswerNr(c.getInt(c.getColumnIndex(QuizContract.Questions_CurrentAffairs.COLUMN_ANSWER_NR)));
                questionList.add(question);
            } while (c.moveToNext());
        }   
        c.close();
        return questionList;
    }    
}

最佳答案

我必须为每个活动创建单独的游标吗?


是;但是,对于具有活动的代码,它不使用游标,它使用的问题对象列表(List<Question>)源自已关闭并已弃置的游标。


  如何进行?


根据代码,您可以当前了解事物的工作方式。您将专门为另一个主题创建几乎相同的方法,但是从长远来看,通过重新考虑数据库设计(架构),您可能会发现事情变得更容易。

真的每个科目都需要一张桌子吗?您似乎已经对各章感到困惑,我想您真的不希望每个主题的每章都有一个表格,即25个表格。

我建议针对每个具体元素/实体/事物使用表格。也就是说,您提到的主题,章节,问题和答案都与层次结构相关。


主题将是具体的,因为它具有与名称相同的属性。
一章将具有名称(或将其与其他章区分开的名称),并且还将与一个且仅一个主题相关。
问题将首先是用户面临的问题,它将与章节相关,因此隐含地针对主题。
答案将与问题相关,它将具有将显示给用户的数据,它将是相关问题的正确答案,也可能不是答案。


注意,在上文中,除了上述内容具有层次结构之外,没有提及数量,在该层次结构中,根据主题的期望,其他实体与上述单个实体相关。这些是一对多关系。这样,可以对数据进行结构化,而不必施加任何限制,除了非常明显的层次结构。

我建议为上述每个实体考虑一个表格。那是 :-

具有的主题表


主题列
用于数字标识符的列


rowid的别名非常适合,即使用INTEGER PRIMARY KEY定义的列(无需AUTOINCREMENT即可,因为效率低下并且不需要)



一章表


向用户显示的章节名称(区分符)列(例如,第1章(输入1即可))
一列,用于存储与该章相关的主题(属于),即主题的数字标识符。
章节数字标识符的列。


所有问题的问题表


问题本身的列。
问题所在章节的专栏
问题数字标识符的列


所有答案的答案表


答案列。
用于指示这是正确还是不正确答案的列
答案所涉及的问题的列。
可选地,是答案数字标识符的列。


因此结构可能是:-

CREATE TABLE IF NOT EXISTS subject (_id INTEGER PRIMARY KEY, subject TEXT UNIQUE);
CREATE TABLE IF NOT EXISTS chapter (_id INTEGER PRIMARY KEY, subject_reference, chapter TEXT UNIQUE);
CREATE TABLE IF NOT EXISTS question (_id INTEGER PRIMARY KEY, chapter_reference INTEGER, question TEXT UNIQUE);
CREATE TABLE IF NOT EXISTS answer (_id INTEGER PRIMARY KEY, question_reference, answer TEXT, correct_flag INTEGER DEFAULT 0);


如果要使用外键,则以上内容可能是:-

CREATE TABLE IF NOT EXISTS subject (_id INTEGER PRIMARY KEY, subject TEXT UNIQUE);

CREATE TABLE IF NOT EXISTS chapter (
    _id INTEGER PRIMARY KEY, 
    subject_reference INTEGER NOT NULL REFERENCES subject(_id) ON DELETE CASCADE ON UPDATE CASCADE, 
    chapter TEXT UNIQUE
);

CREATE TABLE IF NOT EXISTS question (
    _id INTEGER PRIMARY KEY, 
    chapter_reference INTEGER NOT NULL REFERENCES chapter(_id) ON DELETE CASCADE ON UPDATE CASCADE, 
    question TEXT UNIQUE
);

CREATE TABLE IF NOT EXISTS answer (
    _id INTEGER PRIMARY KEY, 
    question_reference INTEGER NOT NULL REFERENCES question(_id) ON DELETE CASCADE ON UPDATE CASCADE, 
    answer TEXT, 
    correct_flag INTEGER DEFAULT 0 /*<<<< deafult to not the correct answer */
);


该结构不仅可以满足章节的需要,而且添加/删除主题和章节将非常简单,它可以提供更大的灵活性,因为每个主题每个章节没有固定的章节,每个问题都没有答案。

例如,考虑添加(插入)以下数据(有限)

INSERT INTO subject VALUES(1,'Current Affairs'),(2,'Islamic Studies'),(3,'Historical'),(4,'Future'),(5,'and so on');
INSERT INTO subject (subject) VALUES ('another subject with id auto generated'),('yet another subject with id auto generated');
INSERT INTO chapter VALUES
    (1,1,'CA Chapter1'),(2,1,'CA Chapter2'),(3,1,'CA Chapter3'),(4,1,'CA Chapter4'),(5,1,'CA Chapter5')
    ,(11,2,'IS Chapter1'),(12,2,'IS Chapter2'),(13,2,'IS Chapter3'),(14,2,'IS Chapter4'),(15,2,'IS Chapter5')
    ,(21,3,'Hist Chapter1'),(22,3,'Hist Chapter2'),(23,3,'Hist Chapter3'),(24,3,'Hist Chapter4'),(25,3,'Hist Chapter5')
    ,(31,4,'Fut Chapter1'),(32,4,'Fut Chapter2'),(33,4,'Fut Chapter3'),(34,4,'Fut Chapter4'),(35,4,'Fut Chapter5')
;
INSERT INTO chapter (subject_reference, chapter) VALUES
    (5,'ASO Chapter1'),(5,'ASO Chapter2')
;
WITH cte_subject AS (SELECT _id FROM subject WHERE subject LIKE 'and so on')
INSERT INTO chapter (subject_reference, chapter) VALUES((SELECT * FROM cte_subject),'Chapter3'),((SELECT * FROM cte_subject),'Chapter4'),((SELECT * FROM cte_subject),'Chapter5')
;

INSERT INTO question VALUES 
  /* Chapter 1 */
    (1,1,'The worlds oldest international human rights organization is?')
    ,(2,1,'CA CHP1 Q2'),(3,1,'CA CHP1 Q3'),(4,1,'CA CHP1 Q4'),(5,1,'CA CHP1 Q5'),(6,1,'CA CHP1 Q6')
    ,(7,1,'CA CHP1 Q7'),(8,1,'CA CHP1 Q8') /* etc */
    /* Chapter 2 */
    ,(101,2,'The constitution of European union has not been ratified by?')
    ,(102,2,'CA CHP2 Q2'),(103,2,'CA CHP2 Q3'),(104,2,'CA CHP2 Q4'),(105,2,'CA CHP2 Q5'),(106,2,'CA CHP2 Q6')
    ,(107,2,'CA CHP2 Q7'),(108,2,'CA CHP2 Q8') /* etc */
;
INSERT INTO answer (question_reference,answer,correct_flag) VALUES
    (1,'amnesty international',null),(1,'freedom house',null),(1,'anti slavery',1),(1,'non of these',0)
    ,(2,'amnesty international',1),(2,'freedom house',null),(2,'anti slavery',0),(2,'non of these',0)
    ,(3,'amnesty international',1),(3,'freedom house',null),(3,'anti slavery',0),(3,'non of these',0)
    ,(4,'amnesty international',1),(4,'freedom house',null),(4,'anti slavery',0),(4,'non of these',0)
    ,(5,'amnesty international',1),(5,'freedom house',null),(5,'anti slavery',0),(5,'non of these',0)
    ,(6,'amnesty international',1),(6,'freedom house',null),(6,'anti slavery',0),(6,'non of these',0)

    ,(101,'amnesty international',null),(101,'freedom house',null),(101,'anti slavery',1),(101,'non of these',0),(101,'A Fifth answer',0)
    ,(102,'first answer',1),(102,'second answer',null),(102,'third answer',0)
    ,(103,'amnesty international',1),(103,'freedom house',null),(103,'anti slavery',0),(103,'non of these',0)
    ,(104,'amnesty international',1),(104,'freedom house',null)
    ,(105,'amnesty international',1),(105,'freedom house',null),(105,'anti slavery',0),(105,'non of these',0)
    ,(106,'amnesty international',1),(106,'freedom house',null),(106,'anti slavery',0),(106,'non of these',0)
;



注意,为方便起见,已重复了许多数据。


使用以上数据,假设您想获取主题中某个章节要显示的问题和答案,那么您可以基于以下查询(作为一种可能性):

SELECT subject, chapter, question, group_concat(answer,'    ') AS answers 
FROM chapter 
    JOIN subject ON subject._id = chapter.subject_reference
    JOIN question ON question.chapter_reference = chapter._id
    JOIN answer ON answer.question_reference = question._id
WHERE 
    subject LIKE 'Current%' /*<<<<< value passed to the query */
    AND chapter LIKE '%Chapter2%'/*<<<<< value passed to the query */
GROUP BY question._id
ORDER BY chapter._id,question._id
;


这将导致:-

enter image description here

一个类似的查询,但是这次基于主题和章节ID,但是这次是针对第一主题和第一章(使用ID通常会更容易,更有效地使用):-

SELECT subject, chapter, question, group_concat(answer,'    ') AS answers 
FROM chapter 
    JOIN subject ON subject._id = chapter.subject_reference
    JOIN question ON question.chapter_reference = chapter._id
    JOIN answer ON answer.question_reference = question._id
WHERE 
    subject._id = 1 /*<<<<< value passed to the query */
    AND chapter._id = 1 /*<<<<< value passed to the query */
GROUP BY question._id
ORDER BY chapter._id,question._id
;


会导致:-

enter image description here

您可以轻松地进行一项活动,该活动允许选择主题/章节(例如,从微调器中选择主题,然后驱动第二个微调器以选择章节),然后向用户提供相关的问题答案。

工作实例

一个有效的例子可以在SO59311624Quiz上找到

作为初次品尝时的品尝者:-

enter image description here

选择第2章的结果为:-

enter image description here

选择主题其他内容会导致:-

enter image description here

关于java - 如何使用sqlite制作android测验应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59311624/

相关文章:

java switch语句机制

java - 如何将标准 Java 类型映射到 SQL 类型?

Java:IllegalStateArgument 的 HttpURLConnection 问题:已经连接

android - 无法解决谷歌服务依赖

javascript - 如何在 Strapi 中发布关系

sqlite - 保存选择语句以供以后使用

java - SQLite 与 Java web 启动(在 JNLP 中)怎么样?

java - 当我的电脑刚刚安装x64 jdk7时,如何使用x86 jdk构建代码

android - 未知权限 android.permission.RECORD_VIDEO

android - XStream 和 Proguard