App crashes when I try to set the TextView - java

I have this class I've named Scoreboard that looks like this:
public class Scoreboard {
private int mScore = 0;
private int mHighScore = 0;
public void addPoint() {
mScore += 1;
}
public int getHighScore() {
return mHighScore;
}
public void setHighScore(int highScore) {
mHighScore = highScore;
}
public int getScore() {
return mScore;
}
public void setScore(int score) {
mScore = score;
}
}
And I have a piece of code in my acticity that manipulates this class everytime the user passes a ball through a rectangle's gap and changes the TextView accordingly to show the user the score:
//Keeps track of score
if (rectWhite1.getTheRight() > Math.round(mBallPos.x) - 5 && rectWhite1.getTheRight() < Math.round(mBallPos.x) + 5) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mScoreboard.addPoint();
scoreTextView.setText(mScoreboard.getScore());
}
});
Log.d(TAG, "If statement has been run3333!!!");
}
if (rectWhite2.getTheRight() > Math.round(mBallPos.x) - 5 && rectWhite2.getTheRight() < Math.round(mBallPos.x) + 5) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mScoreboard.addPoint();
scoreTextView.setText(mScoreboard.getScore());
}
});
Log.d(TAG, "If statement has been run2222!!!");
}
if (rectWhite3.getTheRight() > Math.round(mBallPos.x) - 5 && rectWhite3.getTheRight() < Math.round(mBallPos.x) + 5) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mScoreboard.addPoint();
scoreTextView.setText(mScoreboard.getScore());
}
});
Log.d(TAG, "If statement has been run1111!!!");
}
Everytime I run the app it crashes whenever I try to use any method pertaining to the Scoreboard class I made. When I try to add a point it crashes, when I try to get the current score it crashes, etc. So my question is how do I avoid this from happening and change the score dynamically?

Related

Second method runs only after I press button twice

