-3

I'm making a simple quiz app that consist of 10 questions with 10sec countdown timer each questions, which means i have 10 activity for questions. The scoring works while each questions answer correctly multiply by remaining time on CountDownTimer method, so it will be: score = answer * timeLeft; And the total score will be printed on ResultActivity at the end of activity after activity 10. The problem is i cannot pass my score variable through each activity and when i click next button that intent from activity 10 to ResultActivity, the ResultActivity cannot be open or force close. Here is my code:

TestActivity1

package com.finalproject.logicaltest;

import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;

import java.util.Timer;

import butterknife.ButterKnife;
import butterknife.Bind;

import static android.R.id.message;
import static android.R.string.cancel;
import static com.finalproject.logicaltest.R.id.rb1;
import static com.finalproject.logicaltest.R.id.rb2;
import static com.finalproject.logicaltest.R.id.rb3;
import static com.finalproject.logicaltest.R.id.rb4;


public class TestActivity1 extends AppCompatActivity {

    @Bind(R.id.rb1) RadioButton rB1;
    @Bind(R.id.rb2) RadioButton rB2;
    @Bind(R.id.rb3) RadioButton rB3;
    @Bind(R.id.rb4) RadioButton rB4;
    @Bind(R.id.next) Button bNext;
    @Bind(R.id.timer) TextView cDown;

    public int answer = 0;
    public int score = 0;
    public long timeLeft = 0;
    //The number of milliseconds in the future from
    //the call to start() until the countdown is done
    public long millisInFuture = 11000; //11 seconds
    //The interval along the way to receive onTick(long) callbacks
    long countDownInterval = 1000; //1 second

    public long millisUntilFinished;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test1);
        ButterKnife.bind(this);

        setTimer();

    }

    public void setTimer() {

        //Initialize a new CountDownTimer instance
       final CountDownTimer timer = new CountDownTimer(millisInFuture,countDownInterval){
            public void onTick(long millisUntilFinished){
                //do something in every tick
                //Display the remaining seconds to app interface
                //1 second = 1000 milliseconds
                cDown.setText("" + millisUntilFinished / 1000);
                timeLeft = millisUntilFinished / 1000;

            }
            public void onFinish(){
                //Do something when count down finished
                cDown.setText("NEXT!");
                Intent intent = new Intent(TestActivity1.this,TestActivity2.class);
                intent.putExtra("score", score);
                startActivity(intent);
                finish();
                timeLeft = 0;
            }


        }.start();

        bNext.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                timer.cancel();
                timeLeft = millisUntilFinished;
                Intent intent = new Intent(TestActivity1.this,TestActivity2.class);
                intent.putExtra("score", score);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

            }

        });

    }

    public void onRadioButtonClicked (View v) {

        boolean checked = ((RadioButton) v).isChecked();

        switch (v.getId()) {

            case rb1:
                if (checked){
                    answer++;
                    break;
                }

            case rb2:
                if (checked){
                    answer = 0;
                    break;
                }

            case rb3:
                if (checked){
                    answer = 0;
                    break;
                }

            case rb4:
                if (checked){
                    answer = 0;
                    break;
                }
        }

        score = ((int)(timeLeft) * Integer.valueOf(answer));

    }




}

It pass score with putExtra through TestActivity2 until TestActivity10 like this:

package com.finalproject.logicaltest;

/**
 * Created by VICKY on 19-May-17.
 */

import android.app.Activity;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.Bind;

import static com.finalproject.logicaltest.R.id.rb1;
import static com.finalproject.logicaltest.R.id.rb2;
import static com.finalproject.logicaltest.R.id.rb3;
import static com.finalproject.logicaltest.R.id.rb4;
import static com.finalproject.logicaltest.R.id.rb5;

public class TestActivity10 extends AppCompatActivity {

    @Bind(rb1) RadioButton rB1;
    @Bind(rb2) RadioButton rB2;
    @Bind(rb3) RadioButton rB3;
    @Bind(rb4) RadioButton rB4;
    @Bind(rb5) RadioButton rB5;
    @Bind(R.id.end) Button bEnd;
    @Bind(R.id.timer) TextView cDown;

    public int answer = 0;
    public int score = 0;
    public long timeLeft = 0;
    //The number of milliseconds in the future from
    //the call to start() until the countdown is done
    public long millisInFuture = 11000; //11 seconds
    //The interval along the way to receive onTick(long) callbacks
    long countDownInterval = 1000; //1 second

