简体   繁体   中英

How to make android quiz application using sqlite?

I am working on android quiz application. My goal is to make quiz app which consists of multiple choice questions of 5 subjects.

Each subjects has 5 chapters and each chapter has 20 multiple choice questions.

So far I have been able to make android application which starts quiz of multiple choice questions of all chapters of a subject. I did it by making a table in sqlite.

The multiple choice questions of all chapters are being displayed in one activity. I wanted my app to start quiz for each chapter separately. Do I have to create separate cursor for each activity? How to proceed?

my code

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

Do I have to create separate cursor for each activity?

Yes; BUT, with the code you have the Activity doesn't use the Cursor it uses a List of Question objects ( List<Question> ) derived from a Cursor which is closed and this disposed of.

How to proceed?

With you current view of how things are going to work, based upon the code. You would create a near identical method specifically for another subject BUT you would likely find things easier in the long run by reconsidering the database design (schema).

Do really really need a table per subject? You already appear to be flummexed by chapters I guess you don't really want to have a table per chapter per subject ie 25 tables.

I'd propose using a table per concrete element/entity/thing. That is, you mention Subjects , Chapters , Questions and Answers which are all related in a hierarchy.

  • A subject will be concrete as it will have the same properties primarilly a name.
  • A Chapter will have a name (or something that distinguishes it from other chapters), it will also be related to a one and only one of the subjects .
  • A Question will primarilly be the question that the user is confronted with, it will be related to a chapter and thus implicitly realted to a subject .
  • An Answer will be related to a question, it will have data that will be presented to the user it will be either the correct answer for the related question or it will not be the answer.

Note that in the above no mention has been made of quantities other than the above has a hierarchy in which with the expect of a subject the other entities relate to a single entity above. These are 1 to Many relationships. As such the data could be structured without imposing restrictions other than the pretty obvious hiearchy.

I'd suggest considering a table for each entity as above. That is :-

A subject table with

  • A column for the Subject
  • A column for a numeric identifier
    • an alias of the rowid very much suits ie a column defined using INTEGER PRIMARY KEY (without AUTOINCREMENT as that is inefficient and not needed)

A chapter table with

  • A column for the chapter name(distinguisher) presented to the user (eg Chapter 1 (stroing 1 could be sufficient))
  • A column to store the subject to which the chapter relates (belongs to) ie the subject's numeric identifier.
  • A column for the chapter's numeric identifier.

A question table for ALL questions with

  • A column for the question itself.
  • A column for the chapter to which the question realtes
  • A column for the question's numeric identifier

An answer table for ALL of the answers with

  • A column for the answer.
  • A column for indicating if this is the correct or incorrect answer
  • A column for the question to which the answer relates.
  • Optionaly, a column for the answer's numeric identifier.

So the strutcture could be :-

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);

If Foreign Keys were to be utilised then the above could be :-

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 */
);

Not only would the structure cater for chapter, it would be very simple to add/remove subjects and chapters it allows far more flexibility as there would be no fixed chapters per subject questions per chapter or answers per question.

As an example consider the following data (limited) added (inserted)

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)
;
  • Note for convenience much of the data has been repeated.

Using the above data assume that you want to get the questions and answers to be displayed for a chapter within a subject then you could have a query based upon (as one a numerous possibilities) :-

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
;

This would result in :-

在此处输入图片说明

A similar query but this time based upon subject and chapter id 's but this time for the first subject and the first chapter ( id 's would typically be easier and more efficient to work with) :-

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
;

would result in :-

在此处输入图片说明

You could easily have just the one activity that allows selection of the subject/chapter (eg selecting the subject from a spinner which then drives a second spinner that allows the chapter to be selected) that then provides the user with the relevant set of questions answers.

Working Example

A working example can be found at SO59311624Quiz

As a taster when first run :-

在此处输入图片说明

Select Chapter2 results in :-

在此处输入图片说明

Selecting the Subject Other stuff results in :-

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM