Android中用shardpreferance编写一个保存账号和密码的代码
时间: 2024-04-29 13:25:45 浏览: 62
以下是一个示例代码,使用shardpreferance保存账号和密码:
1. 首先,在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
2. 然后,在MainActivity.java文件中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private EditText etUsername;
private EditText etPassword;
private Button btnSave;
private Button btnLoad;
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = findViewById(R.id.et_username);
etPassword = findViewById(R.id.et_password);
btnSave = findViewById(R.id.btn_save);
btnLoad = findViewById(R.id.btn_load);
sharedPreferences = getSharedPreferences("myPreferences", Context.MODE_PRIVATE);
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", etUsername.getText().toString());
editor.putString("password", etPassword.getText().toString());
editor.apply();
Toast.makeText(MainActivity.this, "保存成功!", Toast.LENGTH_SHORT).show();
}
});
btnLoad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = sharedPreferences.getString("username", "");
String password = sharedPreferences.getString("password", "");
etUsername.setText(username);
etPassword.setText(password);
Toast.makeText(MainActivity.this, "读取成功!", Toast.LENGTH_SHORT).show();
}
});
}
}
```
3. 最后,在activity_main.xml文件中添加以下布局:
```xml
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<EditText
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名"/>
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
android:inputType="textPassword"/>
<Button
android:id="@+id/btn_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="保存"/>
<Button
android:id="@+id/btn_load"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="读取"/>
</LinearLayout>
```
以上代码实现了保存账号和密码,并在下次打开应用程序时自动加载它们。
阅读全文