• 数据存储


    一、三种方法

    SharedPreferences
    文件
    SQLite

    二、SharedPreferences

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 "
                            + "hh:mm:ss");
                    // 存入当前时间
                    editor.putString("time", sdf.format(new Date()));
                    // 存入一个随机数
                    editor.putInt("random", (int) (Math.random() * 100));
                    // 提交所有存入的数据
                    editor.commit();
    // 读取int类型的数据
                    int randNum = preferences.getInt("random", 0);

     三、file

    private String read()
        {
            try        {
                // 打开文件输入流
                FileInputStream fis = openFileInput(FILE_NAME);
                byte[] buff = new byte[1024];
                int hasRead = 0;
                StringBuilder sb = new StringBuilder("");
                // 读取文件内容
                while ((hasRead = fis.read(buff)) > 0)
                {
                    sb.append(new String(buff, 0, hasRead));
                }
                // 关闭文件输入流
                fis.close();
                return sb.toString();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }
    private void write(String content)
        {
            try
            {
                // 以追加模式打开文件输出流
                FileOutputStream fos = openFileOutput(FILE_NAME, MODE_APPEND);
                // 将FileOutputStream包装成PrintStream
                PrintStream ps = new PrintStream(fos);
                // 输出文件内容
                ps.println(content);
                // 关闭文件输出流
                ps.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

    四、读写SD卡

    <!--在SD卡中创建与删除文件权限-->
        <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
        <!--在SD卡中写入数据权限-->
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    if(!Environment.getExternalStorageState().equals(
    Environment.MEDIA_MOUNTED)){
    System.exit(0);
    }

     

    ActivityCompat.requestPermissions(this,
    new String[]{Manifest.permission. WRITE_EXTERNAL_STORAGE}, 1);
    public void onRequestPermissionsResult(
        int requestCode, String[] permissions,
         int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    //允许grantResults [i]值为0 禁止为-1
    if(grantResults[0]==-1) System.exit(0);
    }
    File sdCardDir = Environment.
            getExternalStorageDirectory();
    File targetFile
    = new File(sdCardDir.getCanonicalPath()
    + FILE_NAME); RandomAccessFile raf = new RandomAccessFile( targetFile, "rw");

     五、

    // 打开或创建数据库
            db = openOrCreateDatabase(DB_NAME,  Context.MODE_PRIVATE, null);
    
            // 创建数据表
            String createTable="CREATE TABLE IF NOT EXISTS " +
                    TB_NAME +
                    "(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    "name VARCHAR(32), " +
                    "phone VARCHAR(16), " +
                    "email VARCHAR(64))";
            db.execSQL(createTable);
    
            // 查询数据
            cur=db.rawQuery("SELECT * FROM "+ TB_NAME, null);
    
            // 若查询结果是空的则写入 2 项测试数据
            if(cur.getCount()==0){
                addData("旗标公司","02-23963257","service@flag.com.tw");
                addData("旗讯公司","02-23214335","service@pcdiy.com.tw");
            }
    
            adapter=new SimpleCursorAdapter(this,
                    R.layout.item, cur,FROM,
                    new int[] {R.id.name,R.id.phone,R.id.email}, 0);
    
            lv=(ListView)findViewById(R.id.lv);
            lv.setAdapter(adapter);
            lv.setOnItemClickListener(this);
    
            // 调用自定义方法, 重新查询及设置按钮状态
            requery();
        }
    
        private void addData(String name, String phone, String email) {
            // 创建含 3 个字段的 ContentValues对象
            ContentValues cv=new ContentValues(3);
            cv.put(FROM[0], name);
            cv.put(FROM[1], phone);
            cv.put(FROM[2], email);
    
            db.insert(TB_NAME, null, cv);
        }
    
        private void update(String name, String phone, String email, int id) {
            ContentValues cv=new ContentValues(3);
            cv.put(FROM[0], name);
            cv.put(FROM[1], phone);
            cv.put(FROM[2], email);
            // 更新 id 所指的字段
            db.update(TB_NAME, cv, "_id="+id, null);
        }
    
        // 重新查询的自定义方法
        private void requery() {
            cur=db.rawQuery("SELECT * FROM "+TB_NAME, null);
            //更改 Adapter的Cursor
            adapter.changeCursor(cur);
            if(cur.getCount()==MAX) // 已达上限, 停用新增按钮
                btInsert.setEnabled(false);
            else
                btInsert.setEnabled(true);
            btUpdate.setEnabled(false);    // 停用更新按钮
            btDelete.setEnabled(false);    // 停用删除按钮
        }
    
        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            // 移动 Cursor 至用户选取的选项
            cur.moveToPosition(position);
            // 读出姓名,电话,Email数据并显示
            etName.setText(cur.getString(
                    cur.getColumnIndex(FROM[0])));
            etPhone.setText(cur.getString(
                    cur.getColumnIndex(FROM[1])));
            etEmail.setText(cur.getString(
                    cur.getColumnIndex(FROM[2])));
    
            btUpdate.setEnabled(true); // 启用更新按钮
            btDelete.setEnabled(true); // 启用删除按钮
        }
    
        public void onInsertUpdate(View v){
            String nameStr=etName.getText().toString().trim();
            String phoneStr=etPhone.getText().toString().trim();
            String emailStr=etEmail.getText().toString().trim();
            // 任一字段的内容为空即返回
            if(nameStr.length()==0 ||
                    phoneStr.length()==0 ||
                    emailStr.length()==0) return;
    
            if(v.getId()==R.id.btUpdate)   // 单击更新按钮
                update(nameStr, phoneStr, emailStr, cur.getInt(0));
            else                     // 单击新增按钮
                addData(nameStr, phoneStr, emailStr);
    
            requery();
        }
    
        // 删除按钮的onClick事件方法
        public void onDelete(View v){
            db.delete(TB_NAME, "_id="+cur.getInt(0),null);
            requery();
        }
  • 相关阅读:
    【NOIP2003提高组】加分二叉树
    【luogu1220】关路灯
    【luogu2583】地铁间谍
    Hello, World!
    python中的画笔控制函数
    python中库引用与import
    python中RGB色彩
    turtle角度坐标体系
    turtle空间坐标系
    python中turtle库的使用
  • 原文地址:https://www.cnblogs.com/zyh0430/p/8166397.html
Copyright © 2020-2023  润新知