Kara W
Kara W

Reputation: 143

Android Studio quiz app saving score

I'm currently making a flag quiz app, and want to add scores. Below you can see a picture of it; each flag is a fragment, and when you press them, the right hand side allows you to submit an answer.

enter image description here

When you enter the right answer, a "correct" message appears, and you can go to the next flag. I want a right answer to give a score of 1, and a wrong one (or when pressed skip or hint) to give a score of zero. At the end, the score is summarized. However, I'm unsure how to do this. I've created a ScoreActivity.java file where the scores will be registered (though it's currently empty), and I've tried writing the code shown below.

Play.java

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.app.FragmentManager;
import android.view.View;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.view.View.OnClickListener;
import android.view.LayoutInflater;
import android.widget.Button;
import android.widget.ImageButton;
import android.view.ViewGroup;


import layout.FragmentOne;
import layout.FragmentTwo;
import layout.FragmentThree;
import layout.FragmentDefault;


public class Play extends MainActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_play);


    final ImageButton imageBtn10 = (ImageButton) findViewById(R.id.imageButton10);
    final ImageButton imageBtn9 = (ImageButton) findViewById(R.id.imageButton9);
    final ImageButton imageBtn8 = (ImageButton) findViewById(R.id.imageButton8);
    final ImageButton imageBtn7 = (ImageButton) findViewById(R.id.imageButton7);
    final ImageButton imageBtn6 = (ImageButton) findViewById(R.id.imageButton6);
    final ImageButton imageBtn5 = (ImageButton) findViewById(R.id.imageButton5);
    final ImageButton imageBtn4 = (ImageButton) findViewById(R.id.imageButton4);
    final ImageButton imageBtn3 = (ImageButton) findViewById(R.id.imageButton3);

    FragmentManager fragMan = getFragmentManager();
    FragmentTransaction fragTrans = fragMan.beginTransaction();
    FragmentDefault fd = new FragmentDefault();
    fragTrans.replace(R.id.fragment_place, fd);
    fragTrans.commit();

    fragTrans.hide(new FragmentOne());
    fragTrans.hide(new FragmentTwo());
    fragTrans.hide(new FragmentThree());

    imageBtn10.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                FragmentManager fragMan = getFragmentManager();
                FragmentTransaction fragTrans = fragMan.beginTransaction();
                fragTrans.replace(R.id.fragment_place, new FragmentOne());
                fragTrans.commit();
                imageBtn10.setEnabled(false);
        }

    });


    imageBtn9.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fragMan = getFragmentManager();
            FragmentTransaction fragTrans = fragMan.beginTransaction();
            fragTrans.replace(R.id.fragment_place, new FragmentTwo());
            fragTrans.commit();
        }
    });

    imageBtn8.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
                FragmentManager fragMan = getFragmentManager();
                FragmentTransaction fragTrans = fragMan.beginTransaction();
                fragTrans.replace(R.id.fragment_place, new FragmentThree());
                fragTrans.commit();
        }
    });

    imageBtn7.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fragMan = getFragmentManager();
            FragmentTransaction fragTrans = fragMan.beginTransaction();
            fragTrans.replace(R.id.fragment_place, new FragmentThree());
            fragTrans.commit();
        }
    });

    imageBtn6.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fragMan = getFragmentManager();
            FragmentTransaction fragTrans = fragMan.beginTransaction();
            fragTrans.replace(R.id.fragment_place, new FragmentThree());
            fragTrans.commit();
        }
    });

    imageBtn5.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fragMan = getFragmentManager();
            FragmentTransaction fragTrans = fragMan.beginTransaction();
            fragTrans.replace(R.id.fragment_place, new FragmentThree());
            fragTrans.commit();
        }
    });

    imageBtn4.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fragMan = getFragmentManager();
            FragmentTransaction fragTrans = fragMan.beginTransaction();
            fragTrans.replace(R.id.fragment_place, new FragmentThree());
            fragTrans.commit();
            //imageBtn4.setEnabled(false);
        }
    });

    imageBtn3.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fragMan = getFragmentManager();
            FragmentTransaction fragTrans = fragMan.beginTransaction();
            fragTrans.replace(R.id.fragment_place, new FragmentThree());
            fragTrans.commit();
        }
    });

    Button button_score = (Button)findViewById(R.id.scoreButton);
    button_score.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intentPlay = new Intent(Play.this, ScoreActivity.class);
            startActivity(intentPlay);
        }
    });



}




}

