一,最简单实用的SharePreference
首先获取保存数据和提交数据的实例对象,参考如下:
shareDB = mContext.getSharedPreferences(ConstData.Share._SHARE_TBALE, Context.MODE_PRIVATE); sharEdit = shareDB.edit();
然后就可以开始保存和读取数据了:
// 保存数据 sharEdit.putString(ConstData.Share._SHARE_COLUMN1, str); sharEdit.commit(); // 读取数据 String str1 = shareDB.getString(ConstData.Share._SHARE_COLUMN1, null);
二,然后就是保存在文件中。这个文件在当前软件的目录下。所以软件卸载了,数据也随之被清除
查询(读取)数据如下:即使这个文件根本就不存在也没关系
public String readFileData(String readFileName) { String res = ""; try { FileInputStream fin = mContext.openFileInput(readFileName); // 一口气读完 int length = fin.available(); byte[] buffer = new byte[length]; fin.read(buffer); res = EncodingUtils.getString(buffer, "utf-8"); fin.close(); } catch (Exception e) { e.printStackTrace(); return null; } return res; }
保存数据如下:
public boolean saveFile(String saveContent, String saveFileName) { try { byte[] buf = saveContent.getBytes(); FileOutputStream fos = mContext.openFileOutput(saveFileName, Context.MODE_PRIVATE); fos.write(buf); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
三,保存在SD卡中,比如图片,配置文件等。
首先判断有无SD卡,有的话,定义好文件在SD中的路径和文件名称
private final String FILEPATH = "/configfile/userinfo/"; private final String FILENAME = "myfile.txt"; //--------------------------------- public String createSDCardDir() { String path = null; if (Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { File sdcardDir = Environment.getExternalStorageDirectory(); path = sdcardDir.getPath() + FILEPATH; File path1 = new File(path); if (!path1.exists()) { path1.mkdirs(); } } return path; }
保存文件参考如下代码
try { File file = new File(pathStr + FILENAME); file.createNewFile();// 不存在该文件的时候才创建。 FileOutputStream fos = new FileOutputStream(file); fos.write(str.getBytes()); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(mContext, "保存失败", Toast.LENGTH_SHORT).show(); }
查询数据参考如下
try { File file = new File(pathStr + FILENAME); file.createNewFile(); InputStream fis = new FileInputStream(file); byte[] buffer = new byte[fis.available()]; fis.read(buffer); String str1 = new String(buffer); if (TextUtils.isEmpty(str1)) { Toast.makeText(mContext, "无数据", Toast.LENGTH_SHORT).show(); } else { et1.setText(str1); } } catch (Exception e) { e.printStackTrace(); }
最后别忘了在配置文件中添加操作外接存储设备的权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
四、SQLite关系型数据库
首先建立数据库DB和表Table,参考如下类:
public class DBHelper extends SQLiteOpenHelper { // 得到可写的SqliteDatabase public SQLiteDatabase sqliteDB = this.getWritableDatabase(); public DBHelper(Context context) { super(context, ConstData.SQL._SQL_DBNAME, null, 1); } public void onCreate(SQLiteDatabase db) { // 创建表,两列 String sql = "create table " + ConstData.SQL._SQL_TABLE1 + "(_id integer primary key autoincrement," + ConstData.SQL._SQL_COLUMN1 + " text," + ConstData.SQL._SQL_COLUMN2 + " text)"; db.execSQL(sql); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
然后定义一个数据访问对象接口类DAO,参考如下
public class DAO { public static Cursor queryAll(Context context) { Cursor cursor = null; try { String sql = "select _id," + ConstData.SQL._SQL_COLUMN1 + "," + ConstData.SQL._SQL_COLUMN2 + " from " + ConstData.SQL._SQL_TABLE1 + " order by _id desc"; DBHelper dbHelper = new DBHelper(context); cursor = dbHelper.sqliteDB.rawQuery(sql, null); } catch (Exception e) { e.printStackTrace(); } return cursor; } public static boolean insert(Context context, String column1, String column2) { boolean flag = true; try { String sql = "insert into " + ConstData.SQL._SQL_TABLE1 + "(" + ConstData.SQL._SQL_COLUMN1 + "," + ConstData.SQL._SQL_COLUMN2 + ") values('" + column1 + "','" + column2 + "')"; DBHelper dbHelper = new DBHelper(context); dbHelper.sqliteDB.execSQL(sql); dbHelper.sqliteDB.close(); } catch (SQLException e) { flag = false; e.printStackTrace(); } return flag; } public static boolean update(Context context, int _id, String userName, String userMobile) { boolean flag = true; try { String sql = "update users set username='" + userName + "',userMobile='" + userMobile + "' where _id=" + _id; DBHelper dbHelper = new DBHelper(context); dbHelper.sqliteDB.execSQL(sql); dbHelper.sqliteDB.close(); } catch (SQLException e) { flag = false; e.printStackTrace(); } return flag; } public static boolean delete(Context context, int _id) { boolean flag = true; try { String sql = "delete from users where _id=" + _id; DBHelper dbHelper = new DBHelper(context); dbHelper.sqliteDB.execSQL(sql); dbHelper.sqliteDB.close(); } catch (SQLException e) { flag = false; e.printStackTrace(); } return flag; } }
最后用DAO去操作数据的增删改查
boolean saveSuc = DAO.insert(mContext, str1, str2); //------------------------------- Cursor cursor = DAO.queryAll(mContext); StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); if (cursor.moveToFirst()) { do { String str3 = cursor.getString(cursor .getColumnIndexOrThrow(ConstData.SQL._SQL_COLUMN1)); String str4 = cursor.getString(cursor .getColumnIndexOrThrow(ConstData.SQL._SQL_COLUMN2)); sb1.append(str3).append("--"); sb2.append(str4).append("--"); } while (cursor.moveToNext()); }