4

I've created a question and answer game with different levels, each level consisting a question. I didn't create it with a database. I just used string. When the user answers a question in level one he is taken to level two but when the user returns back to level one, he has to type the answer again even though he's solved it before. Is there anyway in JAVA to keep the answer in the type panel (if the user's solved it) without having to create a database?? Also, while typing in the type panel, the user has to delete the "Type here..." and then answer. Is there anyway that when user taps to type the "Type here..." is automatically erased?

Here's my level one activity.xml:

<?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:text="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>

and here's my Oneactivity.java

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.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 OneActivity extends Activity {
public SharedPreferences preferences; //ADDED THIS LINE
    public Button check;
    public EditText typeh;
    private Toast toast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one);
        toast = Toast.makeText(OneActivity.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")))
                {
                    preferences = PreferenceManager.getDefaultSharedPreferences(v.getContext());
                SharedPreferences.Editor editor = preferences.edit();
                editor.putInt("Level 1 question 1 ", 1); //Depends of the level he have passed.
                editor.apply();
                ///Correct Toast
                toast.setText("Correct");
                toast.setGravity(Gravity.TOP | Gravity.LEFT, 500, 300);
                toast.show();
                Intent i = new Intent(OneActivity.this, TwoActivity.class);
                startActivity(i);
                finish();

                }
                else{
                    //It's not the correct answer
                    toast.setText("Wrong! Try again...");
                    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);
    }
}

Also, the toast is displayed where there's keyboard. Is there anyway to move the toast screen to somewhere on the screen where it is clearly visible?

Bikal Nepal
  • 477
  • 1
  • 10
  • 26

5 Answers5

1

I'll give to you two methods to do it :

Create a LevelEarned class as follows :

public class LevelEarned {
 public static int level = 0;
}

Everytime you get an Intent (because user has answered the question correctly) just type :

LevelEarned.level = 1; // 1 depends with the level you have answered correctly

And the best method that it's that I'd use to this it's called SharedPreferences

You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).

The first thing you have to do is store this data on SharedPreferences and you do it with an Editor as follows :

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(v.getContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("player_level",1); //Depends of the level he have passed.
editor.apply();

NOTE

I guess you will do it immediately when the user accepts the question so, you'll do it on a Button click so you'll have to pass as a context v.getContext() if you are not on a ButtonClick and you are on your onCreate() just call this to refer your context.

To get the stored data (level) you'll need to do this :

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int level = preferences.getInt("player_level", 0);

Let's explain to you a little bit.

The first parameter it's the key to find the SharedPreference so it won't change and the second one is a default value that it's used in case it doesn't find any "player_level" SharedPreferences.

Hope it helps to you to keep going in your code :)

EDIT2

Create SharedPreferences preferences as a global variable as follows :

public SharedPreferences preferences;

Then inside of your onClick() method add those lanes :

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("4") || (Answer.equals("four")))
            {
                preferences = PreferenceManager.getDefaultSharedPreferences(v.getContext());
                SharedPreferences.Editor editor = preferences.edit();
                editor.putInt("player_level",1); //Depends of the level he have passed.
                editor.apply();
                //Create a Toast because it's correct
                Toast.makeText(OneActivity.this, "Correct!",
                        Toast.LENGTH_LONG).show();
            }
            else{
                //It's not the correct answer
                Toast.makeText(OneActivity.this, "Wrong! Try Again",
                        Toast.LENGTH_LONG).show();
            }
        }
    });

And where you want to know the level you only will have to do :

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int level = preferences.getInt("player_level", 0); //level is the current level of the player.

EDIT 3

Create a class as follows :

 public static class LevelPlayer(){

     public int static getLevelPlayer(){

     SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
     int level = preferences.getInt("player_level", 0); //level is the current level of the playe


     return level;
     }

  }

And every time you want to ask the level of the player you do :

int Level = LevelPlayer.getLevelPlayer(); //that's the level

So after every question you can ask the level and put the next question.

EDIT4

I've made some changes, delete your lvl class and put this code :

public class lvl{
public Context mcontext;

public lvl(Context context){
    this.mcontext = context;

}
public int getLevelPlayer(){

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mcontext);
    int level = preferences.getInt("player_level", 0); //level is the current level of the playe
    return level;
}

