app在运行过程中,需要保存用户的一些信息。例如登录状态、账户信息等,安卓提供了多种方式来保存用户的数据。
1.key-value保存,通过SharedPreferences实现
SharedPreferencessp=getSharedPreferences("test",Context.MODE_PRIVATE);
sp.edit().putString("str","hello").commit();
Log.e(TAG,"save1:"+sp.getString("str",null));
2.文件保存,把数据写入内部存储器中
Filefile=getFilesDir();
Log.e(TAG,"save2:"+file.getAbsolutePath());
Filef2=newFile(file,"test.log");
try{
f2.createNewFile();
//在文件中写入数据
Log.e(TAG,"save2:"+f2.exists());
}catch(IOExceptione){
e.printStackTrace();
}
3.数据库保存,通过SQLite数据库读写结构化数据
通过openOrCreateDatabase创建数据库或者继承SQLiteOpenHelper实现
4.网络保存,通过http协议把数据保存在服务器上
URLurl=newURL("http://www.android.com/");
HttpURLConnectionurlConnection=(HttpURLConnection)url.openConnection();
try{
InputStreamin=newBufferedInputStream(urlConnection.getInputStream());
readStream(in);
}finally{
urlConnection.disconnect();
}
实例下载:https://files.cnblogs.com/files/bruce2020/TestSQLite.zip