1

I've created a question and answer game and I need to keep score without creating any database. I've created an individual activity and .xml for each question and user needs to input answer in a text field and if the answer is correct, it automatically goes to next activity (i.e. next question). Now, I need to keep score in such a way that after user enters a correct answer the score should be shown in the top right corner of the screen. How do I do that? please help. Here's the java activity and xml file for my Second question of first level:

package com.golo.user.gaunkhanekatha;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Handler;



public class TwoActivity extends Activity {

    public Button check;
    public EditText typeh;
    private Toast toast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);
        toast = Toast.makeText(TwoActivity.this, "", Toast.LENGTH_SHORT);
        check = (Button)findViewById(R.id.check1); //R.id.button is the id on your xml
        typeh = (EditText)findViewById(R.id.type1); //this is the EditText id
        check.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                //Here you must get the text on your EditText
                String Answer = (String) typeh.getText().toString(); //here you have the text typed by the user
                //You can make an if statement to check if it's correct or not
                if(Answer.equals("piano") || (Answer.equals("keyboard")))
                {
                    ///Correct Toast
                    toast.setText("Correct! Now, next question...");
                    toast.setGravity(Gravity.TOP | Gravity.LEFT, 500, 300);
                    toast.show();
                    Intent i = new Intent(TwoActivity.this, ThreeActivity.class);
                    startActivity(i);
                    finish();

                }
                else{
                    //It's not the correct answer
                    toast.setText("Wrong! Try Again!");
                    toast.setGravity(Gravity.TOP | Gravity.LEFT, 500, 300);
                    toast.show();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(toast!= null) {
            toast.cancel();
        }
    }

    @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_aboutus, 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);
    }
}

The xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:weightSum="1"
    android:textAlignment="center"
    android:id="@+id/level1">

    <TextView
        android:layout_width="300dp"
        android:layout_height="200dp"
        android:text="What has 88 keys but cannot open a single door?"
        android:id="@+id/que1"
        android:width="255dp"
        android:textSize="30dp"
        android:layout_margin="50dp"
        android:textStyle="italic"
        android:gravity="center" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/type1"
        android:layout_gravity="center_horizontal"
        android:hint="Type here..." />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check answer..."
        android:id="@+id/check1"
        android:layout_gravity="center_horizontal" />
</LinearLayout>
Bikal Nepal
  • 477
  • 1
  • 10
  • 26

3 Answers3

3

If you want the scores to be kept between runs, you could write the scores to a text file using something along the lines of this: How do I create a file and write to it in Java?

And then read from it when you want to display the score: Java: How to read a text file

Alternatively if you wanted to just maintain a score for the duration of the running of the application you could use a singleton of the score. Such as:

public class Score {

    private static int score = 0;

    //So that this class can't be instantiated
    private Score () {
    }

    //Return current score
    public static int getScore() {
        return score;
    }

    //Increment score
    public static void increaseScoreByOne() {
        score = score++;
    }

    //Decrement score
    public static void decreaseScoreByOne() {
        score = score--;
    }

    //Reset score back to 0
    public static void resetScore() {
        score = 0;
    }
}

This could then be accessed anywhere in the application by calling:

Score.getScore();
Score.increaseScoreByOne();
Score.decreaseScoreByOne();
Score.resetScore();
Community
  • 1
  • 1
Kialandei
  • 394
  • 1
  • 11
  • I made a score.java activity and pasted the code but while calling in my level's activity, it shows error in Score saying cannot resolve symbol Score – Bikal Nepal Sep 16 '15 at 15:38
  • The file name will need to match the class name so it will need to be called Score.java (with the capital). Also make sure you put it in the same package as your original class, or if you put it in a different package you'll need to import it with `import your.package.name.Score` – Kialandei Sep 16 '15 at 15:46
  • still shows error under Score. I've created a new class and named it Score.java and copied the code there. But in OneActivity.java it still shows error under Score – Bikal Nepal Sep 16 '15 at 16:27
  • Try the code now, I might have made a boo-boo and forgotten to use public class – Kialandei Sep 16 '15 at 16:30
  • Add this line `package com.golo.user.gaunkhanekatha;` to the `Score` class and remove the import line for `Score` from `TwoActivity`. Make sure that the `Score` class is in the same folder as your `TwoActivity` class. The folder where the classes are also needs to follow the structure ./com/golo/user/gaunkhanekatha. I've put both in the same folder in that location and I can use the `Score` class from `TwoActivity`. – Kialandei Sep 17 '15 at 08:11
  • thanks no errors were shown. So, this records the score but I want to display the score too. How do I do that? Please help – Bikal Nepal Sep 17 '15 at 09:34
  • To display the score, you'll need to add a label to your GUI, the value of the label will be Score.getScore() and you'll update the value with the result of that method each time you want to display the new score https://docs.oracle.com/javase/tutorial/uiswing/components/label.html – Kialandei Sep 17 '15 at 10:30
2

If you don't need to keep score between plays, just add a new attribute to the class and increment it during the class flow.

public class TwoActivity extends Activity {

    public Button check;
    public EditText typeh;
    private Toast toast;

    private int score;

    if(Answer.equals("piano") || (Answer.equals("keyboard")))
    {
        ///Correct Toast
        .... 
        // +5 points per correct answer
        score +=5;
    } else{
        //It's not the correct answer
        ....
        // -1 point per incorrect answer
        score --;
    }
}

If you want to keed score between app executions, or maybe show a rank, you need to use SharedPreferences. Check this question for examples

Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
0

If you want scores to be saved all the time then please use SharedPreferences, otherwise if you want it to be only in running state of the application then use static data member with in the class to store the scores

Akber
  • 521
  • 4
  • 10