Then on your MainActivity(or wherever you have to know what's the level of the player) you have to put this :

public levelplayer mlevelplayer;

Then inside on your onCreate() add this :

mlevelplayer = new levelplayer(this);
int level  = mlevelplayer.getLevelPlayer();
Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
  • @Bik see my edit let me know if it works, if it does not i'll update the code – Skizo-ozᴉʞS ツ Sep 02 '15 at 19:02
  • still having problems?? – Skizo-ozᴉʞS ツ Sep 03 '15 at 20:38
  • Hmm Bik? you didn't mark any answer as a correct noone dind't helped you? – Skizo-ozᴉʞS ツ Sep 06 '15 at 10:21
  • Hey Skizo, sorry it's a late post, i was kinda busy. I'm not understanding where exactly do I have to paste the last line and how is that going to save the correct answer in the game after the level's been played? I'm talking about this last code: SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); int level = preferences.getInt("player_level", 0); //level is the current level of the player. – Bikal Nepal Sep 09 '15 at 17:03
  • You have to put this wherever you want to know the level of the player, in your first activity, second, wherever. Shall I update my answer to you accept this answer? – Skizo-ozᴉʞS ツ Sep 14 '15 at 09:02
  • Okay, I've added the "public SharedPreferences preferences;" inside the activity of question 1 of level 1 (i.e. OneActivity), please see above, I've edited. and i've made changes inside onclick() too and I've done it for activity of few other questions too but it's not saving the answer when the level is reopened. I still don't understand where should I add that last line of code. Do I add it on every activity (I've made activity for each question and need to save the answer, once correct answer is inputted, in the input field)? and if yes, on which line should I exactly add it? Please help! – Bikal Nepal Sep 14 '15 at 13:37
  • Do you mean I need to create a new java class in my package? I created a level.java and added those codes and it shows red underlines in every line showing an error saying 'class' or 'interface' expected. What am I not understanding here? :( – Bikal Nepal Sep 15 '15 at 13:58
  • New java class I mean on src in your package – Skizo-ozᴉʞS ツ Sep 15 '15 at 14:02
  • Alright, I created in src I created a File-->Java Class named 'level' and inserted that code. No errors were shown. Now, where do I insert the "int Level = LevelPlayer.getLevelPlayer();" code? I tried to insert it in the mainactivity of first question but it showed error in Levelplayer. – Bikal Nepal Sep 15 '15 at 14:53
  • If your class is named levelplayer you should use int level = levelplayer.getLevelPlayer(); – Skizo-ozᴉʞS ツ Sep 15 '15 at 15:02
  • I named the class as 'lvl' and did "int level=lvl.getLevelPlayer();" It shows "cannot resolve symbol lvl" error! – Bikal Nepal Sep 15 '15 at 15:06
  • Your class is public static class lvl ? – Skizo-ozᴉʞS ツ Sep 15 '15 at 15:51
  • Yes, it's public static class lvl () – Bikal Nepal Sep 15 '15 at 17:14
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/89730/discussion-between-skizo-and-bik). – Skizo-ozᴉʞS ツ Sep 15 '15 at 19:00
  • Hey Skizo, may be you can help me with this: http://stackoverflow.com/questions/32605313/how-to-keep-score-in-a-ques-and-answer-game/32605754?noredirect=1#comment53078758_32605754 – Bikal Nepal Sep 17 '15 at 02:42
  • Yes but if i solves this question mark this as a solved please. – Skizo-ozᴉʞS ツ Sep 17 '15 at 08:36
  • this question is not solved yet...please see the chat – Bikal Nepal Sep 17 '15 at 09:10
  • Okay bik in a few hours ill join the chat since i cant do it now so ill solve the problem – Skizo-ozᴉʞS ツ Sep 17 '15 at 09:20
0

You can use SharedPreferences To Write to shared preference

SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();

to read

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
shaikhmanzoor
  • 89
  • 1
  • 9
0

it is simple. Just create a file to store information. You can do it in two ways. one is to save a simple xml or json, the second one is to create a model of your answer and serialize a collection of them and save them in file.

Remember that you should do it in some kind of structure way: json, xml, serialized class. it is much simpler to work in future with that

Fixus
  • 4,631
  • 10
  • 38
  • 67
0

You have a few options that you could try.

One option is as @Stultuske stated, you could try an XML or a TXT file stored on the users device. This (as well as a database) would persist between application sessions.

The other option that you have is you could create a singleton class. For example, a class called Globals (as below) :

    public class Globals {
        private static Globals instance;

        private String questionOneAnswer;


        private Globals(){}

        public String getQuestionOne()
        {
            return this.questionOneAnswer;
        }

        public void setQuestionOne(String questionOne)
        {
            this.questionOneAnswer = questionOne;
        }

        public static synchronized Globals getInstance()
        {
            if(instance==null)
            {
                instance=new Globals();
            }
            return instance;
        }
    }

This can then be called with Globals g = Globals.getInstance(); . This will only persist through your application instance; however, so if you are wanting to store it throughout app launches you can try the XML/TXT or SharedPreferences as stated by @shaikhmanzoor .

Also it is customary to define variable names with camelCase - ie answers rather than Answers, or typeH rather than typeh. Have a look here for the guidelines for Google Java coding.

Matt Davis
  • 470
  • 5
  • 16
0

For your first question just use SharedPreferences to save and fetch the data like this SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt("level_no_answer", answer_given_by_user); editor.commit();

and for your second question, you are using android:text="Type here..." in EditText. just replace that line by android:hint="Type here..."

rakshi059
  • 11
  • 7