如何在没有创建数据库的情况下在谜语游戏中保存答案?

时间:2015-09-01 06:25:33

标签: java android

我创建了一个不同级别的问答游戏,每个级别都包含一个问题。我没有用数据库创建它。我刚刚用过字符串。当用户在第一级回答问题时,他被带到第二级,但当用户返回到第一级时,即使他之前已经解决了,他也必须再次输入答案。无论如何在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);
    }
}

此外,烤面包显示在键盘的位置。无论如何都要将吐司屏幕移动到屏幕上清晰可见的位置?

5 个答案:

答案 0 :(得分: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上执行该操作,因此您必须作为上下文v.getContext()传递如果您不在ButtonClick,并且您在onCreate(),请致电this,以便推荐您的context

要获取存储的数据(级别),您需要执行此操作:

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

让我们向您解释一下。

第一个参数是找到SharedPreference的关键,因此它不会发生变化,第二个参数是默认值,如果它不是&#39 ;找不到任何"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

所以在每个问题之后你都可以询问关卡并提出下一个问题。

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

答案 1 :(得分: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);

答案 2 :(得分:0)

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

请记住,您应该采用某种结构方式:json,xml,序列化类。使用

将来工作要简单得多

答案 3 :(得分: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();调用此方法。这只会在您的应用程序实例中持续存在;但是,如果您希望在整个应用程序启动期间存储它,您可以尝试@shaikhmanzoor所述的XML / TXT或SharedPreferences。

习惯上用camelCase定义变量名称 - 即answers而不是Answers,或typeH而不是typeh。请查看here以获取Google Java编码指南。

答案 4 :(得分: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();

对于你的第二个问题,你使用的是android:text =&#34;在这里输入...&#34;在EditText中。只需用android替换该行:hint =&#34;在此输入...&#34;