我用一組簡單的&獲取類,這樣我可以檢索整個應用的過程變量,但我需要存儲這個類以備後用,所以我想用共享偏好來存儲但我不知道如何正確實施。我試圖在setter方法中實現共享首選項,並且沒有錯誤,但是當我運行時會崩潰。安卓:共享偏好和getter和setter方法
下面是類
import android.app.Activity;
import android.content.SharedPreferences;
import android.widget.EditText;
public class Passcode extends Activity {
private String pin;
public static final String PREFS_PASS = "MyPrefsFile";
EditText txtNewPin = (EditText)findViewById(R.id.txt_EnterNewPin);
SharedPreferences Pincode = getSharedPreferences(PREFS_PASS,0);
SharedPreferences.Editor editor = Pincode.edit();
public String getPin() {
Pincode.getString(pin,"0000");
return pin;
}
public void setPin(String pin) {
editor.putString(pin, txtNewPin.getText().toString());
editor.commit();
}
}
所以很多東西丟失片斷中,我建議你應該多看一些關於Android和活動。與你合作應該重寫'onCreate()'在那裏加載你的佈局,在完成之後你可以使用'findViewById()'設置你的'EditText',查看共享首選項處理的答案。 – Robert
林不知道我正確解釋這個但這並不意味着是一個活動我只作了重要的是能夠從另一個XML文件中的EditText帶給我只是希望能夠去object.setPin其他類ANS有值存儲在共享的喜好,並能夠通過去object.getPin – Eunan
歐凱稱呼它,但你必須加載反正你的佈局,才能在佈局中訪問UI組件。但是你的佈局是在某個班加載的,對吧?你爲什麼不在那裏有你的getter和setter? – Robert