SharedPreferenceActivity.java<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName" />
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Clear" />
</LinearLayout>
package com.platform;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SharedPreferenceActivity extends Activity {
/** Called when the activity is first created. */
private String SETTING = "datas";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//get SharedPreferences object
SharedPreferences setting = getSharedPreferences(SETTING, 0);
//get username and password's value (default value "")
String username = setting.getString("USERNAME", "");
String password = setting.getString("PASSWORD", "");
//get editText1 and editText2 object
final EditText editText1 = (EditText)findViewById(R.id.editText1);
final EditText editText2 = (EditText)findViewById(R.id.editText2);
editText1.setText(username);
editText2.setText(password);
//get button1
Button button1 =(Button)findViewById(R.id.button1);
button1.setText("Save");
//save datas
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences setting = getSharedPreferences(SETTING, 0);
setting.edit().putString("USERNAME", editText1.getText().toString())
.putString("PASSWORD", editText2.getText().toString()).commit();
}
});
//get button2
Button button2 =(Button)findViewById(R.id.button2);
button2.setText("Clear");
//clear datas (commit after clear )
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences setting = getSharedPreferences(SETTING, 0);
setting.edit().clear().commit();
}
});
}
}
评论