Android 笔记10-数据存储技术

数据存储方式

[1] Shared Preferences

  1. 存储的文件格式 .XML

  2. 存储的路径 data/data/包名/…

  3. 存储数据的步骤:

//第一步:
 SharedPreferences sp = getSharedPreferences("config",0);
//第二步:根据API文档
Editor edit =sp.edit();
edit.putString("name",name);
edit.putString("password",password);
edit.commit();
  1. 读取数据的步骤:
第一步:
String name=sp.getString("name"," ");
String password = sp.getString("password","");
第二步:
et_name.setText(name);
et_userpassword.setText(password);

示例 代码:

//获取SharedPreferences对象,创建文件
  final SharedPreferences sp=getSharedPreferences("mrsoft",MODE_PRIVATE);
        String username=sp.getString("username",null);
        String password = sp.getString("password",null);
        if(username!=null&&password!=null){
            if(username.equals(mr)&&password.equals(mrsoft)) {
                Intent intent = new Intent(MainActivity.this, MessageActivity.class);
                startActivity(intent);
            }
        }else
        {
            login.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String in_account = account.getText().toString().trim();
                    String in_password = password_Text.getText().toString().trim();
                    //获取Editor对象
                    SharedPreferences.Editor editor=sp.edit();
                    if(in_account.equals(mr)&&in_password.equals(mrsoft)){
                        editor.putString("username",in_account);
                        editor.putString("password",in_password);
                        editor.commit();
                        Intent intent = new Intent(MainActivity.this, MessageActivity.class);
                        startActivity(intent);
                        Toast.makeText(MainActivity.this,"已保存帐号密码",Toast.LENGTH_SHORT).show();
                    }else
                    {
                        Toast.makeText(MainActivity.this,"帐号或密码错误",Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

IO文件流存储(java复习)

1.写入数据

String result=username+"##"+pwd;
//1.创建file类指定我们要把数据存储的位置 
File file = new File("/data/data/com.itcast.cn.qqlogin/info.txt")
//   /data/data/com.itcast.cn.qqlogin/ 等 价于context.getFilesDir().getPath();

//2.文件输出流
FileOutputStream fos = new FileOutputStream(file);
//3.文件输出流写入数据
fos.write(result.getBytes());
fos.close();

2.读取数据,找出用户名和密码

//定义一个Map集合
Map<String,String> maps = new HashMap<String,String>();
//指定读取文件的路径
File file = new File("/data/data/com.itcast.cn.qqlogin/info.txt"))
//创建文 件输入流对象 
FileInputStream fis= new FileInputStream(file);
BufferedReader bufr = new BufferedReader(new InputStreamReader(fis));
//读取数据
String content =bufr.readLine();
//切割字符串,封装到Map
String [] splits =content.split("##");
String name=splits[0];
String pwd=splits[1];
maps.put("username",name);
maps.put("pwd",pwd);
fis.close()  //关闭流

[2]内部存储

在这里插入图片描述
示例代码

 protected void onCreate(Bundle savedInstanceState) {
      
        buffer = null;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        mEditText = (EditText) findViewById(R.id.editText);
        mSave = (ImageView) findViewById(R.id.save);
        mCancel=findViewById(R.id.cancel);
        mCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*******保存填写的备忘信息********/
                FileOutputStream fos = null; //声明文件输出流
                String text = mEditText.getText().toString(); //获取备忘信息
                try {
                    fos=openFileOutput("memo",MODE_PRIVATE); //获取文件输出流对象
                    fos.write(text.getBytes());//转换成字节数组写入到文件
                    fos.flush(); //清除缓存
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if(fos!=null) {   //非空检测,很重要
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
         /*******读取保存的备忘信息********/

        FileInputStream fis =null;  //声明文件输入流
        try {
            //获取文件输入流
            fis=openFileInput("memo");
            buffer = new byte[fis.available()]; //实例化字节数组
            fis.read(buffer); //从输入流读取数据
        } catch (IOException e) {
            e.printStackTrace();
        }finally
        {
            if (fis != null) {   //非空检测,很重要
                try {

                    String textshow = new String(buffer); //把字节数组转换为字符串
                    mEditText.setText(textshow);
                    fis.close();
                } catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

[3]外部存储

  • 1.加权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  • 2.实例化一个外部文件
  file = new File(Environment.getExternalStorageDirectory(),"text.txt");
  • 3.读取和写入时
fis=new FileInputStream(file);   读取

fos= new FileOutputStream(file) ; 写入

[4]数据库SQLite3

  1. .数据库介绍
    sqlite
    问:什么情况下用数据库,有大量相似结构的数据需要存储的时候
  2. 数据库的创建
    定义一个类继承sqliteOpenHelper,实现方法,加入构造
public class DBOpenHelper extends SQLiteOpenHelper {
    //定义创建数据表的SQL语句
    final String CREATE_TABLE_SQL ="create table dict(_id integer primary key autoincrement,word,detail)";

    public DBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, null, version);  //游标工厂设为null
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_SQL); //创建单词数据表
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.i("词典","版本更新"+oldVersion+"--->"+newVersion);
    }
}
  1. .数据库的oncreate方法和onupgrade方法
    [1] 使用SQLite Expert Professional 这个工具可以打开我们创建的数据库
    [2] 需要提前安装
    [3] sql语句回顾:
    –alter table info add phone varchar(20);
    –insert into info (name,phone) values(‘王五’,‘13712388002’);
    –delete from info where name=“王五”;
    –update info set phone=“11382398” where name=“王五”;
    select name,phone from info

  2. .使用sql语句对数据库进行增删改查
    缺点: A: sql语句容易写错
    B:执行Sql语句没有返回值 ,不容易进行判断
    优点:多表查询容易

  3. 命令行工具: .exit 退出数据库
    1)设置好环境变量

    1. cmd-----adb shell
      3)root权限 su root
      4)mkdir /data/data/appstore.xianchuang.com.callphone/db
      5)切换目录 cd /data/data/appstore.xianchuang.com.callphone/
      6)sqlite3
      7)创建表 create table tb_user(id integer primary key autoincrement,name text not null,pwd text not null);
      8).tables可以查看表
      9)用sql语句进行增删改查

