-1

Can anyone help me when I click on my Quiz button, the app stops when running it on the emulator. I got code that I use from the internet but with the tutorial the quiz starts when the app is opened. With my app the person first need to click on the quiz button and then the quiz must start.

MainActivity:

package app.mobiledevicesecurity;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {
DatabaseHelper myDb;
private static Button readbtn;
private static Button quizbtn;
private static Button scoresbtn;
private static Button settingsbtn;
private static Button helpbtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myDb = new DatabaseHelper(this);
    myDb.insertData();

     OnClickReadButtonListener();
     OnClickQuizButtonListener();
     OnClickScoresButtonListener();
     OnClickSettingsButtonListener();
     OnClickHelpButtonListener();


}

public void OnClickReadButtonListener() {
    readbtn = (Button) findViewById(R.id.readbutton);
    readbtn.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent("app.mobiledevicesecurity.Read_Category");
                    startActivity(intent);
                }
            }
    );
}

public void OnClickQuizButtonListener() {
    quizbtn = (Button) findViewById(R.id.quizbutton);
    quizbtn.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
                    startActivity(intent);
                }
            }
    );
}

public void OnClickScoresButtonListener() {
    scoresbtn = (Button) findViewById(R.id.scoresbutton);
    scoresbtn.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent("app.mobiledevicesecurity.Scores");
                    startActivity(intent);
                }
            }
    );
}

public void OnClickSettingsButtonListener() {
    settingsbtn = (Button) findViewById(R.id.settingsbutton);
    settingsbtn.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent("app.mobiledevicesecurity.Settings");
                    startActivity(intent);
                }
            }
    );
}

public void OnClickHelpButtonListener() {
    helpbtn = (Button) findViewById(R.id.helpbutton);
    helpbtn.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent("app.mobiledevicesecurity.Help");
                    startActivity(intent);
                }
            }
    );
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

Question:

     package app.mobiledevicesecurity;

/**
 * Created by Martin on 2015/08/28.
 */
import android.app.Activity;
public class Question extends Activity {
    private int ID;
    private String QUESTION;
    private String OPTA;
    private String OPTB;
    private String OPTC;
    private String ANSWER;
    public Question() {
        ID = 0;
        QUESTION = "";
        OPTA = "";
        OPTB = "";
        OPTC = "";
        ANSWER = "";
    }
    public Question(String qUESTION, String oPTA, String oPTB, String oPTC,
                    String aNSWER) {
        QUESTION = qUESTION;
        OPTA = oPTA;
        OPTB = oPTB;
        OPTC = oPTC;
        ANSWER = aNSWER;
    }
    public int getID() {
        return ID;
    }
    public String getQUESTION() {
        return QUESTION;
    }
    public String getOPTA() {
        return OPTA;
    }
    public String getOPTB() {
        return OPTB;
    }
    public String getOPTC() {
        return OPTC;
    }
    public String getANSWER() {
        return ANSWER;
    }
    public void setID(int id) {
        ID = id;
    }
    public void setQUESTION(String qUESTION) {
        QUESTION = qUESTION;
    }
    public void setOPTA(String oPTA) {
        OPTA = oPTA;
    }
    public void setOPTB(String oPTB) {
        OPTB = oPTB;
    }
    public void setOPTC(String oPTC) {
        OPTC = oPTC;
    }
    public void setANSWER(String aNSWER) {
        ANSWER = aNSWER;
    }

   }

QuizHelper:

package app.mobiledevicesecurity;