The problem is that the method runs only after I press button second time, but the goal is to work for both methods one after another when I press button for the first time.
The first method is runThreadWork(); and after that runThreadRest(); when the first is completed.
This is the part for the button.
btnStartTimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(workMinutes > 0 || workSeconds > 0){
runThreadWork();
}else if(isTimerCompleted){
runThreadRest();
}
}
});
That's is the part for the method, basically both methods are the same in logic, but only change are variables for values, except TextView variable isn't changed for both methods, I want to use one TextView to show the output from both methods one after another.
private void runThreadWork() {
new Thread() {
public void run() {
while (workMinutes > 0 || workSeconds > 0) {
while (workSeconds > 0) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
workSeconds--;
String timeFormatedCountDownWork = String.format("Work time: " + "%02d:%02d", workMinutes, workSeconds);
txtTimeCountDown.setText(timeFormatedCountDownWork);
if(workSeconds == 0 && workMinutes > 0){
workMinutes--;
workSeconds = 60;
}
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}.start();
isTimerCompleted = true;
}

How to use runOnUiThread for updating a TextView

I have two threads in my main activity from Runner and start them with clicking a button. The only thing thy do is count up. I want to update two TextViews wit the current count from ech thread. When i start my app and click my button, the app crashed.
The code run perfektly in the console.
The class Runner is only used for the counting. I want to Update the two TextViews after each passage in the methode running().
public class Runner extends Activity implements Runnable {
int count = 0;
String name;
public Runner(String name) {
super();
this.name = name;
}
public void warten() throws InterruptedException {
int zahl = (int) (Math.random() * 500) + 500;
Thread.sleep(zahl);
}
public void running() throws InterruptedException {
for(int i = 0; i < 10; i++) {
warten();
count++;
System.out.println(name + " ist bei: " + count);
if(count == 10) {
System.out.println(name + " IST FERTIG");
}
runOnUiThread(new UiThread(name, count));
}
}
public void run() {
try {
running();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The class UiThread should be the main thread for updating the UI.
public class UiThread extends Activity implements Runnable {
String name;
int count;
TextView textView1;
TextView textView2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
textView1 = findViewById(R.id.textView2);
textView2 = findViewById(R.id.textView3);
}
public UiThread(String name, int count){
this.name = name;
this.count = count;
}
#Override
public void run() {
if(name == "thread1"){
textView1.setText("thread1 ist bei: " + count);
}else{
textView2.setText("thread2 ist bei: " + count);
}
}
}
i would recommend you checkout this guide on android threading docs.
You can't initialize an activity class, you only add it to the manifest, doing so will lead to a null context. So remove the constructor in your UiThread class.
Also you do not need for your runner class to extend Activity. Pass an instance of Activity inorder to use the runOnUiThread() method.
Here is an example of how the UiTHread class should be.
public class UiThread extends Activity {
public TextView textView1;
public TextView textView2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
textView1 = findViewById(R.id.textView2);
textView2 = findViewById(R.id.textView3);
startThreads();
}
private void startThreads(){
// Initialize the runnable class passing this activity context.
Runner runner = new Runner(this);
Thread thread1 = new Thread(runner, "thread1");
Thread thread2 = new Thread(runner, "thread2");
thread1.start();
thread2.start();
}
}
the runner class
public class Runner implements Runnable {
private int count = 0;
private UiThread context;
public Runner(UiThread activityContext) {
this.context = activityContext;
}
public void warten() throws InterruptedException {
int zahl = (int) (Math.random() * 500) + 500;
Thread.sleep(zahl);
}
public void running() throws InterruptedException {
for(int i = 0; i < 10; i++) {
warten();
count++;
System.out.println(Thread.currentThread().getName() + " ist bei: " + count);
if(count == 10) {
System.out.println(Thread.currentThread().getName() + " IST FERTIG");
}
// update text views from the main thread.
context.runOnUiThread(new Runnable() {
#Override
public void run() {
if(Thread.currentThread().getName().equals("thread1")){
context.textView1.setText("thread1 ist bei: " + count);
}else{
context.textView2.setText("thread2 ist bei: " + count);
}
}
});
}
}
public void run() {
try {
running();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Hope this helps.

Android Broadcast Receiver as inner static class Passing a String

Probably you want to jump to Update 2 and check the code if needed
I am building a barcode scanner and having difficulty in passing data that I have captured from an inner class that extends BroadcastReceiver to MainActivity class, I do understand the difference between static and non static objects, but I got stuck.
Cant invoke my logic method from the inner class.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
protected void onCreate(Bundle savedInstanceState){...}
public void Logic(String result){// Do something...}
//Inner Class
public static class ScanResultReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {...
// data here captured fine!
// Here I want to send my data to MainActivity Logic(result)
Logic(result);
}
}
If I make "Logic()" as Static method, I get a lot of errors regards to calling non static from static method from Toaster/variables..etc
Update
This method is inside MainActivity, I do want to call it from the inner class
public void Logic(String result) throws Exception {
//prepare the results
if (mDecodeResult.decodeValue.substring(0, 1).equals("{") && mDecodeResult.decodeValue.substring(mDecodeResult.decodeValue.length() - 1).equals("}")) {
if (!(mDecodeResult.decodeValue.equals("SCAN AGAIN"))) {
mDecodeResult.decodeValue = mDecodeResult.decodeValue.substring(1);
mDecodeResult.decodeValue = mDecodeResult.decodeValue.substring(0, mDecodeResult.decodeValue.length() - 1);
}
}
if (mDecodeResult.decodeValue.equals("SCAN AGAIN")) {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received! Please Scan Again", Toast.LENGTH_SHORT);
toast.show();
} else if (mDecodeResult.decodeValue != null && tourFlag) {
String formattedDate = getTime();
String scanContent = mDecodeResult.decodeValue;
boolean found = false;
if (ForcedOrRandom.equals("Random")) {
String[] b;
for (String l : ToBeScanned) {
b = l.split(":");
if (scanContent.equals(b[0])) {
Log.d("remove", "scanned: " + scanContent);
Log.d("remove", "remove : " + b[0]);
found = true;
}
}
} else if (ForcedOrRandom.equals("Forced")) {
String[] b;
for (String I : FTobeScannedNext) {
b = I.split(":");
if (scanContent.equals(b[0])) {
Log.d("remove", "scanned: " + scanContent);
Log.d("remove", "remove : " + b[0]);
found = true;
}
}
}// end Skip/Forced
if (listLoaded && found) {
theResult[resultCount].setTourID(currentTourId);
theResult[resultCount].setBarcode(scanContent);
BarcodeObject a = getBarcodeInfo(scanContent);
if (ForcedOrRandom.equals("Random")) {
} else {
if (myTimer != null) {
myTimer.cancel();
Timer = (TextView) findViewById(R.id.timertext);
Timer.setText("");
PlayOrPause.setVisibility(View.INVISIBLE);
}
boolean isTimed = a.getForceNextBarCode().equals("");
if (!(isTimed)) {
PlayOrPause = (ImageButton) findViewById(R.id.PlayPause);
PlayOrPause.setVisibility(View.VISIBLE);
PlayOrPause.setImageResource(R.drawable.pause);
final AlertDialog.Builder timealert = new AlertDialog.Builder(this);
PlayOrPause.setEnabled(true);
long duration = Integer.parseInt(a.getForceNextBarCode());
duration = duration * 60000;
myTimer = new CountDownTimer(duration, 1000) {
#Override
public void onTick(long millisuntilFinished) {
int seconds = (int) (millisuntilFinished / 1000) % 60;
int minutes = (int) ((millisuntilFinished / (1000 * 60)) % 60);
Timer = (TextView) findViewById(R.id.timertext);
Timer.setText(minutes + ":" + seconds);
timeLeft = millisuntilFinished;
}
String value = "";
#Override
public void onFinish() {
Timer = (TextView) findViewById(R.id.timertext);
theResult[resultCount].setScanstatus(scanStatusTimeElapsed);
timealert.setTitle("Site Secure");
timealert.setMessage("Time Elapsed! Enter reason");
// Set an EditText view to get user input
final EditText input = new EditText(MainActivity.this);
timealert.setView(input);
timealert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
value = input.getText().toString();
// Do something with value!
while (value.equals("")) {
timealert.setView(input);
timealert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
value = input.getText().toString();
}
});
}
theResult[resultCount].setComments(value);
}
});
timealert.setIcon(android.R.drawable.ic_dialog_alert);
timealert.show();
Timer.setText(R.string.Time_Elapsed);
}
};
myTimer.start();
}
}
theResult[resultCount].setBarcodeID(a.getBarCodeId());
theResult[resultCount].setDateScanned(formattedDate);
theResult[resultCount].setSkipped(getResources().getString(R.string.Scanned));
}// end big if listLoaded && found
contentTxt.setText(scanContent);
Toaster(getResources().getString(R.string.TScan_Complete));
if (mainScanCounter == 0) {
if (tourDecider(scanContent)) {//tour decider is called to determine if this is boolJanamScanner random or forced tour
tourId = scanContent;
if (!(readFileOffline(siteSecurePath + "/doneTourNumber.txt").equals(""))) {
SYNC.setEnabled(true);
}
}
} else if (mainScanCounter > 0) {
if (ForcedOrRandom.equals("Random")) {
ListManager(scanContent);
} else {
ForcedListManager(scanContent);
}
}
} else if (mDecodeResult.decodeValue != null && officerScanFlag) {
TextView officertextview = (TextView) findViewById(R.id.officerid);
UserObject theofficer = getUserInfo(mDecodeResult.decodeValue);
if (theofficer == null) {
popUps("Error", "Invalid Officer ID, Please Rescan", "TITLE");
officerScan.setEnabled(true);
} else if (theofficer != null) {
// officer ID found need to store it for backup
officerId = theofficer.getOfficerid();
makeFileOffline(officerId, "officerID");
officertextview.setText(theofficer.getUsername());
officerScanFlag = false;
startTimersOfficerID = getTime();
tourBtn.setEnabled(true);
}
}
if (mDecodeResult.decodeValue != null && exceptionFlag) {
Log.d("check", "exception was clicked");
String ex_result = mDecodeResult.decodeValue;
for (int i = 0; i < theExceptions.length; i++) {
if (!(theExceptions[i].getBarcode().equals(ex_result))) {
String refnum = theExceptions[i].getRefNum();
i = theExceptions.length;
theResult[resultCount - 1].setException(refnum);
}
}
exceptionFlag = false;
Toaster(getResources().getString(R.string.TScan_Complete));
}
} // Logic Ends
Update 2
Not sure if I need to have another thread for this but I will put what I have found, my issue have narrowed to the following:
I am waiting on an intent called
<action android:name="device.scanner.USERMSG" />
with a permission
android:permission="com.permission.SCANNER_RESULT_RECEIVER"
now my issue
if a user tap button and released in less than .5 second onKeyup() event will be fired before my onReceive() that is inside the static class which is extends BroadcastReceiver, and that causes problem because Logic() will be invoked before updating the String inside onReceive()
if user hold the button long enough, onReceive will be invoked and everything is good and happy.
How can I make sure that onReceive() always invoked first?
public boolean onKeyUp(int keycode, KeyEvent event) {
if (keycode == 221 || keycode == 220 || keycode == 222) {
Logic(result);
}
return true;
}
Move this line of code:
public void Logic(String result){// Do something...}
inside your class ScanResultReceiver and it will work for sure. Your code should look like this:
public static class ScanResultReceiver extends BroadcastReceiver {
public ScanResultReceiver() {
//empty constructor
}
#Override
public void onReceive(Context context, Intent intent) {...
// data here captured fine!
// Here I want to send my data to MainActivity Logic(result)
Logic(result);
}
public void Logic(String result){/* ... */}
}

Two-Dimensional Array with JSON data - Data is downloaded, but I can't access it (?)

So, I am creating a little trivia game for learning purposes, but I ran into a problem.
First, I had a specific Android Fragment obtaining the data from JSON, and I will simply use that data on the callback method and display it on TextViews and Buttons. Everything was working fine, however, every time I returned to that fragment, the same questions would be there. So I decided to handle that in a better way outside of the callback method.
The problem here is that apparently my Arrays are either null or their lengths is zero. Which is weird, because according to my LOG, data is being passed to those arrays on the callback method.
Here's my full fragment code. Thanks!
public class GameFragment extends Fragment {
private TextView txtQuestion;
private Button btnAnswer1;
private Button btnAnswer2;
private Button btnAnswer3;
private Button btnAnswer4;
private Questions[] gameQuestions;
private Questions[] animeQuestions;
private Questions[] techQuestions;
private Questions[] movieQuestions;
private Questions[][] gameCategories = new Questions[4][];
int correctAnswer = -1;
private TransparentProgressDialog progressBar;
private Handler handler;
private Runnable runnable;
Callback cb = new Callback<MyApiData>(){
#Override
public void success(MyApiData myApiData, Response response) {
gameCategories[0] = new Questions[myApiData.getCategory()[0].getQuestions(0).length];
gameCategories[1] = new Questions[myApiData.getCategory()[1].getQuestions(1).length];
gameCategories[2] = new Questions[myApiData.getCategory()[2].getQuestions(2).length];
gameCategories[3] = new Questions[myApiData.getCategory()[3].getQuestions(3).length];
//gameCategories = new Questions[][] {gameQuestions, animeQuestions, techQuestions, movieQuestions};
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < gameCategories[i].length ; j++){
gameCategories[i][j] = myApiData.getCategory()[i].getQuestions(i)[j];
//Log.d("GameFragment", "gameCategories[i][j] - gameCategories["+i+"]["+j+"]: " + gameCategories[i][j].getQuestion());
}
}
//displayQuestion();
progressBar.dismiss();
displayQuestion();
}
#Override
public void failure(RetrofitError error) {
Log.d("GameScreen", "Callback failed!");
}
};
public GameFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_game, container, false);
txtQuestion = (TextView) view.findViewById(R.id.txtQuestion);
btnAnswer1 = (Button) view.findViewById(R.id.btnAnswer1);
btnAnswer2 = (Button) view.findViewById(R.id.btnAnswer2);
btnAnswer3 = (Button) view.findViewById(R.id.btnAnswer3);
btnAnswer4 = (Button) view.findViewById(R.id.btnAnswer4);
btnAnswer1.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer2.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer3.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(view);
}
});
handler = new Handler();
progressBar = new TransparentProgressDialog(getActivity(), R.drawable.loading_spinner);
runnable = new Runnable() {
#Override
public void run() {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
};
//launchRingDialog();
//RestClient.get().getQuestions(cb);
// Inflate the layout for this fragment
return view;
}
public void launchRingDialog() {
new Thread(new Runnable() {
public void run(){
try {
Log.d("Thred", "Try");
progressBar.show();
RestClient.get().getQuestions(cb);
//Thread.sleep(10000);
} catch (Exception e) {
}
//progressBar.dismiss();
}
}).start();
}
public void checkAnswer(View v){
switch(v.getId()){
case R.id.btnAnswer1:
if(correctAnswer == 1){
feedback(true, btnAnswer1);
}else {
feedback(false, btnAnswer1);
}
break;
case R.id.btnAnswer2:
if(correctAnswer == 2){
feedback(true, btnAnswer2);
}else {
feedback(false, btnAnswer2);
}
break;
case R.id.btnAnswer3:
if(correctAnswer == 3){
feedback(true, btnAnswer3);
}else {
feedback(false, btnAnswer3);
}
break;
case R.id.btnAnswer4:
if(correctAnswer == 4){
feedback(true, btnAnswer4);
}else {
feedback(false, btnAnswer4);
}
break;
default: txtQuestion.setText("Error");
break;
}
}
public void feedback(Boolean correct, Button btn){
if(correct){
btn.setBackgroundColor(Color.GREEN);
btn.setText("CORRECT!");
}else{
btn.setBackgroundColor(Color.RED);
btn.setText("WRONG!");
}
}
#Override
public void onResume() {
super.onResume();
//displayQuestion();
}
public void displayQuestion(){
Random randomizer = new Random();
int randomQuestion;
int category = GTMain.choosenCategory;
if(category == 5){
category = randomizer.nextInt(4);
}
randomQuestion = randomizer.nextInt(25);
Log.d("displayQuestion", "Before if statements");
if(gameCategories != null && gameCategories.length != 0) {
Log.d("displayQuestion", "First if");
if(gameCategories[category] != null && gameCategories[category].length != 0){
Log.d("displayQuestion", "Second if");
txtQuestion.setText(gameCategories[category][randomQuestion].getQuestion());
correctAnswer = gameCategories[category][randomQuestion].getCorrectAnswer();
Log.d("displayQuestion()", "correctAnswer: " + correctAnswer);
btnAnswer1.setText(gameCategories[category][randomQuestion].getAnswers().getA1());
btnAnswer2.setText(gameCategories[category][randomQuestion].getAnswers().getA2());
btnAnswer3.setText(gameCategories[category][randomQuestion].getAnswers().getA3());
btnAnswer4.setText(gameCategories[category][randomQuestion].getAnswers().getA4());
}
}
}
}
PS: On my main activity, I check to see which fragment should be loaded. If it's the fragment that contains the components to display the questions and answer (the one from the code above), I call the following method: gameFragment.launchRingDialog(); (and yes, I have created an instance of my GameFragment fragment before calling that method!)
When onResume() is called, your RestClient.get().getQuestions(cb) is still running in background, and your call displayQuestion(), so of course nothing is shown.
Can you put displayQuestion() inside success() of your callback?
Callback cb = new Callback<MyApiData>(){
#Override
public void success(MyApiData myApiData, Response response) {
....
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < gameCategories[i].length ; j++){
...
}
}
displayQuestion();
}
....
};
I would also suggest you to remove displayQuestion() in onResume() method.

