背景:以登录为例
分别运用txt读写、xml的SharedPreferences使用、Gson解析json进行简单数据的存取。
Gson有关jar包的导入(Android视图下Gradle Scripts目录下的Module:app build.gradle文件中加入Gson坐标)
布局loginqq.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/beijing2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3fa0a0a0"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/change_user"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="24dp"
android:src="@drawable/wanzi" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/user_name"
android:layout_width="match_parent"
android:layout_height="50sp"
android:layout_margin="10dp"
android:gravity="center"
android:hint="用户名"
android:inputType="text"
android:padding="5dp" />
<Button
android:id="@+id/rl_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="@null" />
</RelativeLayout>
<EditText
android:id="@+id/user_password"
android:layout_width="match_parent"
android:layout_height="50sp"
android:layout_margin="10dp"
android:gravity="center"
android:hint="密码"
android:inputType="textPassword"
android:padding="5dp" />
<Button
android:id="@+id/btn_login"
android:layout_width="180dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:background="@drawable/reqiqiu"
android:onClick="loginClick"
android:text="登录"
android:textColor="#009688" />
<!-- android:onClick="loginClick"-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp">
<CheckBox
android:id="@+id/cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="记住密码"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
<Button
android:id="@+id/btn_zhuche"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@null"
android:gravity="center"
android:text="还没有账号? 去创建"
android:textColor="#050505"
android:textSize="18sp" />
</RelativeLayout>
PersonBean.java
public class PersonBean {
String name;
String pwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
页面交互MainActivity.java
//登录记住账号密码
public class MainActivity extends AppCompatActivity {
EditText etNumber;
EditText etPassword;
Button btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginqq);
etNumber =(EditText)findViewById(R.id.user_name);
etPassword=(EditText)findViewById(R.id.user_password);
btnLogin = (Button) findViewById(R.id.btn_login); // 设置按钮的点击事件
Map<String, String> userInfo = SaveTool.getUserInfoFromTXT(this);
// Map<String, String> userInfo = SaveTool.getUserInfosFromJson(this);
// Map<String, String> userInfo = SaveTool.getUserInfoFromXML(this);
if (userInfo != null) {
etNumber.setText(userInfo.get("name"));
etPassword.setText(userInfo.get("pwd"));
}
}
public void loginClick (View v)
{ // 当单击“登录”按钮时,获取账号和密码
String number = etNumber.getText().toString().trim();
String password = etPassword.getText().toString();
// 检验账号和密码是否正确
if (TextUtils.isEmpty(number)) {
Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
return;
}
// 登录成功
Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show(); // 保存用户信息
boolean isSaveSuccess = SaveTool.saveUserInfoinTXT(this, number, password);
// boolean isSaveSuccess = SaveTool.saveUserInfosinJSON(this, number, password);
// boolean isSaveSuccess = SaveTool.saveUserInfosinXML(this, number, password);
if (isSaveSuccess) {
Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
}
}
}
存取工具实现类SaveTool.java
public class SaveTool {
// 用户保存的文件名,封装起来 , 避免给调用者带来负担,
// 也避免了写入 / 读入不一致导致的失败
final static String txtfileName = "data.txt";
//注意:用SharedPreferences存储在xml文件不需要后缀名
final static String xmlfileName = "data";
final static String jsonfileName = "data.json";
// 保存账号和密码到data.txt文件中
public static boolean saveUserInfoinTXT(Context context, // 用户上下文
String number, // 用户的账号
String password) { // 用户的密码
try {
FileOutputStream fos = context.openFileOutput(txtfileName, Context.MODE_PRIVATE);
// 账号和密码间采用的是【 : 】 , 这就是一个简单的【文件格式】!
// 不论多么复杂的文件格式,如【 bmp 】,都有自己的一套标准
fos.write((number + ":" + password).getBytes());
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
//从data.txt文件中获取存储的QQ账号和密码
// 由于获取的是 账号和密码,因此应该用一个数据结构存下来,如 HashMap
public static Map<String, String> getUserInfoFromTXT(Context context) {
String content = "";
try {
FileInputStream fis = context.openFileInput(txtfileName);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
content = new String(buffer);
Map<String, String> userMap = new HashMap<String, String>();
// 根据文件格式解析数据内容
String[] infos = content.split(":"); // 存入数据结构中
userMap.put("name", infos[0]);
userMap.put("pwd", infos[1]);
Log.v("aa", "data.txt name: " + infos[0] + " pwd: " +infos[1]);
fis.close();
return userMap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// 保存账号和密码到data.xml文件中
public static boolean saveUserInfosinXML(Context context, String number,
String password) {
SharedPreferences sp = context.getSharedPreferences(xmlfileName,
Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putString("name", number);
edit.putString("pwd", password);
edit.commit();
return true;
}
//从data.xml文件中获取存储的QQ账号和密码
public static Map<String, String> getUserInfoFromXML(Context context) {
SharedPreferences sp = context.getSharedPreferences(xmlfileName,
Context.MODE_PRIVATE);
String number = sp.getString("name", null);
String password = sp.getString("pwd", null);
Map<String, String> userMap = new HashMap<String, String>();
userMap.put("name", number);
userMap.put("pwd", password);
Log.v("aa", "data.xml name: " + number + " pwd: " + password);
return userMap;
}
// 从data.json文件中取出保存的账号和密码
//解析json文件返回信息的集合
public static Map<String, String> getUserInfosFromJson(Context context) {
try {
FileInputStream is = context.openFileInput(jsonfileName);
byte[] buffer = new byte[is.available()];
is.read(buffer);
String json = new String(buffer, "utf-8");
//使用gson库解析JSON数据
Gson gson = new Gson();
PersonBean person = gson.fromJson(json, PersonBean.class);
Map<String, String> map = new HashMap<String, String>();
map.put("name", person.getName());
map.put("paw", person.getPwd());
Log.v("aa", "data.json name: " + person.getName() + " pwd: " + person.getPwd());
return map;
} catch (
Exception e) {
e.printStackTrace();
}
return null;
}
/**
*保存账号和密码到data.json文件中
* 封装JSON对象-带Key
* {
* "name":"liaoyanxia",
* "pwd":123456,
* }
*/
public static boolean saveUserInfosinJSON(Context context, String number,
String password) {
try {
FileOutputStream fos = context.openFileOutput(jsonfileName, Context.MODE_PRIVATE);
// json 对象
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", number);
jsonObject.put("paw", password);
// JSONArray jsonArray = new JSONArray();
// jsonArray.put(0, jsonObject);
fos.write(jsonObject.toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
在第一次登录时需要输入用户名和密码
按下“登录”按钮后触发时间保存在data/daya/包/对应的文件中
再次启动则可自动显示用户名密码
最后测试结果
Gson解析成功