FragmentOne.java (this is the fragment for the German flag)

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
 import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
//import android.widget.TextView;


public class FragmentOne extends Fragment {

EditText theAnswer;
Button ScoreButton;

private EditText userAnswer;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_fragment_one, null);
    userAnswer = (EditText)v.findViewById(R.id.editText);
    final TextView tv = (TextView)v.findViewById(R.id.showCorrect);
    final TextView hintv = (TextView)v.findViewById(R.id.textHint);


    final Button submit = (Button)v.findViewById(R.id.submitBtn1);
    submit.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String theAnswer = (userAnswer.getText().toString());
            if (theAnswer.equalsIgnoreCase("Germany")) {
                //TextView tv = (TextView)v.findViewById(R.id.showCorrect);
                tv.setText("Correct!");

            } else {

            }
            submit.setEnabled(false);

            // updateScore();
        }
    });

    final Button skip = (Button)v.findViewById(R.id.skipBtn);
    skip.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            submit.setEnabled(false);
        }
    });

    final Button hint = (Button)v.findViewById(R.id.hintBtn);
    hint.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            hintv.setText("The capital is Berlin \n The country is in Europe \n It starts with G... ");
            //submit.setEnabled(false);
        }
    });


    return v;


}

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ScoreButton = (Button)getView().findViewById(R.id.scoreButton);


    final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    ScoreButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            SharedPreferences.Editor editor = app_preferences.edit();

            if (userAnswer.isChecked()){
                editor.putInt("answer_value", 1);
            }
            else {
                editor.putInt("answer_value", 0);
            }
            editor.commit();
        }
    });
}



}

.isChecked() appears in red. Do I need to import something?

Upvotes: 1

Views: 3051

Answers (3)

Kara W
Kara W

Reputation: 143

So I have amended the code in FragmentOne.java, and now it looks like this:

public class FragmentOne extends Fragment {

private EditText userAnswer;
private boolean wellAnswered;
private Button ScoreButton;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_fragment_one, null);
    userAnswer = (EditText)v.findViewById(R.id.editText);
    final TextView tv = (TextView)v.findViewById(R.id.showCorrect);
    final TextView hintv = (TextView)v.findViewById(R.id.textHint);

    final Button submit = (Button)v.findViewById(R.id.submitBtn1);
    submit.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String theAnswer = (userAnswer.getText().toString());
            if (theAnswer.equalsIgnoreCase("Germany")) {
                //TextView tv = (TextView)v.findViewById(R.id.showCorrect);
                tv.setText("Correct!");
                wellAnswered = true;

            } else {

            }
            submit.setEnabled(false);

            // updateScore();
        }
    });

    final Button skip = (Button)v.findViewById(R.id.skipBtn);
    skip.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            submit.setEnabled(false);
        }
    });

    final Button hint = (Button)v.findViewById(R.id.hintBtn);
    hint.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            hintv.setText("The capital is Berlin \n The country is in Europe \n It starts with G... ");
            //submit.setEnabled(false);
        }
    });


    return v;}

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ScoreButton = (Button)getView().findViewById(R.id.scoreButton);


        final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        ScoreButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                SharedPreferences.Editor editor = app_preferences.edit();

                if (wellAnswered){
                    editor.putInt("answer_value", 1);

                    // remember to reset your variable for next question
                    wellAnswered = false;
                }
                else {
                    editor.putInt("answer_value", 0);
                }
                editor.commit();
            }
        });
    }



}

I have used the suggestions from your answers and I get no errors, however, the app crashes when I press the flags. Any idea what I'm doing wrong?

STACKTRACE:

