一、文件 1、文件操作类
public class FileOperation { //保存文件,参数分别是上下文、文件名、数据 public static void save(Context context,String filename,String data){ FileOutputStream fileOutputStream=null; BufferedWriter bufferedWriter=null; try { //打开文件,这里以append方式 fileOutputStream=context.openFileOutput(filename,Context.MODE_APPEND); //使用BufferWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(fileOutputStream)); bufferedWriter.write(data); bufferedWriter.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { if(bufferedWriter!=null){ bufferedWriter.close(); } } catch (IOException e) { e.printStackTrace(); } } } //读取文件,参数分别是上下文、文件名 public static String read(Context context,String filename){ FileInputStream fileInputStream=null; BufferedReader bufferedReader=null; StringBuffer data=new StringBuffer(); try { fileInputStream=context.openFileInput(filename); bufferedReader=new BufferedReader(new InputStreamReader(fileInputStream)); String line; while ((line=bufferedReader.readLine())!=null){ data.append(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { if(bufferedReader!=null){ bufferedReader.close(); } } catch (IOException e) { e.printStackTrace(); } } return data.toString(); } }2、测试
public class FileActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_file); EditText editText=(EditText)findViewById(R.id.edit); Button button=(Button)findViewById(R.id.bt); button.setOnClickListener( view->{ String data=editText.getText().toString(); FileOperation.save(this,"myfile",data);//写数据 String str=FileOperation.read(this,"myfile");//读数据 Toast.makeText(this,str,Toast.LENGTH_SHORT).show();//将数据显示出来 } ); } }二、SharedPreferences 通过键值对来存取数据
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shared); Button bt=(Button)findViewById(R.id.bt_shared); bt.setOnClickListener( view -> { /* 获得SharedPreferences对象有三种途径: 1、Content类的getSharedPreferences(),2个参数分别是文件名与操作模式 2、Activity类的getPreferences(),参数是操作模式,会自动将当前活动类名当作文件名 3、PreferenceManager类的getDefaultSharedPreferences(),静态方法,参数是Content 写数据: 1、通过SharedPreferences对象的edit()获得SharedPreferences.Editor对象 2、使用put***()向该对象中添加数据 3、调用apply()将添加的数据提交 */ SharedPreferences.Editor editor=getSharedPreferences("sharedfile",MODE_PRIVATE).edit(); editor.putString("name","yang"); editor.putInt("age",20); editor.apply(); } ); Button show=(Button)findViewById(R.id.bt_shared_show); show.setOnClickListener( view -> { /* 读数据: 1、获得SharedPreferences对象 2、使用get***()读数据,参数分别是键和默认返回值,当找不到该键时,就使用默认返回值 */ SharedPreferences sharedPreferences=getSharedPreferences("sharedfile",MODE_PRIVATE); String data1=sharedPreferences.getString("name","lcy"); String data2=Integer.toString(sharedPreferences.getInt("age",20)); Toast.makeText(this,data1+"的年龄是"+data2,Toast.LENGTH_SHORT).show(); } ); }三、SQLite数据库 SQLiteOpenHelper类是数据库管理帮助类,其有2个抽象方法:onCreate()与onUpgrade(),在子类中需要实现这2个方法 SQLiteOpenHelper子类:
public class SQLiteHelper extends SQLiteOpenHelper { private Context context; //建表的sql语句 String createSQL="create table info(" + "id text primary key," + "name text," + "class text"+ ")"; public SQLiteHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); this.context=context; } //在数据库创建的时候会执行该方法 @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { //在数据库建立的时候建表 sqLiteDatabase.execSQL(createSQL); } //当构造方法里的版本号大于之前的版本号时执行此方法 @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { sqLiteDatabase.execSQL("drop table if exists info");//将之前的表删除 onCreate(sqLiteDatabase);//重新执行onCreate() } }对数据库进行操作:
public class SQLiteActivity extends AppCompatActivity { //获得一个SQLiteHelper对象 private SQLiteHelper sqLiteHelper=new SQLiteHelper(this,"student.db",null,1); //数据库引用,通过其可以进行增删改查 private SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sqlite); Button create=(Button)findViewById(R.id.database_create); Button add=(Button)findViewById(R.id.add) ; Button delete=(Button)findViewById(R.id.delete); Button update=(Button)findViewById(R.id.update); Button query=(Button)findViewById(R.id.query); Button databaseDelete=(Button)findViewById(R.id.database_delete); /* 创建数据库或打开已存在的数据库有2个方法: 1、getReadableDatabase(),当数据库不可写的时候,返回的对象以只读的形式访问数据库 2、getWritableDatabase(),当数据库不可写的时候,抛出异常 */ db=sqLiteHelper.getReadableDatabase(); create.setOnClickListener( view -> db=sqLiteHelper.getReadableDatabase() ); //对应sql:db.execSQL("insert into info (id,nam,class) values(?,?,?)",new String[]{"20180001","yang","computer 1802"}); add.setOnClickListener( view -> { //使用ContentValues来组装数据 ContentValues contentValues=new ContentValues(); //插入第一条数据 contentValues.put("id","20180001"); contentValues.put("name","yang"); contentValues.put("class","computer 1801"); db.insert("info",null,contentValues); contentValues.clear(); //插入第二条数据 contentValues.put("id","20180002"); contentValues.put("name","yue"); contentValues.put("class","math 1802"); db.insert("info",null,contentValues); } ); //对应sql:db.execSQL("delete from info where id = ?",new String[]{"2018001"}); delete.setOnClickListener( view -> { //参数1指定表,参数2、参数3指定要删除的行 db.delete("info","id = ?",new String[]{"20180001"}); } ); //对应sql:db.execSQL("update info set class = ? where id=?",new String[]{"English 1802","20180002"}); update.setOnClickListener( view -> { //使用ContentValues组装数据 ContentValues contentValues=new ContentValues(); contentValues.put("class","English 1802"); //参数1指定表,参数2为ContentValues对象,指定要更改的字段及更改后的值,参数3、参数4指定要更改的行 db.update("info",contentValues,"id = ?",new String[]{"20180002"}); } ); //对应sql:db.rawQuery("select name,class from info",null); query.setOnClickListener( view -> { /* 参数1:指定表 参数2:指定查询的字段,默认查询所有字段 参数3、参数4:指定查询的行,默认查询所有行 参数5、指定需要group by的字段,默认不进行group by操作 参数6:对group by之后的数据进一步过滤,默认不过滤 参数7:指定查询结果的排序方式,默认按照默认排序 */ Cursor cursor=db.query("info",new String[]{"name","class"},null,null,null,null,null); //循环遍历cursor将数据取出来 if(cursor.moveToFirst()) { do { String name = cursor.getString(cursor.getColumnIndex("name")); String clazz = cursor.getString(cursor.getColumnIndex("class")); Log.d("student", name + "的班级是" + clazz); } while (cursor.moveToNext()); } } ); databaseDelete.setOnClickListener( view -> { db.close(); File file=new File("/data/data/com.example.store/databases/student.db"); file.delete(); } ); } }四、LitePal Android数据库框架,采用对象关系映射模式 依赖:
implementation 'org.litepal.android:core:1.4.1'配置LitePal: 新建文件:app->assets->litepal.xml:
<?xml version="1.0" encoding="utf-8" ?> <litepal> <!-- 指定数据库名 --> <dbname value="student"/> <!-- 指定数据库版本 --> <version value="2"/> <!-- 指定映射模型 --> <list> <!--将Information添加到映射模型列表中--> <mapping class="com.example.store.Information"/> </list> </litepal>配置项目Application:
android:name="org.litepal.LitePalApplication"建表:
//类名对应数据库中的表名,如果需要进行CRUD操作,则需要继承DataSupport public class Information extends DataSupport { //类中的每个属性对应表中的一个字段 //不要把属性设置为id private String studentId;//学号 private String name;//姓名 private String classes;//班级 //getter() public String getStudentId() { return studentId; } public String getName(){ return name; } public String getClasses(){ return classes; } //setter() public void setStudentId(String studentId){ this.studentId=studentId; } public void setName(String name) { this.name = name; } public void setClasses(String classes) { this.classes = classes; } }CRUD:
public class LitePalActivity extends AppCompatActivity { private SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_litepal); Button create=(Button)findViewById(R.id.database_create_litepal); Button add=(Button)findViewById(R.id.add_litepal) ; Button delete=(Button)findViewById(R.id.delete_litepal); Button update=(Button)findViewById(R.id.update_litepal); Button query=(Button)findViewById(R.id.query_litepal); Button display=(Button)findViewById(R.id.display_litepal); Button databaseDelete=(Button)findViewById(R.id.database_delete_litepal); //创建数据库,数据库名、版本等信息在litepal.xml中 create.setOnClickListener( view ->{ db=LitePal.getDatabase(); Toast.makeText(this,"create",Toast.LENGTH_SHORT).show(); } ); //添加数据 add.setOnClickListener( view -> { Information information=new Information(); //设置数据 information.setStudentId("0001"); information.setName("江离"); information.setClasses("com 01"); information.save();//提交数据 //再添加一条数据 //如果使用上面的information,那么就只是对已存储的对象更新,而不是添加另一条数据 Information information1=new Information(); information1.setStudentId("0002"); information1.setName("阳月"); information1.setClasses("com 01"); information1.save(); Toast.makeText(this,"add",Toast.LENGTH_SHORT).show(); } ); //删除数据 delete.setOnClickListener( view -> { /* 删除数据的方法: 1、调用已存储对象的delete() 2、DataSupport类的deleteAll() */ //参数1是表名,或者Class对象,如Information.class,后面的参数指定要删除的行,如果不指定,默认删除所有行 DataSupport.deleteAll("Information","studentId = ?","0001"); Toast.makeText(this,"delete",Toast.LENGTH_SHORT).show(); } ); //修改数据 update.setOnClickListener( view -> { /* 更新数据的方法: 1、对已存储对象重新设值,然后save() 2、通过updateAll(),这种方法更加灵活 */ Information information=new Information(); //设置数据 information.setClasses("com 02"); //指定要更新的行,如果不指定的话,默认更新所有行 information.updateAll("studentId = ?","0002"); /* 注意:使用此种方法时,不可以将字段更新为默认值,如int型的不能更新为0 因为,创建一个对象时,其所有属性均已初始化为默认值,那么setter()是无效的 而LitePal是不会对属性为默认值的字段进行更新 原因也很简单,就是这么做了会导致不想更新的字段都更新为默认值 解决方法是不使用setter(),而使用setToDefault(),参数为字段名,那么在调用updateAll()时,该字段会更新为默认值 */ Toast.makeText(this,"update",Toast.LENGTH_SHORT).show(); } ); //查询数据 query.setOnClickListener( view -> { /* DataSupport类中有很多查询的方法: 1、findAll(),参数为表对应的Class对象,表示查询所有行 2、findFirst(),参数为表对应的Class对象,表示查询第一行 3、findLast(),与findFirst()对应 4、连缀查询: select()指定查询的字段 where()指定查询的行 order()指定排序方式,asc表示升序排序,desc表示降序排序,默认升序排序 limit()指定查询结果的数量 offset()指定查询结果的偏移量 find()指定表 以上方法,不需要的时候可以不写 */ List<Information> list=DataSupport.select("name","classes")//查询的字段 .where("studentId = ?","0001")//指定行 .order("id desc")//按id降序排列 .limit(2)//查询结果最多行数 .offset(0)//查询结果偏移量,这里不偏移,此方法可以不写 .find(Information.class);//查询的表 //将数据打印出来 for (Information line:list){ Log.d("yang", line.getName()+"的班级是"+line.getClasses()); } //LitePal也支持sql:Cursor cursor=DataSupport.findBySQL(sql); Toast.makeText(this,"query",Toast.LENGTH_SHORT).show(); } ); //将所有数据显示出来 display.setOnClickListener( view -> { List<Information> list=DataSupport.findAll(Information.class); //将数据打印出来 Log.d("yang", Integer.toString(list.size())); for (Information line:list){ Log.d("yang", line.getName()+"的班级是"+line.getClasses()); } Toast.makeText(this,"display",Toast.LENGTH_SHORT).show(); } ); databaseDelete.setOnClickListener( view -> { File file=new File("/data/data/com.example.store/databases/student.db"); file.delete(); Toast.makeText(this,"already delete the database",Toast.LENGTH_SHORT).show(); } ); } }更新数据库: 将版本号增加,然后重新create就好,以前的数据会自动保存