1.文件(手机内存)
将数据以普通文件的形式保存在 /data/data/com.example.qqLogin/data.txt 中(不需要申请权限)
public static boolean saveUserInfo(String number,String password){
String path = "/data/data/com.example.qqLogin/data.txt";
try {
FileOutputStream fos = new FileOutputStream(path);
String info = number + "##" + password;
fos.write(info.getBytes());
fos.flush();
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static Map<String,String> getUserInfo(){
String path = "/data/data/com.example.qqLogin/data.txt";
try {
FileInputStream fis = new FileInputStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String text = reader.readLine();
if(!TextUtils.isEmpty(text)){
String[] infos = text.split("##");
Map<String,String> map = new HashMap<String, String>();
map.put("number",infos[0]);
map.put("password", infos[1]);
return map;
}
text.split("##");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
path可用api方式动态获取
String path = context.getFilesDir().getPath();// data数据目录
String path = context.getCacheDir().getPath();// data/cache缓存目录
以context打开FileOutputStream,默认路径为 /data/data/<包名>/filename ,具体mode权限见https://blog.youkuaiyun.com/qq_38709999/article/details/81708888
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 写数据
// 私有文件
writeToLocal("private.txt", Context.MODE_PRIVATE);
// 可读文件
writeToLocal("readable.txt", Context.MODE_WORLD_READABLE);
// 可写文件
writeToLocal("writeable.txt", Context.MODE_WORLD_WRITEABLE);
// 可读可写文件
writeToLocal("readable_writeable.txt", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
}
private void writeToLocal(String fileName, int mode) {
try {
FileOutputStream fos = openFileOutput(fileName, mode);
fos.write(("第一个程序写的数据: " + fileName).getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.文件(sdcard中)
将数据保存在 /mnt/sdcard/data.txt(需申请权限:android.permission.WRITE_EXTERNAL_STORAGE)
public static boolean saveUserInfo(Context context, String number, String password) {
try {
// 判断当前的手机是否有sd卡
String state = Environment.getExternalStorageState();
if(!Environment.MEDIA_MOUNTED.equals(state)) {
// 已经挂载了sd卡
return false;
}
File sdCardFile = Environment.getExternalStorageDirectory();
File file = new File(sdCardFile, "data.txt");
FileOutputStream fos = new FileOutputStream(file);
String data = number + "##" + password;
fos.write(data.getBytes());
fos.flush();
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static Map<String, String> getUserInfo(Context context) {
try {
// 判断当前的手机是否有sd卡
String state = Environment.getExternalStorageState();
if(!Environment.MEDIA_MOUNTED.equals(state)) {
// 已经挂载了sd卡
return null;
}
File sdCardFile = Environment.getExternalStorageDirectory();
File file = new File(sdCardFile, "data.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String text = br.readLine();
br.close();
if(!TextUtils.isEmpty(text)) {
Map<String, String> userInfoMap = new HashMap<String, String>();
String[] split = text.split("##");
userInfoMap.put("number", split[0]);
userInfoMap.put("password", split[1]);
return userInfoMap;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
3.SharedPreference的使用
将数据以键值对的形式保存在data.xml中,路径为 /data/data/<包名>/shared_prefs/data.xml
public static boolean saveUserInfo(Context context, String number,String password){
try {
SharedPreferences sp = context.getSharedPreferences("data",Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("number", number);
editor.putString("password", password);
editor.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static Map<String,String> getUserInfo(Context context){
try {
SharedPreferences sp = context.getSharedPreferences("data",Context.MODE_PRIVATE);
String number = sp.getString("number", null);
String password = sp.getString("password", null);
if(!TextUtils.isEmpty(number)&&!TextUtils.isEmpty(password)){
Map<String,String> map = new HashMap<String, String>();
map.put("number",number);
map.put("password", password);
return map;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
4.SQLite数据库
将数据以data.db方式保存在 /data/data/<包名>/databases/data.db 中
1.创建SQLiteOpenHelperDemo 实现虚基类 SQLiteOpenHelper
SQLiteOpenHelperDemo.class
package com.example.DB;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLiteOpenHelperDemo extends SQLiteOpenHelper{
public SQLiteOpenHelperDemo(Context context) {
super(context, "data.db", null, 1);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql = "";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
2.创建实体类(略)
Person.class
3.创建dao
PresonDao.class
package com.example.dao;
import java.util.ArrayList;
import java.util.List;
import com.example.DB.SQLiteOpenHelperDemo;
import com.example.pojo.Person;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class PresonDao {
private SQLiteOpenHelperDemo sQLiteOpenHelperDemo;
public PresonDao(Context context) {
sQLiteOpenHelperDemo = new SQLiteOpenHelperDemo(context);
}
/**
* 添加到person表一条数据
* @param person
*/
public void insert(Person person) {
SQLiteDatabase db = sQLiteOpenHelperDemo.getWritableDatabase();
if(db.isOpen()) { // 如果数据库打开, 执行添加的操作
// 执行添加到数据库的操作
db.execSQL("insert into person(name, age) values(?, ?);", new Object[]{person.getName(), person.getAge()});
db.close(); // 数据库关闭
}
}
/**
* 更据id删除记录
* @param id
*/
public void delete(int id) {
SQLiteDatabase db = sQLiteOpenHelperDemo.getWritableDatabase(); // 获得可写的数据库对象
if(db.isOpen()) { // 如果数据库打开, 执行添加的操作
db.execSQL("delete from person where _id = ?;", new Integer[]{id});
db.close(); // 数据库关闭
}
}
/**
* 根据id找到记录, 并且修改姓名
* @param id
* @param name
*/
public void update(int id, String name) {
SQLiteDatabase db = sQLiteOpenHelperDemo.getWritableDatabase();
if(db.isOpen()) { // 如果数据库打开, 执行添加的操作
db.execSQL("update person set name = ? where _id = ?;", new Object[]{name, id});
db.close(); // 数据库关闭
}
}
public List<Person> queryAll() {
SQLiteDatabase db = sQLiteOpenHelperDemo.getReadableDatabase(); // 获得一个只读的数据库对象
if(db.isOpen()) {
Cursor cursor = db.rawQuery("select _id, name, age from person;", null);
if(cursor != null && cursor.getCount() > 0) {
List<Person> personList = new ArrayList<Person>();
int id;
String name;
int age;
while(cursor.moveToNext()) {
id = cursor.getInt(0); // 取第0列的数据 id
name = cursor.getString(1); // 取姓名
age = cursor.getInt(2); // 取年龄
personList.add(new Person(id, name, age));
}
db.close();
return personList;
}
db.close();
}
return null;
}
/**
* 根据id查询人
* @param id
* @return
*/
public Person queryItem(int id) {
SQLiteDatabase db = sQLiteOpenHelperDemo.getReadableDatabase(); // 获得一个只读的数据库对象
if(db.isOpen()) {
Cursor cursor = db.rawQuery("select _id, name, age from person where _id = ?;", new String[]{id + ""});
if(cursor != null && cursor.moveToFirst()) {
int _id = cursor.getInt(0);
String name = cursor.getString(1);
int age = cursor.getInt(2);
db.close();
return new Person(_id, name, age);
}
db.close();
}
return null;
}
}
目录