01-06 20:08:18.152 3912-3912/? I/art: Not late-enabling -Xcheck:jni (already on)
01-06 20:08:18.153 3912-3912/? W/art: Unexpected CPU variant for X86 using defaults: x86
01-06 20:08:18.189 3912-3919/? I/art: Debugger is no longer active
01-06 20:08:18.189 3912-3919/? I/art: Starting a blocking GC Instrumentation
01-06 20:08:18.294 3912-3912/? W/System: ClassLoader referenced unknown path: /data/app/com.example.karolinawullum.quizapp-1/lib/x86
01-06 20:08:18.299 3912-3912/? I/InstantRun: Instant Run Runtime started. Android package is com.example.karolinawullum.quizapp, real application class is null.

                                             [ 01-06 20:08:18.311  1560: 1583 D/         ]
                                             HostConnection::get() New Host Connection established 0x8d661580, tid 1583
01-06 20:08:18.378 3912-3912/? W/System: ClassLoader referenced unknown path: /data/app/com.example.karolinawullum.quizapp-1/lib/x86
01-06 20:08:18.487 3912-3912/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
01-06 20:08:18.608 3912-3933/? I/OpenGLRenderer: Initialized EGL, version 1.4
01-06 20:08:18.610 3912-3933/? D/OpenGLRenderer: Swap behavior 1
01-06 20:08:18.637 3912-3933/? E/EGL_emulation: tid 3933: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
01-06 20:08:18.637 3912-3933/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x90557900, error=EGL_BAD_MATCH

Upvotes: 0

OBX
OBX

Reputation: 6114

To save the Scores , you can use SharedPreferences. As per the docs:

If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs. A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared.

How do I use SharedPreferences to store my Score?

Every time the user clicks the submit button, inside the onClickListener() retrieve the existing value from the SharedPreferences file and increment it by one.


So, How do I do it?

Well First, create an instance of SharedPreferences:

private SharedPreferences sharedpreferences;

then initialize it:

sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);

then inside the onClickListener() :

SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("SCORE", sharedpreferences.getInt("SCORE",0)+1);
editor.apply();

So what this does is , it creates a Key value pair, where the key is SCORE, and putInt() method inserts a value associated with the key, in this case SCORE.

NOTE : sharedpreferences.getInt("SCORE",0)+1) what this does is it increments, the score by one. And finally apply() saves the data to the SharedPreferences file.


How do I retrieve the Score ?

sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
int score = sharedpreferences.getInt("SCORE",0)

Where, the 0 is the default value.


Hope it helps!

Upvotes: 0

firegloves
firegloves

Reputation: 5709

First of all: why are you using all of these fragment? Can't you use a single fragment updating its data to alternate between questions?

The problem is that EditText class does not have isChecked() method. To use that method you need to use a CheckBox class.

You are using a widget to catch user input, like a text type HTML input. Is checked is logically a property of an item that can ben checked, like an HTML checkbox

You are putting a text into your EditText (user answer) and then you are asking to a string container field if it's checked. It does not make sense.

What you really needs is store if user answer match right answer (like in a boolean). You can set this value when you set "correct" in result TextView, someting like this:

final Button submit = (Button)v.findViewById(R.id.submitBtn1);
    submit.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String theAnswer = (userAnswer.getText().toString());
            if (theAnswer.equalsIgnoreCase("Germany")) {
                //TextView tv = (TextView)v.findViewById(R.id.showCorrect);
                tv.setText("Correct!");
                // keep trace of user answer result
                wellAnswered = true;
            } else {

            }
            submit.setEnabled(false);

            // updateScore();
        }
    });

Then you can update your FragmentOne code as follows:

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ScoreButton = (Button)getView().findViewById(R.id.scoreButton);


    final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    ScoreButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            SharedPreferences.Editor editor = app_preferences.edit();

            if (wellAnswered){
                editor.putInt("answer_value", 1);

                // remember to reset your variable for next question
                wellAnswered = false;
            }
            else {
                editor.putInt("answer_value", 0);
            }
            editor.commit();
        }
    });
}

Upvotes: 2

Related Questions