我遇到了一些麻煩恢復SharedPreferences到活動從原來的分開。SharedPreferences分佈在不同的活動在同一應用程序
我有被利用這一點,「NewCustomerActivity」和「OldCustomerActivity」兩班。兩者都應該具有對文件的讀/寫訪問權限 - 目前我只是通過從NewCustomerActivity中寫入來進行測試,NewCustomerActivity會在殺死活動時適當地恢復表單數據;不過,我在打開OldCustomerActivity時收到一個FC,該OldCustomerActivity嘗試用與NullPointerException相同的NewCustomerActivity來恢復數據。
NewCustomerActivity:
public class NewCustomerActivity extends Activity {
public static final String USER_INFO = "UserInfoFile"; // This file will the store the user's information for later use.
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newcustomer);
SharedPreferences userInfo = getSharedPreferences(USER_INFO, 0); // Restore our earlier saved info.
EditText et;
...... (Other code is irrelevant)
}
OldActivityNew是一樣的:
public class OldCustomerActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.oldcustomer);
SharedPreferences userInfo = getSharedPreferences(NewCustomerActivity.USER_INFO, 0); // Restore our earlier saved info.
EditText et;
et = (EditText) findViewById(R.id.EditTextName);
et.setText(userInfo.getString("name",""));
..... (Continue to fill forms in this context)
}
這兩個活動的填補與以前信息的形式,如果有什麼改變了更新在提交的文件;然而只有NewCustomerActivity似乎是填充文件(或不強制關閉是具體的)
我試着在MODE_WORLD_READABLE(第二個參數= 1)設置SharedPreference以及無濟於事;即使我相信我應該可以在PRIVATE中運行它。我也嘗試引用USER_INFO作爲NewCustomerActivity.USER_INFO
我必須失去了一些東西明顯 - 但任何幫助,將感謝讚賞,因爲這是我第一次嘗試,!
編輯:
對於那些問我是怎麼寫入文件:
SharedPreferences userInfo = getSharedPreferences(USER_INFO, 0); // Save info for later
SharedPreferences.Editor userInfoEditor = userInfo.edit();
EditText et;
et = (EditText) findViewById(R.id.EditTextName);
String nameValue = et.getText().toString();
userInfoEditor.putString("name", nameValue);
如何在每個活動中寫入SharedPreference? – 2012-01-18 01:18:48
這裏的一個片段: SharedPreferences USERINFO = getSharedPreferences(USER_INFO,0); //保存以後的信息 \t \t SharedPreferences。編輯器userInfoEditor = userInfo.edit(); \t \t EditText et; \t \t et =(EditText)findViewById(R.id.EditTextName); \t \t String nameValue = et.getText()。toString(); \t \t userInfoEditor.putString(「name」,nameValue); – 2012-01-18 02:44:04
看起來你沒有提交寫操作。爲了讓'SharedPreferences'生效,在完成所有編輯之後,您需要執行'userInfoEditor.commit();' – curioustechizen 2012-01-18 03:02:10