    public long millisUntilFinished;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test10);
        ButterKnife.bind(this);
        score = getIntent().getExtras().getInt("score");

        setTimer();
    }

    public void setTimer() {


        //Initialize a new CountDownTimer instance
        final CountDownTimer timer = new CountDownTimer(millisInFuture,countDownInterval){
            public void onTick(long millisUntilFinished){
                //do something in every tick
                //Display the remaining seconds to app interface
                //1 second = 1000 milliseconds
                cDown.setText("" + millisUntilFinished / 1000);
                timeLeft = millisUntilFinished / 1000;
            }
            public void onFinish(){
                //Do something when count down finished
                cDown.setText("NEXT!");
                Intent intent = new Intent(TestActivity10.this,ResultActivity.class);
                intent.putExtra("score", score);
                startActivity(intent);
                finish();
                timeLeft = 0;
            }
        }.start();


        bEnd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                timer.cancel();
                timeLeft = millisUntilFinished;
                Intent intent = new Intent(TestActivity10.this,ResultActivity.class);
                intent.putExtra("score", score);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            }

        });
    }

    public void onRadioButtonClicked (View v) {

        boolean checked = ((RadioButton) v).isChecked();

        switch (v.getId()) {

            case rb1:
                if (checked){
                    answer = 0;
                    break;
                }

            case rb2:
                if (checked){
                    answer++;
                    break;
                }

            case rb3:
                if (checked){
                    answer = 0;
                    break;
                }

            case rb4:
                if (checked){
                    answer = 0;
                    break;
                }

            case rb5:
                if (checked){
                    answer = 0;
                    break;
                }
        }

        score += ((int)(timeLeft) * Integer.valueOf(answer));

    }




}

And printed total score on ResultActivity:

package com.finalproject.logicaltest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import static android.R.id.message;


public class ResultActivity extends AppCompatActivity {
    public int score = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        score = getIntent().getExtras().getInt("score");
        TextView result = (TextView) findViewById(R.id.total_score);
        result.setText(score);
    }
}

What's wrong with my code?

Vicky Sultan
  • 73
  • 2
  • 15
  • 2
    You can store the value of the result in shared Preference and fget it in the result screen instead of always passing it. – Anmol317 May 19 '17 at 07:35
  • 3
    Why are you creating activity for each question? You should use Fragment and reuse it as many times as you do have the questions. – schinj May 19 '17 at 07:36
  • 2
    `I'm making a simple quiz app that consist of 10 questions with 10sec countdown timer each questions, which means i have 10 activity for questions` this seems like you're trying to solve the problem in the wrong way. I'd imagine you could just have one generic activity which takes a question and then shows that question, instead of creating a new activity for each question. Right now all your 10 activities are basically copies of each other. Maintaining those will get a lot harder as time goes on. – nbokmans May 19 '17 at 07:37
  • What do you mean with not work? The score returns 0 or you get an exception or...? – Denny May 19 '17 at 07:37
  • Check you **Android Monitor** once for any exception. – Shruti May 19 '17 at 07:58
  • As Sac and nbokmans told you can make a quiz app very more simple and practical. Just make some search. I recommend : http://stackoverflow.com/questions/25200551/android-making-quiz-app-with-database – Hossein Seifi May 19 '17 at 08:13

3 Answers3

0

You can use Application class for that , save score value in Application class which can be accessible from any class you want.(as you only need to save score value.) for more info you can check here

Hope it helps..

Community
  • 1
  • 1
Gagan
  • 745
  • 10
  • 31
  • While this is a working solution this is generally not recommended. Why should the `Application` class hold this data? It's better to pass it around via intents and extras. – nbokmans May 19 '17 at 07:43
  • You only need score value .... for that Application class can work. No doubt intents are the good approach it should work, but Application class can also work here ,check the link i mention. – Gagan May 19 '17 at 07:47
  • My point is that dumping everything in the Application class quickly leads to a tightly coupled system that becomes a monstrosity to do any form of testing/refactoring on. – nbokmans May 19 '17 at 07:48
0

Hello Try this code it may help,use according to your logic

Declarations and Initialization

SharedPreferences sharedpreferences;
sharedpreferences = getSharedPreferences("results", Context.MODE_PRIVATE);

storing your score for using in the other activities

SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putString("score", score);
            editor.commit();

Retrieving the stored data

SharedPreferences prefs = this.getSharedPreferences("results", Context.MODE_PRIVATE);
String lanSettings = prefs.getString("score", null);
Pratik Vyas
  • 644
  • 7
  • 20
  • Where should i write this code? In onCreate? public class? or which method ? – Vicky Sultan May 19 '17 at 07:52
  • you have to the SharedPreferences before starting the test, onCreate will work fine here – Pratik Vyas May 19 '17 at 07:55
  • I just have to add these code or replace it with other wrong code of mine? Which one should i replace? And on the declaration, unlike mine, you didn't declare a global variable like `public int score = 0;` or it will works automatically? Should i let putExtra() written there or replace it with SharedPreferences? – Vicky Sultan May 19 '17 at 08:00
  • you should use shared preference instead of sending intents – Pratik Vyas May 19 '17 at 08:06
  • editor.putInt("userScore1", zero); int userScore1 = prefs.getInt("userScore1",0); editor.putFloat("percantage", 1.2f); float someFloat = prefs.getFloat("percantage", 0.0f); – Pratik Vyas May 19 '17 at 08:07
  • these two examples for int and float in case you want to store percentage – Pratik Vyas May 19 '17 at 08:08
  • I see. But are there any way to pass variable only using intents? – Vicky Sultan May 19 '17 at 08:15
0

IMO you are setting score to your TextView which is incorrect. Either set it like this:

result.setText(String.valueOf(score));

or like this:

result.setText(" "+score);

See if this works.

Shruti
  • 803
  • 9
  • 26