Android对数据进行存储和读取
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.conserve.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名"
android:id="@+id/name"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
android:digits="0123456789"
android:id="@+id/password"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="写入"
android:id="@+id/wright"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="读取"
android:id="@+id/read"/>
</LinearLayout>
</LinearLayout>
MainActivity:
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText Name;
private EditText password;
private Button wright;
private Button read;
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name=(EditText)findViewById(R.id.name);
password=(EditText)findViewById(R.id.password);
wright=(Button)findViewById(R.id.wright);
read=(Button)findViewById(R.id.read);
//获得对象preferences,创建文件及其属性(这里设置为可追加的属性)
preferences=getSharedPreferences("Save",MODE_APPEND);
//编辑器
editor=preferences.edit();
//分别对两个按钮进行监听
wright.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (wright.isClickable()) {
//从两个输入框内提取相应的数据
editor.putString("Name",Name.getText().toString());
editor.putString("password",password.getText().toString());
editor.commit();
editor.clear();
Toast.makeText(MainActivity.this,"已保存",Toast.LENGTH_SHORT).show();
}
}
});
read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (read.isClickable()) {
//提取文件内的数据
SharedPreferences data = getSharedPreferences("Save",MODE_APPEND);
String name = data.getString("Name", "");
String password = data.getString("password", "");
Toast.makeText(MainActivity.this,"姓名为"+name+"密码为"+password,Toast.LENGTH_LONG).show();
}
}
});
}
}