Using SharedPreferences to store password
package app.test;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
public class Test extends Activity {
public static final String SETTING_INFOS = "SETTING_Infos";
public static final String NAME = "NAME";
public static final String PASSWORD = "PASSWORD";
private EditText field_name;
private EditText filed_pass;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
field_name = (EditText) findViewById(R.id.name);
filed_pass = (EditText) findViewById(R.id.password);
SharedPreferences settings = getSharedPreferences(SETTING_INFOS, 0);
String name = settings.getString(NAME, "");
String password = settings.getString(PASSWORD, "");
field_name.setText(name);
filed_pass.setText(password);
}
protected void onStop(){
super.onStop();
SharedPreferences settings = getSharedPreferences(SETTING_INFOS, 0);
settings.edit()
.putString(NAME, field_name.getText().toString())
.putString(PASSWORD, filed_pass.getText().toString())
.commit();
}
}
//main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="SharedPreferences demo"
/>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Name:" />
<EditText android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Password:" />
<EditText android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:password="true"
android:text="" />
</LinearLayout>
Related examples in the same category