一、整体工程图
二、SharePreferenceWriteActivity.java
package org.ourunix.android.sharepreferencewrite; import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText; public class SharePreferenceWriteActivity extends Activity implements OnClickListener{
private SharedPreferences prference;
private String PREF_NAME = "PREF_NAME";
private String KEY = "TestValue";
private EditText mEditText;
private Button mButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mEditText = (EditText) findViewById(R.id.writeTV);
mButton = (Button) findViewById(R.id.submit);
mButton.setOnClickListener(this);
} @Override
public void onClick(View v) {
// TODO Auto-generated method stub prference = getSharedPreferences(PREF_NAME, MODE_WORLD_READABLE );
prference.edit().putString(KEY, mEditText.getText().toString()).commit();
}
}
三、SharePreferenceReadActivity.java
package org.ourunix.sharepreferenceread; import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.widget.TextView; public class SharePreferenceReadActivity extends Activity {
/** Called when the activity is first created. */
private SharedPreferences prference;
private String NAME = "PREF_NAME";
private String KEY = "TestValue";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
setContentView(tv); String tmp;
Context c = null; try {
c = this.createPackageContext("org.ourunix.android.sharepreferencewrite", CONTEXT_IGNORE_SECURITY); } catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} if (c != null)
prference = c.getSharedPreferences(NAME, 0);
tmp = prference.getString(KEY, "nothing");
tv.setText(tmp);
}
}