改变DOS的编 码方式 chcp 936 -----> GBK
chcp 65001—>utf-8

  1. 使用谷歌封装好的API进行增删改查
    优点: [1]写法简单,不需要写语句,不容易写错
    [2] 有返回值 方便开发者进行开发
    缺点: 如果有多张表,使用谷歌封装的API不容易询
    SQLITE3
    //查询语句
    Cursor cursor = dbOpenHelper.getReadableDatabase()
    cursor.query(“dict”,null,“word=?”,new String[]{key},null,null,null);
    //插入语句
    sqLiteDatabase.insert(“dict”,null,values);
    //更新语句
    ContentValues values = new ContentValues();
    values.put(“word”,“cao”);
    db.updata(“dict”,values,“word=?”,new String [] {“love”});
    //删除语句
    db.delete(“dict”,“word=?”,new String [] {“cao”});

示例代码:
进行插入操作

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        //实例化数据库
        dbOpenHelper = new DBOpenHelper(add.this,"dict",null,1);
        mAddWord = (EditText) findViewById(R.id.add_word);
        mAddInterpret = (EditText) findViewById(R.id.add_interpret);
        mSaveBtn = (ImageButton) findViewById(R.id.save_btn);
        mCancelBtn1 = (ImageButton) findViewById(R.id.cancel_btn1);

        mSaveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //单击保存按钮把把数保存到数据库中
                String word = mAddWord.getText().toString().trim();
                String interpret = mAddInterpret.getText().toString().trim();
                //非空检查
                if(word.equals("")||interpret.equals("")){
                    Toast.makeText(add.this,"单词或解释为空",
                            Toast.LENGTH_SHORT).show();
                }else{
                    //插入方法
                    insertData(dbOpenHelper.getReadableDatabase(),word,interpret);
                    Toast.makeText(add.this,"添加生词成功",Toast.LENGTH_SHORT).show();
                }
            }
        });

        mCancelBtn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(add.this,MainActivity.class);
                startActivity(intent);
            }
        });

    }
    //插入方法
    // 使用ContentValues,类似MAP的键值对,KEY要跟数据表的字段名一致
    private void insertData(SQLiteDatabase sqLiteDatabase,String word,String interpret){
        ContentValues values = new ContentValues();
        values.put("word",word);
        values.put("detail",interpret);
        //执行插入语句
        sqLiteDatabase.insert("dict",null,values);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(dbOpenHelper!=null){
            dbOpenHelper.close(); //最后关闭数据库连接
        }
    }
}

进行查询操作

public class MainActivity extends AppCompatActivity {
    private DBOpenHelper dbOpenHelper;  //声明DBOpenHelper对象
    private EditText mSearchEt;
    private ImageButton mSearchBtn;
    private ListView mResultListview;
    private Button mAddBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //实例化数据库
        dbOpenHelper = new DBOpenHelper(MainActivity.this,"dict",null,1);


        mSearchEt = (EditText) findViewById(R.id.search_et);
        mSearchBtn = (ImageButton) findViewById(R.id.search_btn);
        mResultListview = (ListView) findViewById(R.id.result_listview);
        mAddBtn = (Button) findViewById(R.id.add_btn);

