如何在Android中使用Java代码在string.xml中添加字符串?

时间:2012-03-12 21:32:30

标签: java android string android-edittext

我在My android应用程序的Java代码中创建了两个EditText对象,如

final EditText et1=(EditText)findViewById(R.id.editText1);
final EditText et2=(EditText)findViewById(R.id.editText2);

然后在按钮的onClick()事件上,称为参数为 -

的方法
addStringToXmlFile(et1.getText(),et2.getText());

现在在下面这个方法的定义中,我写了 -

private void addStringToXmlFile(Editable editable1,Editable editable2){
        String s1=new String();
        s1=editable1.toString();

        String s2=new String();
        s2=editable2.toString();
}

问题在于,现在我想使用这两个String对象s1,s2在数据库的res/values/Strings.xml文件中创建两个条目,&我不知道怎么做。

请进一步指导我。

2 个答案:

答案 0 :(得分:1)

这是不可能的 - 应用程序的apk(包括它的资源)无法在运行时更改。我不完全确定所有原因,但我能想到的一个显而易见的事情是R.java需要包含对String的引用才能访问它,并且该文件由编译器生成当你创建APK时。

如果您需要跨会话保留字符串,则应考虑使用Android提供的多个data storage mechanisms之一,例如SharedPreferences

答案 1 :(得分:0)

请查看使用SharedPreferences来存储字符串值。

//Saving your strings
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("s1", s1);
editor.putString("s2", s2);
editor.commit();

//retrieving your strings from preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
String s1 = prefs.getString("s1", ""); //empty string is the default value
String s2 = prefs.getString("s2", ""); //empty string is the default value