欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

AndroidSqlite

程序员文章站 2022-03-28 12:48:24
既然要用到数据库那当然也要了解一下安卓的文件存储,首先看文件存储的代码文件存储@Override public void onClick(View v) { switch (v.getId()) { case R.id.button: Log.d(TAG, "onClick: 1"); save("我"); break; case R.i...

既然要用到数据库那当然也要了解一下安卓的文件存储,首先看文件存储的代码

文件存储

@Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                Log.d(TAG, "onClick: 1");
                save("我");
                break;
            case R.id.button2:
                Log.d(TAG, "onClick: 2");
                String inputText = load();
                if (!TextUtils.isEmpty(inputText)) {
                    textView.setText(inputText);
                }else {
                    Toast.makeText(MainActivity.this,"没有读取到文件",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.button3:
                dbHelper.getWritableDatabase();
                break;
        }
    }

    private void save(String text) {
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try {
            out = openFileOutput("data",Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(text);
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }


    private String load() {
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            in = openFileInput("data");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }

这里写了两个方法一个是save和load,save方法和Java的写法一样定义FileOutputStream和BufferedWriter,后面就是安卓自带的openFileOutput参数1用于指定文件名称,参数2为操作模式,这里的默认的操作模式,然后创建一个字符缓冲输出流对象,writer.write(text);写入字符串.后面在finally后面写关闭输出流.

load方法定义FileInputStream和BufferedReader这里的openFileInput也为安卓自带的填入文件名.创建字符缓冲输入流对象,通过while循环读每一行判断是否为null,在使用前面创建StringBuilder的content来拼接字符后面也是在finally关闭输入流.后返回字符串.

Sqlite

创建一个类表示一个表,

package com.example.xyz.filetest.poj;

public class User {
    private int id;

    private String userName;

    private String passWord;

    private String sex;

    private int age;

    public int getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", passWord='" + passWord + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }
}

在db包创建UserDatabaseHelper继承自SQLiteOpenHelper

SQLiteOpenHelper:

数据库操作的帮助类,借助这个类我们可以简单有效的对数据库进行创建和升级。该类为抽象类,需要我们创建类实现它。两个重要的抽象方法为:onCreate()和onUpgrade() 顾名思义分别是在数据库创建

时和数据可升级时进行调用。两个重要的实例方法:getReadableDatabase()和getWritableDatabase()。前者为打开打开或创建一个可读的数据库,后者为打开或创建一个可读可写的数据库。

package com.example.xyz.filetest.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.Nullable;
import android.util.Log;

import com.example.xyz.filetest.utils.Constante;

public class UserDatabaseHelper extends SQLiteOpenHelper {
    private static final String TAG = "UserDatabaseHelper";
    private static final String createSql = "create table user(id integer primary key autoincrement,userName varchar(30),password varchar(32), sex varchar(5)" +
            ",age integer)";
    public UserDatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
      /*  String createSql = "create table " + Constante.TABLE_NAME +
                "(" + Constante.FIELD_ID + "integer primary key autoincrement," + Constante.FIELD_USER_NAME
                + " varchar(30),"+ Constante.FIELD_PASSWORD
                +" varchar(32)," + Constante.FIELD_SEX +
                " varchar(5),"
                + Constante.FIELD_AGE + " integer)"; */
            db.execSQL(createSql);
            Log.d(TAG, "onCreate: 数据库创建完毕");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

onUpgrade方法是用与升级时进行调用,版本大于原来版本就会被调用,

创建Constante作为常量类用于存放字段。

package com.example.xyz.filetest.utils;

public class Constante {
    public static final String DB_NAME = "provider.db";
    public static final int DB_VERSION = 1;
    public static final String  TABLE_NAME = "user";
    public static final String FIELD_ID = "id";
    public static final String FIELD_USER_NAME = "userName";
    public static final String FIELD_PASSWORD = "password";
    public static final String FIELD_SEX = "sex";
    public static final String FIELD_AGE = "age";
}

创建IUserDao接口

public interface IUserDao {
    long addUser(User user);

    int delUserByid(int id);

    int updataUser(User user);

    User getUserById(int id);

    List<User> listAllUser();
}

在创建UserDaoImpl类来实现IUserDao接口的抽象方法

package com.example.xyz.filetest.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.xyz.filetest.db.UserDatabaseHelper;
import com.example.xyz.filetest.poj.User;
import com.example.xyz.filetest.utils.Constante;

import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements IUserDao {
    private final UserDatabaseHelper mUserDatabaseHelper;
    public UserDaoImpl(Context context) {
        mUserDatabaseHelper = new UserDatabaseHelper(context,Constante.DB_NAME,null,Constante.DB_VERSION);
    }

    @Override
    public long addUser(User user) {
        SQLiteDatabase db = mUserDatabaseHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(Constante.FIELD_USER_NAME,user.getUserName());
        values.put(Constante.FIELD_SEX,user.getSex());
        values.put(Constante.FIELD_PASSWORD,user.getPassWord());
        values.put(Constante.FIELD_AGE,user.getAge());
        long result = db.insert(Constante.TABLE_NAME,null,values);
        db.close();
        return result;
    }

    @Override
    public int delUserByid(int id) {
        SQLiteDatabase db = mUserDatabaseHelper.getWritableDatabase();
        int delete =  db.delete(Constante.TABLE_NAME,Constante.FIELD_ID,new String[] {id + ""});
        db.close();
        return delete;
    }

    @Override
    public int updataUser(User user) {
        SQLiteDatabase db = mUserDatabaseHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(Constante.FIELD_USER_NAME,user.getUserName());
        values.put(Constante.FIELD_SEX,user.getSex());
        values.put(Constante.FIELD_PASSWORD,user.getPassWord());
        values.put(Constante.FIELD_AGE,user.getAge());
        int result = db.update(Constante.TABLE_NAME,values,Constante.FIELD_ID,new String[]{user.getId() + ""});
        db.close();
        return result;
    }

    @Override
    public User getUserById(int id) {
        SQLiteDatabase db = mUserDatabaseHelper.getReadableDatabase();
        String sql = "select * from "+ Constante.TABLE_NAME + " where " + Constante.FIELD_ID + "=?";
        Cursor cursor = db.rawQuery(sql,new String[]{id + ""});
        User user = null;
        if (cursor.moveToNext()) {
            user = new User();
            int userId = cursor.getInt(cursor.getColumnIndex(Constante.FIELD_ID));
            user.setId(userId);
            String userName = cursor.getString(cursor.getColumnIndex(Constante.FIELD_USER_NAME));
            user.setUserName(userName);
            String userSex = cursor.getString(cursor.getColumnIndex(Constante.FIELD_SEX));
            user.setSex(userSex);
            String userPassword = cursor.getString(cursor.getColumnIndex(Constante.FIELD_PASSWORD));
            user.setPassWord(userPassword);
            int userAge = cursor.getInt(cursor.getColumnIndex(Constante.FIELD_AGE));
            user.setAge(userAge);
        }
        db.close();
        return user;
    }

    @Override
    public List<User> listAllUser() {
        SQLiteDatabase db = mUserDatabaseHelper.getReadableDatabase();
        Cursor cursor = db.query(Constante.TABLE_NAME,null,null,null,null,null,null,null);  //Cursor 是每行的集合。
        List<User> users = new ArrayList<>();
        User user = null;
        while (cursor.moveToNext()) {
            user = new User();
            int userId = cursor.getInt(cursor.getColumnIndex(Constante.FIELD_ID));
            user.setId(userId);
            String userName = cursor.getString(cursor.getColumnIndex(Constante.FIELD_USER_NAME));
            user.setUserName(userName);
            String userSex = cursor.getString(cursor.getColumnIndex(Constante.FIELD_SEX));
            user.setSex(userSex);
            String userPassword = cursor.getString(cursor.getColumnIndex(Constante.FIELD_PASSWORD));
            user.setPassWord(userPassword);
            int userAge = cursor.getInt(cursor.getColumnIndex(Constante.FIELD_AGE));
            user.setAge(userAge);
            users.add(user);
        }
        db.close();
        return users;
    }
}

Cursor 的一些重要方法:
close() 关闭游标,释放资源
copyStringToBuffer(int columnIndex, CharArrayBuffer buffer) 在缓冲区中检索请求的列的文本,将将其存储
getColumnCount() 返回所有列的总数
getColumnIndex(String columnName) 返回指定列的名称,如果不存在返回-1
getColumnIndexOrThrow(String columnName) 从零开始返回指定列名称,如果不存在将抛出 IllegalArgumentException 异常。
getColumnName(int columnIndex) 从给定的索引返回列名
getColumnNames() 返回一个字符串数组的列名
getCount() 返回Cursor 中的行数
moveToFirst() 移动光标到第一行
moveToLast() 移动光标到最后一行
moveToNext() 移动光标到下一行
moveToPosition(int position) 移动光标到一个绝对的位置
moveToPrevious() 移动光标到上一行

自此增删改查功能全部写完.

测试

    private static final String TAG = "ExampleInstrumentedTest";
    @Test
    public void testAddUser() {
        Context appContext = InstrumentationRegistry.getTargetContext();
        IUserDao userDao = new UserDaoImpl(appContext);
        User user = new User();
        user.setSex("female");
        user.setAge(18);
        user.setPassWord("123456");
        user.setUserName("luna");
        long result = userDao.addUser(user);
        Log.d(TAG, "testAddUser: ------------->" + result);
        assertNotEquals(-1,result);
    }

本文地址:https://blog.csdn.net/weixin_46942417/article/details/107926887

相关标签: Android