2017-09-13 49 views
-2

我想創建一個簡單的列表樣式應用程序。我已經使用SharedPreferences成功地保存了字符串,因爲我可以在日誌中引用它,但是我希望這樣做是爲了使字符串保持附加到文本字段而不是在每次重新打開應用程序時清除(直到更改或由用戶刪除)。任何其他建議,將不勝感激。如何保存文本字段的響應而不清除

(MainActivity)

public void go(View view) { 

    Intent intent1 = new Intent(SecondActivity.this, myPreferences.class); 

    String passGoal1 = goal1.getText().toString(); 

    intent1.putExtra("goal1", passGoal1); 

    startActivity(intent1); 
} 

如在第一個答案引用另外實施myPreferences類。

public class myPreferences { 

    private SharedPreferences pref; 

    private SharedPreferences.Editor editor; 

    private Context context; 

    int PRIVATE_MODE = 0; 

    private static final String PREF_NAME = "MyPreferencesName"; 

    public final static String KEY_NAME = "key_value"; 

    public myPreferences(Context context) { 

     this.context = context; 

     pref = context.getSharedPreferences(PREF_NAME,PRIVATE_MODE); 

     editor = pref.edit(); 
    } 

    public void setFunction(String data) { 

     editor.putString(KEY_NAME, data); 
    } 
} 

回答

1

在您的共享偏好做出獲取存儲的數據並查看它每次在文本框

public class MyPreferences { 

private SharedPreferences pref; 

// Editor for Shared preferences 
private SharedPreferences.Editor editor; 

// Context 
private Context context; 

// Shared pref mode 
int PRIVATE_MODE = 0; 

// Sharedpref file name 
private static final String PREF_NAME = "MyPreferencesName"; 

public final static String KEY_NAME = "key_value"; 

public MyPreferences(Context context) { 
    this.context = context; 
    pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE); 
    editor = pref.edit(); 
} 

public void setFunction(String data) { 
    editor.putString(KEY_NAME, data); 
    editor.commit(); 
} 

public String getFunction() { 
    return pref.getString(KEY_NAME, ""); 
} 
} 

而在你的活動初始化SharedPreferences並執行以下操作get函數:

private MyPreferences myPreferences; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    myPreferences = new MyPreferences(this); 

    //To set EditText data from SavedPreferences 
    textField.setText(myPreferences.getFunction()); 
} 

//To save the latest data from EditText. 
@Override 
protected void onStop() { 
    Log.d("LifeCycle", "onStop: "); 
    super.onStop(); 
    myPreferences.setFunction(editText.getText().toString()); 
} 
+0

非常感謝,但在嘗試設置AppSettingsPreference類時出現錯誤,有什麼建議? –

+0

我很高興能夠幫助你,我編輯了我的答案,再次嘗試,並希望現在一切都好起來。 @Ian F. –

+0

非常感謝。最後一個問題很抱歉,我怎麼能將文本框中的數據傳遞給這個新類?我會用一個新的意圖來回傳遞它嗎? –