如何在谜语游戏中保存答案而不创建数据库



我创造了一个带有不同关卡的问答游戏,每个关卡包含一个问题。我没有用数据库创建它。我只是用了字符串。当用户在第一级回答问题时,他会被带到第二级,但当用户返回到第一级时,他必须再次输入答案,即使他之前已经解决了这个问题。无论如何,在JAVA中保持答案在类型面板(如果用户解决了它),而不必创建一个数据库??此外,在输入面板中输入时,用户必须删除"在这里输入…",然后回答。无论如何,当用户点击输入"在这里输入…"是自动擦除?

这是我的一级活动。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>

这是我的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);
    }
}

同样,toast显示在有键盘的地方。有没有办法把吐司屏幕移到屏幕上清晰可见的地方?

我给你两种方法:

按如下命令创建LevelEarned类:

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

每次你得到一个Intent(因为用户已经正确回答了问题)只需键入:

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

我使用的最好的方法是SharedPreferences

您可以使用SharedPreferences保存任何基本数据:布尔值、浮点数、整型、长值和字符串。此数据将在用户会话期间持续存在(即使您的应用程序被终止)。

您要做的第一件事是将此数据存储在SharedPreferences上,并使用Editor执行如下操作:

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();

注意

我猜你会在用户接受问题后立即做,所以,你会在Button click上做,所以你必须传递v.getContext()作为上下文,如果你不是在ButtonClick上,你在onCreate()上,只是调用this来引用你的context

要获取存储的数据(级别),您需要这样做:

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

让我给你解释一下。

第一个参数它是找到SharedPreference的关键,所以它不会改变,第二个是一个默认值,它被用来以防它没有找到任何"player_level" SharedPreferences

希望它能帮助你继续在你的代码:)

EDIT2

创建SharedPreferences preferences作为全局变量,如下所示:

public SharedPreferences preferences;

然后在你的onClick()方法中添加这些通道:

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();
            }
        }
    });

如果你想知道的水平,你只需要做:

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

3

编辑

按如下方式创建一个类:

 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;
     }
  }

每次你想问玩家的等级时,你都要问:

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

所以在每个问题之后,你可以问关卡,然后放下一个问题。

我做了一些改变,删除你的等级类,并把这个代码:

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;
}

然后在你的MainActivity(或者任何你需要知道玩家级别的地方),你必须这样写:

public levelplayer mlevelplayer;

然后在你的onCreate()里面添加这个:

mlevelplayer = new levelplayer(this);
int level  = mlevelplayer.getLevelPlayer();

您可以使用SharedPreferences写入共享首选项

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

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);

很简单。只需创建一个文件来存储信息。有两种方法。一个是保存一个简单的XML或json,第二个是创建一个你的答案的模型,并序列化它们的集合,并将它们保存在文件中。

记住,你应该以某种结构方式来做:json, xml,序列化类。以后使用

就简单多了

你有几个选项可以尝试。

一个选项是@Stultuske所说的,您可以尝试存储在用户设备上的XML或TXT文件。此(以及数据库)将在应用程序会话之间持续存在。

另一个选择是你可以创建一个单例类。例如,一个名为Globals的类(如下所示):

    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;
        }
    }

可以通过Globals g = Globals.getInstance();调用。这只会在应用程序实例中持续存在;然而,如果你想在应用程序启动时存储它,你可以尝试@shaikhmanzoor所述的XML/TXT或SharedPreferences。

习惯上也用驼峰大小写定义变量名——比如answers而不是Answers,或者typeH而不是typeh。请看这里的Google Java编码指南

对于您的第一个问题,只需使用SharedPreferences来保存和获取数据,就像这样SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt("level_no_answer", answer_given_by_user); editor.commit();

和你的第二个问题,你正在使用android:text="Type here…"在EditText。只需将这一行替换为android:hint="Type here…"

最新更新