/**
 * Created by Martin on 2015/08/28.
 */
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class QuizHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "mathsone";
    // tasks table name
    private static final String TABLE_QUEST = "quest";
    // tasks Table Columns names
    private static final String KEY_ID = "qid";
    private static final String KEY_QUES = "question";
    private static final String KEY_ANSWER = "answer"; // correct option
    private static final String KEY_OPTA = "opta"; // option a
    private static final String KEY_OPTB = "optb"; // option b
    private static final String KEY_OPTC = "optc"; // option c
    private SQLiteDatabase dbase;
    public QuizHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        dbase = db;
        String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
                + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
                + " TEXT, " + KEY_ANSWER + " TEXT, " + KEY_OPTA + " TEXT, "
                + KEY_OPTB + " TEXT, " + KEY_OPTC + " TEXT)";
        db.execSQL(sql);
        addQuestion();
        // db.close();
    }
    private void addQuestion() {
        Question q1 = new Question("5+2 = ?", "7", "8", "6", "7");
        this.addQuestion(q1);
        Question q2 = new Question("2+18 = ?", "18", "19", "20", "20");
        this.addQuestion(q2);
        Question q3 = new Question("10-3 = ?", "6", "7", "8", "7");
        this.addQuestion(q3);
        Question q4 = new Question("5+7 = ?", "12", "13", "14", "12");
        this.addQuestion(q4);
        Question q5 = new Question("3-1 = ?", "1", "3", "2", "2");
        this.addQuestion(q5);
        Question q6 = new Question("0+1 = ?", "1", "0", "10", "1");
        this.addQuestion(q6);
        Question q7 = new Question("9-9 = ?", "0", "9", "1", "0");
        this.addQuestion(q7);
        Question q8 = new Question("3+6 = ?", "8", "7", "9", "9");
        this.addQuestion(q8);
        Question q9 = new Question("1+5 = ?", "6", "7", "5", "6");
        this.addQuestion(q9);
        Question q10 = new Question("7-5 = ?", "3", "2", "6", "2");
        this.addQuestion(q10);
        Question q11 = new Question("7-2 = ?", "7", "6", "5", "5");
        this.addQuestion(q11);
        Question q12 = new Question("3+5 = ?", "8", "7", "5", "8");
        this.addQuestion(q12);
        Question q13 = new Question("0+6 = ?", "7", "6", "5", "6");
        this.addQuestion(q13);
        Question q14 = new Question("12-10 = ?", "1", "2", "3", "2");
        this.addQuestion(q14);
        Question q15 = new Question("12+2 = ?", "14", "15", "16", "14");
        this.addQuestion(q15);
        Question q16 = new Question("2-1 = ?", "2", "1", "0", "1");
        this.addQuestion(q16);
        Question q17 = new Question("6-6 = ?", "6", "12", "0", "0");
        this.addQuestion(q17);
        Question q18 = new Question("5-1 = ?", "4", "3", "2", "4");
        this.addQuestion(q18);
        Question q19 = new Question("4+2 = ?", "6", "7", "5", "6");
        this.addQuestion(q19);
        Question q20 = new Question("5+1 = ?", "6", "7", "5", "6");
        this.addQuestion(q20);
        Question q21 = new Question("5-4 = ?", "5", "4", "1", "1");
        this.addQuestion(q21);
        // END
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST);
        // Create tables again
        onCreate(db);
    }
    // Adding new question
    public void addQuestion(Question quest) {
        // SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_QUES, quest.getQUESTION());
        values.put(KEY_ANSWER, quest.getANSWER());
        values.put(KEY_OPTA, quest.getOPTA());
        values.put(KEY_OPTB, quest.getOPTB());
        values.put(KEY_OPTC, quest.getOPTC());
        // Inserting Row
        dbase.insert(TABLE_QUEST, null, values);
    }
    public List<Question> getAllQuestions() {
        List<Question> quesList = new ArrayList<Question>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_QUEST;
        dbase = this.getReadableDatabase();
        Cursor cursor = dbase.rawQuery(selectQuery, null);
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Question quest = new Question();
                quest.setID(cursor.getInt(0));
                quest.setQUESTION(cursor.getString(1));
                quest.setANSWER(cursor.getString(2));
                quest.setOPTA(cursor.getString(3));
                quest.setOPTB(cursor.getString(4));
                quest.setOPTC(cursor.getString(5));
                quesList.add(quest);
            } while (cursor.moveToNext());
        }
        // return quest list
        return quesList;
    }
}

Result:

package app.mobiledevicesecurity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class Result extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        TextView textResult = (TextView) findViewById(R.id.textResult);
        Bundle b = getIntent().getExtras();
        int score = b.getInt("score");
        textResult.setText("Your score is " + " " + score + ". Thanks for playing my game.");
    }
    public void playagain(View o) {
        Intent intent = new Intent(this, Quiz.class);
        startActivity(intent);
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="app.mobiledevicesecurity" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Read_Category"
            android:label="@string/title_activity_read__category" >
            <intent-filter>
                <action android:name="app.mobiledevicesecurity.Read_Category" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Quiz"
            android:label="@string/title_activity_quiz" >
            <intent-filter>
                <action android:name="app.mobiledevicesecurity.Quiz" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Scores"
            android:label="@string/title_activity_scores" >
            <intent-filter>
                <action android:name="app.mobiledevicesecurity.Scores" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Settings"
            android:label="@string/title_activity_settings" >
            <intent-filter>
                <action android:name="app.mobiledevicesecurity.Settings" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Help"
            android:label="@string/title_activity_help" >
            <intent-filter>
                <action android:name="app.mobiledevicesecurity.Help" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Result"
            android:label="@string/title_activity_result" >
        </activity>
    </application>

</manifest>

Why does the app stop/chrash Any help?

Quiz:

package app.mobiledevicesecurity;

import java.util.List;
import java.util.Timer;
import java.util.concurrent.TimeUnit;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Quiz extends Activity {
    List<Question> quesList;
    int score = 0;
    int qid = 0;
    Question currentQ;
    TextView txtQuestion, times, scored;
    Button button1, button2, button3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        QuizHelper db = new QuizHelper(this);  // my question bank class
        quesList = db.getAllQuestions();  // this will fetch all quetonall questions
        currentQ = quesList.get(qid); // the current question
        txtQuestion = (TextView) findViewById(R.id.txtQuestion);
        // the textview in which the question will be displayed
        // the three buttons,
        // the idea is to set the text of three buttons with the options from question bank
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);
        // the textview in which score will be displayed
        scored = (TextView) findViewById(R.id.score);
        // the timer
        times = (TextView) findViewById(R.id.timers);
        // method which will set the things up for our game
        setQuestionView();
        times.setText("00:02:00");
        // A timer of 60 seconds to play for, with an interval of 1 second (1000 milliseconds)
        CounterClass timer = new CounterClass(60000, 1000);
        timer.start();
        // button click listeners
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // passing the button text to other method
                // to check whether the anser is correct or not
                // same for all three buttons
                getAnswer(button1.getText().toString());
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAnswer(button2.getText().toString());
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAnswer(button3.getText().toString());
            }
        });
    }
    public void getAnswer(String AnswerString) {
        if (currentQ.getANSWER().equals(AnswerString)) {
            // if conditions matches increase the int (score) by 1
            // and set the text of the score view
            score++;
            scored.setText("Score : " + score);
        } else {
            // if unlucky start activity and finish the game
            Intent intent = new Intent(Quiz.this,
                    Result.class);
            // passing the int value
            Bundle b = new Bundle();
            b.putInt("score", score); // Your score
            intent.putExtras(b); // Put your score to your next
            startActivity(intent);
            finish();
        }
        if (qid < 20) {
            // if questions are not over then do this
            currentQ = quesList.get(qid);
            setQuestionView();
        } else {
            // if over do this
            Intent intent = new Intent(Quiz.this,
                    Result.class);
            Bundle b = new Bundle();
            b.putInt("score", score); // Your score
            intent.putExtras(b); // Put your score to your next
            startActivity(intent);
            finish();
        }
    }
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @SuppressLint("NewApi")
    public class CounterClass extends CountDownTimer {
        public CounterClass(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }
        @Override
        public void onFinish() {
            times.setText("Time is up");
        }
        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
            long millis = millisUntilFinished;
            String hms = String.format(
                    "%02d:%02d:%02d",
                    TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis)
                            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
                            .toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis)
                            - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
                            .toMinutes(millis)));
            System.out.println(hms);
            times.setText(hms);
        }
    }
    private void setQuestionView() {
        // the method which will put all things together
        txtQuestion.setText(currentQ.getQUESTION());
        button1.setText(currentQ.getOPTA());
        button2.setText(currentQ.getOPTB());
        button3.setText(currentQ.getOPTC());
        qid++;
    }
    }

