classSharedPrefs

Last-modified: 2015-03-18 (水) 12:34:36
public class SharedPrefs extends Activity implements OnClickListener{

	EditText  sharedData;
	TextView dataResults;
	public static String filename = "MySharedString";
	SharedPreferences someData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO 自動生成されたメソッド・スタブ
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sharedpreferences);
		setupVariables();
		someData = getSharedPreferences(filename, 0);
	}
	private void setupVariables() {
		// TODO 自動生成されたメソッド・スタブ
		Button save = (Button) findViewById (R.id.bSave);
		Button load = (Button) findViewById (R.id.bLoad);
		sharedData = (EditText) findViewById (R.id.etSharedPrefs);
		dataResults = (TextView) findViewById (R.id.tvLoadSharedPrefs);
		save.setOnClickListener(this);
		load.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO 自動生成されたメソッド・スタブ
		switch(v.getId()){
			case R.id.bSave:
				String stringData = sharedData.getText().toString();
				SharedPreferences.Editor editor = someData.edit();
				editor.putString("sharedString", stringData);
				editor.commit();
				break;
			case R.id.bLoad:
				someData = getSharedPreferences(filename, 0);
				String dataReturned = someData.getString("sharedString", "Couldn't Load Data");
				dataResults.setText(dataReturned);
				break;
		}
	}
}



~
~<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <android.widget.EditText
        android:id="@+id/etSharedPrefs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         >
    </android.widget.EditText>
    <Button
        android:id="@+id/bSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save" />
    <Button
        android:id="@+id/bLoad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load" />
    <TextView
        android:id="@+id/tvLoadSharedPrefs"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load your data" />
~</LinearLayout>