文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Android数据存储基础:

2022-06-06 13:12

关注

1.基础:

1.1.Android 数据存储路径:
内部存储:
 /data/data/packageName/databases: 数据库
 /data/data/packageName/file:   内部存储
 /data/data/packageName/shared_prefs :  sp键值对存储

 sdcard下:
 /storage/sdcard/Android/data/packageName  : 应用卸载时删除,sd对应应用包的内部存储
 /storage/sdcard/xxx    : 应用卸载时不删除,6.0需要权限

模拟器类型必须是Google APIc才有root权限可以查看data/data目录

2. shared_prefs Api 键值对使用

// /data/data/packageName/shared_prefs
    private SharedPreferences sp;
    public void  spOperator(View view){
        //1. 得到sp对象
        sp = getSharedPreferences("atguigu", Context.MODE_PRIVATE);
        //2. 得到editor对象
        SharedPreferences.Editor edit = sp.edit();
        // 3. sp 存储数据
        edit.putString("username", "xiaoming").commit();
        // 4. sp  读取数据
        String str=sp.getString("username","");
        Log.e("denganzhi1",str);
    }
3. 安卓内部存储file

 // /data/data/packageName/file   安卓内部存储默认
    public void writeImgage(View view) throws IOException {
        AssetManager manager = getAssets();
        // 会自动去assert目录下找
        InputStream is = manager.open("a.txt");
        // 会自动打开 /data/data/packageName/file 目录
        FileOutputStream fos = openFileOutput("a.txt", Context.MODE_PRIVATE);
        //3. 边读边写
        byte[] buffer = new byte[1024];
        int len = -1;
        while((len=is.read(buffer))!=-1) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        is.close();
    }
    public void readImgage(View view) throws IOException {
        // 获取路径
        // /data/data/packageName/file 目录
        String filesPath = getFilesDir().getAbsolutePath()+"/a.txt";
        BufferedReader reader=new BufferedReader(new FileReader(filesPath));
        String line=null;
        while(null!=(line=reader.readLine())){
            Log.e("line:",line);
        }
      reader.close();
    }
4. sd对应应用包的内部存储


    //  /storage/emulated/0/Android/data/com.example.myapplication/files  : 应用卸载时删除
    public void  writeSD(View view) throws IOException {
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String filesPath = getExternalFilesDir(null).getAbsolutePath();
            Log.e("path:",filesPath);
            // : /storage/emulated/0/Android/data/com.example.myapplication/files
            String filePath = filesPath+"/"+"a.txt";
            FileOutputStream fos = new FileOutputStream(filePath);
            fos.write("写sdcard".getBytes("utf-8"));
            fos.close();
        }
    }
    public void  readSD(View view) throws IOException {
        // 1. 判断sd卡状态, 如果是挂载的状态才继续, 否则提示
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            String filesPath = getExternalFilesDir(null).getAbsolutePath()+"/a.txt";
            FileInputStream fis = new FileInputStream(filesPath);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while((len=fis.read(buffer))!=-1) {
                baos.write(buffer, 0, len);
            }
            String content = baos.toString();
            Log.e("readSD-->content:",content);
            baos.close();
            fis.close();
        }
    }
5.   sd外部存储

    

  // 权限回调   