        mAddBtn.setOnClickListener(new View.OnClickListener() {  //添加生词功能
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,add.class);
                startActivity(intent);
            }
        });
        mSearchBtn.setOnClickListener(new View.OnClickListener() {  //翻译功能
            @Override
            public void onClick(View v) {
                //获取要查询的单词
                String key = mSearchEt.getText().toString().trim();
                //执行查询语句
                Cursor cursor = dbOpenHelper.getReadableDatabase().query("dict",
                        null,"word=?",new String[]{key},null,null,null);
                //创建ArrayList对象,用于保存查询到的结果
                ArrayList<Map<String,String>> resultList = new ArrayList<Map<String, String>>();
                //游标下移,存放数据
                while (cursor.moveToNext()){
                    Map<String,String> map = new HashMap<>();
                    map.put("word",cursor.getString(1));
                    map.put("interpret",cursor.getString(2));
                    resultList.add(map);
                }
                //如果查询没有结果
                if(resultList==null||resultList.size()==0){
                    Toast.makeText(MainActivity.this,"很遗憾,没有数据",Toast.LENGTH_SHORT).show();
                }else{
                    //否则将数据显示到ListView中
                    SimpleAdapter simpleAdapter = new SimpleAdapter(MainActivity.this,resultList,
                            R.layout.activity_result_main,new String[]{"word","interpret"},
                            new int[]{R.id.result_word,R.id.result_interpret});
                    mResultListview.setAdapter(simpleAdapter);
                }
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(dbOpenHelper!=null){
            dbOpenHelper.close(); //最后关闭数据库连接
        }
    }
}

**开源项目LitePal ** https://github.com/LitePalFramework/LitePal
配置litepal
1.build.gradle文件

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
...
    implementation 'org.litepal.android:java:3.0.0'
}
  1. app/src/main---->建文件夹assets,建litepal.xml
<?xml version="1.0" encoding="utf-8"?>
<litepal>
    <dbname value="bookstore"></dbname>
    <version value="3"></version>
    <list>
        <mapping class="appstore.xianchuang.com.litepal.Book"></mapping>
        <mapping class="appstore.xianchuang.com.litepal.Category"></mapping>
    </list>
</litepal>
  1. AndroidManifest.xml
 <application
        android:name="org.litepal.LitePalApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        ...

litePal创建数据库

  1. 建一个类如
package appstore.xianchuang.com.litepal;

public class Book extends LitePalSupport {
    private int id;
    private String author;
    private double price;
    private int pages;
    private String name;
    private  String press;

    public String getPress() {
        return press;
    }

    public void setPress(String press) {
        this.press = press;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

  1. litepal.xml文件中的版本号加1
 <version value="4"></version>

3.主程序中:Connector.getDatabase();

			 Book book = new Book();
                book.setAuthor("高手");
                book.setName("第一行代码");
                book.setPages(500);
                book.setPress("unknow");
                book.setPrice(18.25f);
                book.save();

 LitePal.deleteAll(Book.class,"price<?","15");

 				Book book = new Book();
                book.setPress("Author");
                book.setPrice(12.00f);
                book.updateAll("name=? and author=?","第一行代码","高手");


                List<Book> list =LitePal.findAll(Book.class);
                for(Book book:list){
                    Log.d("MainActivity","book name is"+book.getName());
                    Log.d("MainActivity","book author is"+book.getAuthor());
                    Log.d("MainActivity","book pages is"+book.getPages());
                    Log.d("MainActivity","book price is"+book.getPrice());
                    Log.d("MainActivity","book press is"+book.getPress());
					}
  //复杂查询用另一种:
                //List<Song> songs = LitePal.where("name like ? and duration < ?",
                // "song%", "200").order("duration").find(Song.class);

[5]Content Provider

在这里插入图片描述
示例代码:

public class MainActivity extends AppCompatActivity {
    private TextView mResult;
    //获取到姓名
    private String columns = ContactsContract.Contacts.DISPLAY_NAME;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mResult = (TextView) findViewById(R.id.result);
        mResult.setText(getQueryData()); //显示联系人姓名
    }
    private CharSequence getQueryData(){
        //创建StringBuilder对象,用来保存获取的联系人
        StringBuilder stringBuilder = new StringBuilder();
        ContentResolver resolver = getContentResolver();
        //查询记录
        Cursor cursor=resolver.query(ContactsContract.Contacts.CONTENT_URI,null,
                null,null,null);
        //获取姓名记录的索引值
        int displayNameIndex = cursor.getColumnIndex(columns);
        for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
            String displayName =cursor.getString(displayNameIndex);
            stringBuilder.append(displayName+"\n");
        }
        //关闭记录集
        cursor.close();
        return stringBuilder.toString();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值