数据存储
文件存储
1.写入数据到文件中
使用Context类中的openFileOutput()方法,该方法需要传入两个参数,第一个是文件名,指定数据要存入哪一个文件夹,第二个参数为文件的操作模式
openFileOutput()方法返回一个FileOutputStream对象,然后以Java流的方式写入到文件即可。
public void save(String inputext){
FileOutputStream outputStream=null;
BufferedWriter writer=null;
try {
outputStream=getContext().openFileOutput("data",Context.MODE_PRIVATE);
writer=new BufferedWriter(new OutputStreamWriter(outputStream));
writer.write(inputext);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (writer!=null){
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
save()方法 传入一个需要保存的String。
2.从文件中读取数据
同样,使用Context类中的openFileInput()方法,传入一个参数,为需要读取数据的地址
public String load() {
FileInputStream in=null;
BufferedReader reader=null;
StringBuilder content=new StringBuilder();
try {
in=getContext().openFileInput("data");
reader=new BufferedReader(new InputStreamReader(in));
String line="";
while ((line!=null)){
line=reader.readLine();
content.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}
返回为获得的数据
SharedPrefrences存储
使用该方法存储数据分为三步
1.得到SharedPreferences对象
2.调用SharedPreferences对象的edit方法获取一个SharedPreferences.Editor对象
3.使用edit对象保存数据,最后调用apply方法保存
editor.putString("account",ACCOUNT);
editor.putString("password",PASSWORD);
editor.apply();
读取数据方法很简单,调用SharedPreferences对象的getString(),getint(),getAll()等方法
preferences.getString("account","");
第一个参数为保存数据的字段名,第二个参数为数据为空时获取的默认值
实例Demo
public class LoginActivity extends AppCompatActivity {
private final String PASSWORD="1";
private final String ACCOUNT="1";
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private Button button;
private EditText password;
private EditText account;
@SuppressLint("CommitPrefEdits")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
button=findViewById(R.id.bt_login);
password=findViewById(R.id.et_password);
account=findViewById(R.id.et_account);
//用editor存入数据 preferences取出数据
preferences= PreferenceManager.getDefaultSharedPreferences(this);
editor=preferences.edit();
editor.putString("account",ACCOUNT);
editor.putString("password",PASSWORD);
editor.apply();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String ac=account.getText().toString();
String ps=password.getText().toString();
if(preferences.getString("account","").equals(ac)
&&preferences.getString("password","").equals(ps)){
Intent intent=new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
else{
Toast.makeText(LoginActivity.this,"密码或账户错误,请重新输入!",Toast.LENGTH_SHORT).show();
}
}
});
}
}
SQLite数据库存储
使用Android的提供的SQLiteOpenHelper帮助类来使用SQLite,创建数据库和表