@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
    {
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                try {
                    writeSdOut();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else
            {
                // Permission Denied
                Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
//  写入SD卡内容
  public static int MY_PERMISSIONS_REQUEST_CALL_PHONE=100;
    public void  writeSDW(View view)  {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},MY_PERMISSIONS_REQUEST_CALL_PHONE);
        } else
        {
            try {
                writeSdOut();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 public void writeSdOut() throws IOException {
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            // /storage/emulated/0
            String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
            Log.e("sdPath:",sdPath);
            //   /storage/emulated/0
            File file = new File(sdPath+"/atguigu");
            if(!file.exists()) {
                file.mkdirs();//创建文件夹
            }
            String filePath = sdPath+"/atguigu/"+"a.txt";
            FileOutputStream fos = new FileOutputStream(filePath);
            //4. 写数据
            fos.write("sd卡外部存储".getBytes("utf-8"));
            fos.close();
        }
    }
//  读取SD卡内容
 public void  readSDW(View view) throws IOException {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED) {
            String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
            //   /storage/emulated/0
            File file = new File(sdPath+"/atguigu");
            String filePath = sdPath+"/atguigu/"+"a.txt";
            Log.e("sdPath:",sdPath);
            FileInputStream fis = new FileInputStream(filePath);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while((len=fis.read(buffer))!=-1) {
                baos.write(buffer, 0, len);
            }
            String content = baos.toString();
            Log.e("readSDW-->content:",content);
            fis.close();
        }
    }
6. sqlite数据库存储

路径: /data/data/packageName/datebases
联系人App的数据库路径: data/data/com.android.prividers.contacts
打开导出本地.sqlite数据工具: SQLite Expert

     6.1. 数据库基本操作:

工具:Sqlite Expert Personal3 查看 .sqlite数据库,常用sql语句

## 建表
create table employee( 
       _id integer primary key autoincrement,    
       name varchar,
       salary double,
       birthday date
)   

##  插入数据
insert into employee(name,salary,birthday) values("Tom",100000,"1994-12-12");

##  删除数据
delete from employee where _id=1

## 更新数据
update employee set name="xiaozhang" where _id=2;

## 查找
select * from employee where  _id=2;


使用adb命令查看:

     adb shell
     cd /data/data
     cd com.android.providers.contacts 
     cd databases
     sqlite3 contacts2.db
     .tables :查看所有表
     select * from data; 

6.2. Android Api对sqlite数据库操作

基础类:


package com.example.myapplication;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {
	public DBHelper(Context context,int version) {
		super(context, "atguigu.db", null, version);
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		Log.e("TAG", "DBHelper onCreate()");
		//建表
		String sql = "create table person(_id integer primary key autoincrement, name varchar,age int)";
		db.execSQL(sql);
		//插入一些初始化数据
		db.execSQL("insert into person (name, age) values ('Tom1', 11)");
		db.execSQL("insert into person (name, age) values ('Tom2', 12)");
		db.execSQL("insert into person (name, age) values ('Tom3', 13)");
	}
	//当传入的版本号大于数据库的版本号时调用
	// 用户版本升级
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.e("TAG", "DBHelper onUpgrade()-->"+"oldVersion:"+oldVersion + "newVersion:"+newVersion);
	}
    // 还有版本下降的时候调用的方法onDowngrade
}

 6.2.1. 创建数据库:


   
    public void  creatTable(View view){
     DBHelper dbHelper=new DBHelper(this,1);
        // 创建数据源库
    //    dbHelper.getWritableDatabase();  //本地空间满了如果,继续插入没有反应
        // 连接数据库,得到连接
      SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();  // 本地空间满了如果,继续插入抛异常
    }

  6.2.2.  更新数据库版本


   public void updateTable(View view){
        DBHelper dbHelper=new DBHelper(this,2);
        // 连接数据库才会更新
        // 回调 onUpgrade 回调方法,比如更新一些字段
        SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
    }

  6.2.3. 数据的插入、修改、删除、查询


public void insertFun(View view){
        DBHelper dbHelper=new DBHelper(this,2);
        SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
        //insert into person (name, age) values ('Tom1', 11)
        ContentValues contentValues=new ContentValues();
        contentValues.put("name","denganzhi");
        contentValues.put("age",25);
       long id= sqLiteDatabase.insert("person",null,contentValues);
        sqLiteDatabase.close();
        Toast.makeText(MainActivity.this,"longid:"+id,Toast.LENGTH_SHORT).show();
    }
    public void updateFun(View view){
        DBHelper dbHelper=new DBHelper(this,2);
        SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
        ContentValues contentValues=new ContentValues();
        contentValues.put("age","300000");
        int updateCount=sqLiteDatabase.update("person",contentValues,"_id=?",new String[]{"5"});
        sqLiteDatabase.close();
        Toast.makeText(MainActivity.this,"updateCount:"+updateCount,Toast.LENGTH_SHORT).show();
    }
    public void deleteFun(View view){
        DBHelper dbHelper=new DBHelper(this,2);
        SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
        int deleteId= sqLiteDatabase.delete("person","_id=5",null);
        sqLiteDatabase.close();
        Toast.makeText(MainActivity.this,"deleteId:"+deleteId,Toast.LENGTH_SHORT).show();
    }
    public void selectFun(View view){
        DBHelper dbHelper=new DBHelper(this,2);
        SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
   // select * from person
        //query(String table, String[] columns, String selection,
       // String[] selectionArgs, String groupBy, String having,
         //       String orderBy)
        Cursor cursor =  sqLiteDatabase.query("person",null,"_id=?",new String[]{"3"},null,null,null);
        int count =cursor.getCount();  // 得到上面匹配的总数
        while(cursor.moveToNext()){
            int id= cursor.getInt(0);
            String name =cursor.getString(1);
            int age= cursor.getInt(cursor.getColumnIndex("age")); //如果记得名字了可以这样
            Log.e("denganzhi","count:"+count + " id:"+id +" name:"+ name + " age:"+ age);
        }
        cursor.close();
        sqLiteDatabase.close();
    }

  6.2.4. 数据库事务操作



    public void operatorTransiction(View view){
        DBHelper dbHelper=new DBHelper(this,2);
        SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
        // 1.开启事务, 不会自动保存提交了
        sqLiteDatabase.beginTransaction();
        ContentValues contentValues1=new ContentValues();
        contentValues1.put("age","300000");
        int updateCount1=sqLiteDatabase.update("person",contentValues1,"_id=?",new String[]{"1"});
        int j=1/0;
        contentValues1=new ContentValues();
        contentValues1.put("age","200000");
        updateCount1=sqLiteDatabase.update("person",contentValues1,"_id=?",new String[]{"2"});
        //2. 设置事务在全局
        sqLiteDatabase.setTransactionSuccessful();
        // 3. 结束事务
        sqLiteDatabase.endTransaction();
        sqLiteDatabase.close();
    }

作者:小置同学


阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-移动开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