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

4
我创建了一个问题和答案游戏,有不同的等级,每个等级都包含一个问题。我没有使用数据库,只是用字符串创建它。当用户在第一级回答一个问题后,他会被带到第二级,但当用户返回第一级时,即使他以前解决过该问题,他仍然必须再次输入答案。在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将显示在其位置。是否有办法将toast屏幕移动到屏幕上某个明显可见的地方?

1
文本文件,XML 文件,... - Stultuske
5个回答

1
我将为您提供两种方法来完成它: 创建一个名为 LevelEarned 的类,如下所示:
public class LevelEarned {
 public static int level = 0;
}
每次你获得一个Intent(因为用户已经正确地回答了问题),只需要输入:
LevelEarned.level = 1; // 1 depends with the level you have answered correctly

最好的方法是使用SharedPreferences,它可以用于保存任何原始数据类型:布尔值、浮点数、整数、长整型和字符串。即使应用程序被杀死,这些数据也会持久化保存。

首先,您需要使用Editor将这些数据存储在SharedPreferences中,具体操作如下:

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上执行它,因此,如果您不在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

每个问题后面都可以询问难度并提出下一个问题。

编辑4

我做了一些更改,删除你的lvl类并放置以下代码:

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

@Bik,请查看我的编辑并告诉我它是否有效,如果无效,我会更新代码。 - Skizo-ozᴉʞS ツ
还有问题吗? - Skizo-ozᴉʞS ツ
嗯,Bik?你没有标记任何答案为正确的,也没有人帮助你吗? - Skizo-ozᴉʞS ツ
嘿Skizo,抱歉晚发了,我有点忙。我不明白最后一行代码应该粘贴在哪里,以及在游戏完成关卡后如何保存正确答案?我指的是这段代码:SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); int level = preferences.getInt("player_level", 0); //level是玩家当前的等级。 - Bikal Nepal
好的,我已经在第一级(即OneActivity)的问题1的活动中添加了“public SharedPreferences preferences;”,请参见上面,我已经进行了编辑。我还在onclick()内部进行了更改,并且我也对其他几个问题的活动进行了更改,但是当重新打开级别时它并没有保存答案。我仍然不明白我应该在哪里添加最后一行代码。我是否应该在每个活动中都添加它(我为每个问题制作了一个活动,并且需要在输入正确答案后将答案保存在输入字段中)?如果是,请问我应该在哪一行确切地添加它?请帮忙! - Bikal Nepal
显示剩余13条评论

0

这很简单。只需创建一个文件来存储信息。您可以用两种方式来实现。 一种是保存一个简单的xml或json,另一种是创建一个答案模型并序列化它们的集合并将其保存在文件中。

记住,您应该以某种结构方式进行操作:json、xml、序列化类。这样未来的工作会更加简单。


0

对于您的第一个问题,只需使用SharedPreferences来保存和获取数据,如下所示:

SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt("level_no_answer", answer_given_by_user); editor.commit();

对于您的第二个问题,您正在EditText中使用android:text="Type here...",只需将该行替换为android:hint="Type here..."即可。


0
你可以使用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);

0

你有几个选项可以尝试。

一个选项是像@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();来调用。然而,它只会在应用程序实例中持续存在; 如果您想在应用程序启动期间存储它,可以尝试XML / TXT或SharedPreferences,如@shaikhmanzoor所述。

此外,惯例是使用camelCase定义变量名 - 例如answers而不是AnswerstypeH而不是typeh。请参阅here以获取Google Java编码指南。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,