2012-03-12 69 views
0

我已經在我的Android應用程序的Java代碼創建了兩個的EditText對象,如何在Android中使用Java代碼在string.xml中添加字符串?

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,以將T wo數據庫的res/values/Strings.xml文件中的條目,&我不知道該怎麼做。

請引導我進一步。

+0

你可以做String s2 = editable2.toString();在分配字符串之前,不需要初始化字符串 – dymmeh 2012-03-12 21:39:17

回答

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 
1

這是不可能的 - 一個應用的APK(包括它的資源)不能在運行時改變。我並不完全確定所有原因,但我能想到的一個顯而易見的事情是,R.java需要包含對您的字符串的引用才能訪問它,並且此文件由編譯器生成當你創建APK時。

如果您需要在會話中保留一個字符串,則應該使用Android提供的其中一個data storage mechanisms進行研究,例如SharedPreferences

相關問題