如何从“编辑文本”字段中获取一个值到预先存在的字符串列表中?

时间:2019-04-21 17:49:05

标签: android android-intent android-edittext

我有一个应用程序,我试图让用户在注册帐户时回答一系列问题。然后,他们将以记忆力测试的形式询问他们这些问题。我已经实施了一个开放式问题功能,但是对问题的答案进行了硬编码。我想获取用户在注册过程中在“答案”字符串中输入的值。

问答数据库的代码:

package com.example.memory;

public class QuestionDatabase {

    public static String[] questions = {
            "What time did you wake up?",
            "What do you do first when you wake up?",
            "What did you have for breakfast?",
            "What time did you go to bed last night?",
            "What is your favorite colour?",
            "What is your favorite movie?",
            "What is your favorite food?",
    };

    public static String[] answers = {

            "9",
            "Bathroom",
            "Coffee",
            "11",
            "Blue",
            "Avengers",
            "Pizza",
    };

}

这是询问问题的代码:

package com.example.memory;

public class Q1 extends AppCompatActivity {

    Button save1;
    EditText ans1;
    String answer1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_q1);

        save1 = (Button) findViewById(R.id.save1);
        ans1 = (EditText) findViewById(R.id.ans1);
        answer1 = ans1.getText().toString();

        save1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save1();
            }
        });


    }

    public void save1() {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.putExtra("", ans1.getText().toString());
        startActivity(intent);
    }
}

如何获取在“ ans1”中输入的值到QuestionDatabase的String []答案部分。

2 个答案:

答案 0 :(得分:2)

最好使用String的ArrayList代替String Array

ArrayList<String> stringList = new ArrayList<>();
stringList.add("you String");

答案 1 :(得分:0)

对字符串使用HashSet而不是String数组。这样,您将能够轻松添加字符串,并且答案数据结构中不会重复字符串。

HashSet<String> answers = new HashSet<String>();  
set.add("input string);