Logcat:

08-28 13:35:22.081  30049-30049/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
08-28 13:35:22.148  30049-30056/? E/art﹕ Failed writing handshake bytes (-1 of 14): Broken pipe
08-28 13:35:22.148  30049-30056/? I/art﹕ Debugger is no longer active
08-28 13:35:22.397  30049-30066/? D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
08-28 13:35:22.400  30049-30049/? D/﹕ HostConnection::get() New Host Connection established 0xb3eb3f90, tid 30049
08-28 13:35:22.410  30049-30061/? I/art﹕ Background partial concurrent mark sweep GC freed 383(32KB) AllocSpace objects, 0(0B) LOS objects, 33% free, 8MB/12MB, paused 2.886ms total 102.170ms
08-28 13:35:22.421  30049-30049/? D/Atlas﹕ Validating map...
08-28 13:35:22.526  30049-30066/? D/﹕ HostConnection::get() New Host Connection established 0xb3ff7270, tid 30066
08-28 13:35:22.543  30049-30066/? I/OpenGLRenderer﹕ Initialized EGL, version 1.4
08-28 13:35:22.611  30049-30066/? D/OpenGLRenderer﹕ Enabling debug mode 0
08-28 13:35:22.618  30049-30066/? W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-28 13:35:22.618  30049-30066/? W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb3f1ab40, error=EGL_SUCCESS
08-28 13:35:23.202  30049-30049/app.mobiledevicesecurity I/Choreographer﹕ Skipped 34 frames!  The application may be doing too much work on its main thread.
08-28 13:35:29.269  30049-30049/app.mobiledevicesecurity D/AndroidRuntime﹕ Shutting down VM
08-28 13:35:29.269  30049-30049/app.mobiledevicesecurity E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: app.mobiledevicesecurity, PID: 30049
    java.lang.RuntimeException: Unable to start activity ComponentInfo{app.mobiledevicesecurity/app.mobiledevicesecurity.Quiz}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
            at app.mobiledevicesecurity.Quiz.setQuestionView(Quiz.java:135)
            at app.mobiledevicesecurity.Quiz.onCreate(Quiz.java:45)
            at android.app.Activity.performCreate(Activity.java:5990)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
08-28 13:35:36.669  30049-30049/app.mobiledevicesecurity I/Process﹕ Sending signal. PID: 30049 SIG: 9
Martin Park
  • 11
  • 1
  • 7
  • Can you show the code of app.mobiledevicesecurity.Quiz and mark the line 135 – Jens Aug 28 '15 at 11:39
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Jens Aug 28 '15 at 11:41
  • Really, its all in the logcat: `Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at app.mobiledevicesecurity.Quiz.setQuestionView(Quiz.java:135) at app.mobiledevicesecurity.Quiz.onCreate(Quiz.java:45)` Check `setQuestionView` you have a `setText()` method that you call on a null object (either not initialized or return null/not found from `findViewById` – Evripidis Drakos Aug 28 '15 at 11:41
  • Added the quiz code. I am new to this. How can I fix it. I now busy experimenting with android studio – Martin Park Aug 28 '15 at 11:47
  • Line 135:txtQuestion.setText(currentQ.getQUESTION()); – Martin Park Aug 28 '15 at 11:51

3 Answers3

1

Check this line :

txtQuestion = (TextView) findViewById(R.id.txtQuestion); // Line number : 33

Be sure txtQuestion TextView available in your activity_main.xml.

Your app not getting txtQuestion from your activity_main.xml, so you get null pointer exception at :

txtQuestion.setText(currentQ.getQUESTION()); // Line number : 135
SANAT
  • 8,489
  • 55
  • 66
0

In your Quiz activity on line no 29, you have code,

        setContentView(R.layout.activity_main);

Where you are inflating the XML file of MainActivity rather than that it should be XML designed for Quiz Activity, which is why it doesn't find the txtQuestion and gives null pointer exception.

Rohit Jagtap
  • 1,660
  • 1
  • 14
  • 12
0

Please Check Quiz file line number 135 txtQuestion is NULL or Check currentQ is NULL

Tabassum Latif
  • 247
  • 2
  • 15