iis服务器助手广告广告
返回顶部
首页 > 资讯 > 移动开发 >Android数据存储基础:
  • 351
分享到

Android数据存储基础:

存储Android 2022-06-06 13:06:24 351人浏览 安东尼
摘要

1.基础: 1.1.Android 数据存储路径: 内部存储:  /data/data/packageName/databases: 数据库  /data/data/packa

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();
    }

作者:小置同学


--结束END--

本文标题: Android数据存储基础:

本文链接: https://www.lsjlt.com/news/28987.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作