【问题标题】:How to save an answer in a riddle game without creating a database?如何在不创建数据库的情况下在谜语游戏中保存答案?
【发布时间】:2015-09-16 03:00:07
【问题描述】:

我创建了一个具有不同级别的问答游戏,每个级别都包含一个问题。我没有用数据库创建它。我只是用字符串。当用户在第一级回答一个问题时,他会被带到第二级,但是当用户返回到第一级时,即使他之前已经解决了,他也必须再次输入答案。无论如何,JAVA 中是否有将答案保留在类型面板中(如果用户解决了它)而无需创建数据库?此外,在类型面板中输入时,用户必须删除“在此处输入...”然后回答。无论如何,当用户点击输入“在此处输入...”时会自动删除吗?

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

这是我的 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 会显示在有键盘的地方。有没有办法将吐司屏幕移动到屏幕上清晰可见的位置?

【问题讨论】:

  • txt 文件,xml 文件,...

标签: java android


【解决方案1】:

我会给你两种方法来做到这一点:

如下创建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 上执行此操作,因此如果您不在 ButtonClick 上,则必须作为上下文传递 v.getContext()而您在您的onCreate() 上,只需致电this 推荐您的context

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

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

让我们稍微解释一下。

第一个参数是查找SharedPreference 的关键,因此它不会改变,第二个参数是默认值,用于在找不到任何"player_level" SharedPreferences 时使用。

希望它对您继续编写代码有所帮助:)

编辑2

如下创建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

因此,在每个问题之后,您都可以询问级别并提出下一个问题。

EDIT4

我做了一些更改,删除你的 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,抱歉,这是一个迟到的帖子,我有点忙。我不明白我必须在哪里粘贴最后一行,以及在玩完关卡后如何在游戏中保存正确的答案?我说的是最后一个代码: SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); int level = preferences.getInt("player_level", 0); //level是玩家的当前等级。
  • 你必须把它放在你想知道玩家等级的任何地方,在你的第一个活动中,第二个,任何地方。我应该更新我的答案让你接受这个答案吗?
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    这很简单。只需创建一个文件来存储信息。你可以通过两种方式做到这一点。 一种是保存一个简单的 xml 或 json,第二种是为您的答案创建一个模型并序列化它们的集合并将它们保存在文件中。

    请记住,您应该以某种结构方式进行操作:json、xml、序列化类。以后使用它会简单得多

    【讨论】:

      【解决方案4】:

      您可以尝试几个选项。

      如@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。查看here 了解 Google Java 编码指南。

      【讨论】:

        【解决方案5】:

        对于您的第一个问题,只需使用 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..."

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-10-21
          • 1970-01-01
          相关资源
          最近更新 更多