Scoring of trivia game becomes inaccurate after 2nd game

I have a trivia game that is 10 timed questions. A wrong answer is supposed to output 0 points. A correct answer is supposed to output the remaining of the 20,000 milliseconds converted to a 100 point scale.
Right now the game works on the first game. Then, if the user keeps playing for a second time, the points for each question becomes incorrect. For example, incorrect answers begin to have a variety of points from 1 to 100 and also correct answers sometimes have 0 points and also sometimes wrong point totals. So I am guessing some variable is possibly not resetting on the second game so it is causing the points to be a little off.
I posted all the code that deals with the algorithm. My question is how I can get this code to output the correct answer no matter how many times the user plays before closing the app.
QuestionView.java
public class QuestionView extends Activity {
int correctAnswers = 0;
int wrongAnswers = 0;
int answer = 0;
int i = 0;
long score = 0;
long startTime = 20000;
long interval = 1000;
long points;
boolean timerHasStarted = false;
String category;
Button answer1, answer2, answer3, answer4;
TextView question, pointCounter, questionNumber, timeCounter, timeremaining;
AdView adView;
ArrayList<Question> queries;
public static ArrayList<Long> pointsPerQuestion = new ArrayList<Long>(10);
Timer cdTimer;
ProgressBar bar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.questionview);
answer1 = (Button)findViewById(R.id.answer1);
answer2 = (Button)findViewById(R.id.answer2);
answer3 = (Button)findViewById(R.id.answer3);
answer4 = (Button)findViewById(R.id.answer4);
question = (TextView)findViewById(R.id.question);
category = getIntent().getStringExtra("category");
queries = getIntent().getParcelableArrayListExtra("queries");
questionNumber = (TextView)findViewById(R.id.questionnumber);
timeremaining = (TextView)findViewById(R.id.timeremaining);
cdTimer = new Timer(startTime, interval);
bar = (ProgressBar)findViewById(R.id.progressbar);
bar.setIndeterminate(false);
bar.setMax(20000);
tracker.sendView("/QuestionView - Started Quiz");
loadQuestion();
}
public void loadQuestion() {
if(i == 10) {
cdTimer.cancel();
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.start();
timerHasStarted = false;
}
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(0);
if(answer == 0) {
correctAnswers++;
correct();
} else {
wrongAnswers++;
incorrect();
}
}
});
answer2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(1);
if(answer == 1) {
correctAnswers++;
correct();
} else {
wrongAnswers++;
incorrect();
}
}
});
answer3.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(2);
if(answer == 2) {
correctAnswers++;
correct();
} else {
wrongAnswers++;
incorrect();
}
}
});
answer4.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(3);
if(answer == 3) {
correctAnswers++;
correct();
} else {
wrongAnswers++;
incorrect();
}
}
});
}
}
public ArrayList<Question> getQueries() {
return queries;
}
public static ArrayList<Long> getPointsPerQuestion() {
return pointsPerQuestion;
}
public void correct() {
pointsPerQuestion.add(points);
score = score + points;
i++;
loadQuestion();
}
public void incorrect() {
long zero = 0;
pointsPerQuestion.add(zero);
i++;
loadQuestion();
}
public class Timer extends CountDownTimer {
public Timer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
points = 0;
if(i >= 9) {
cdTimer.cancel();
pointsPerQuestion.add(points);
endQuiz();
} else {
wrongAnswers++;
incorrect();
}
}
#Override
public void onTick(long millisUntilFinished) {
bar.setProgress((int) millisUntilFinished);
points = millisUntilFinished / 200;
timeremaining.setText("Score remaining: " + points);
if(i < 10) {
questionNumber.setText("Question " + (i + 1) + " of 10");
}
}
}
public void endQuiz() {
Intent intent = new Intent(QuestionView.this, Results.class);
intent.putExtra("correctAnswers", correctAnswers);
intent.putExtra("wrongAnswers", wrongAnswers);
intent.putExtra("score", score);
intent.putExtra("pointsPerQuestion", pointsPerQuestion);
intent.putParcelableArrayListExtra("queries", queries);
intent.putExtra("category", category);
startActivity(intent);
}
}
Here is a Question object:
exodus.add(new Question("6th", "3rd", "5th", "4th", 2, "Name that plague: All livestock dies", -1, "Exodus 9:6"));
In my Results class, which is where the points per question is displayed, this is the line that displays the points:
scoreTV.setText("You received " + QuestionView.getPointsPerQuestion().get(x) + " out of a possible 100 points.");
Everything else is pretty much in my QuestionView above. Let me know if you still need something else.
First 3 Strings are answers A (index 0), B (index 1), C (index 2) and D (index 3). The first int is the correct answer. The 5th String is the question. The second int is set to the answer selected by user during quiz. Last String is the bible verse where the answer is found.

Categories

Resources