安卓数据库案例4

1、调用SQLiteDatabase的 beginTransaction() 方法来开启一个事务,然后在一个异常捕获的代码块中去执行具体的数据库操作,
2、当所有的操作都完成之后,调用 setTransactionSuccessful() 表示事务已经执行成功了
3、最后在finally代码块中调用 endTransaction() 来结束事务。
在这里插入图片描述

 /**

 * Created by mikeyna on 18-7-3.
 */

public class FaceDetection {
    private static String TAG = "FaceDetection";
    private ArrayList<String> mPicturePathList = new ArrayList<>();
    private Context mContext;
    GalleryDatabaseHelper mDBHelper;
    public FaceDetection(Context context)
    {
        mContext = context;
        mDBHelper = new GalleryDatabaseHelper(context);
    }
    public void init(String folderDir)
    {
        String labelfile = "";
        String conf = "/sdcard/tfmodel/caffemodel/facedetector/deploy.prototxt";
        String model =  "/sdcard/tfmodel/caffemodel/facedetector/res10_300x300_ssd_iter_140000_fp16.caffemodel";
        SmartNative.faceDetectorInit(model, conf, labelfile);
        getPicturePaths(folderDir);
        StorePictureInfo2DB();
    }
    public void close()
    {
        SmartNative.faceDetectorClose();
    }
    //获取相片的名称
    private ArrayList<String> getPicturePaths(String dir)
    {
        mPicturePathList.clear();
        mPicturePathList = Files.searchFiles(dir, ".jpg", false, mPicturePathList);
        return mPicturePathList;
    }
    //store picture information to database
    private void StorePictureInfo2DB()
    {
        SQLiteDatabase db = mDBHelper.getReadableDatabase();
        for(String imagePath : mPicturePathList)
        {
            Cursor cursor = db.query(GalleryDatabaseHelper.Tables.PICTURES,
                     null,
                    GalleryConstrant.Picture.PATH + " =?", new String[]{imagePath},
                    null, null, null);
            if(cursor != null) {
                if(cursor.moveToNext())
                    continue;
            }
            ContentValues values = new ContentValues();
            values.put(GalleryConstrant.Picture.PATH, imagePath);
            db.insert(GalleryDatabaseHelper.Tables.PICTURES, null, values);
        }
    }
    //face detection and store result to database
    public void faceDetectAndStoreResult(){
        SQLiteDatabase db = mDBHelper.getReadableDatabase();
        Cursor cursor = db.query(GalleryDatabaseHelper.Tables.PICTURES,
                new String[]{GalleryConstrant.Picture.ID, GalleryConstrant.Picture.PATH},
                null, null, null, null,
                null, null);
        if (cursor == null) {
            Log.i(TAG, "cursor is null");
            return ;
        }
        try {
            while(cursor.moveToNext()) {
                int imageId = cursor.getInt(0);
                String imagePath = cursor.getString(1);
                ArrayList<LabelInfo>  labelInfoList = DetectFace(imagePath);

                if(labelInfoList != null)
                {
                    ContentValues values = new ContentValues();
                    //删除原始记录
                    db.delete(GalleryDatabaseHelper.Tables.Faces,
                            GalleryConstrant.Face.PICTURE_ID + "=?",
                            new String[]{String.valueOf(imageId)});
                    //将现有的人脸检测结果插入数据库
                    for(LabelInfo labelInfo : labelInfoList)
                    {
                        Gson g = new Gson();
                        String jsonString = g.toJson(labelInfo.boundingBox);
                        //add label information to database
                        values.put(GalleryConstrant.Face.PICTURE_ID, imageId);
                        values.put(GalleryConstrant.Face.CLUSTER_ID, -1);
                        values.put(GalleryConstrant.Face.RECT, jsonString);
                        values.put(GalleryConstrant.Face.FEATURE, "");
                        db.insert(GalleryDatabaseHelper.Tables.Faces, null, values);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cursor.close();
        }
    }
    private ArrayList<LabelInfo> DetectFace(String imagePath)
    {
        if(imagePath.compareTo("") == 0) return null;
        ArrayList<LabelInfo> labelInfos = SmartNative.faceDetect(imagePath);
        return labelInfos;
    }
}

4、数据库是什么时候用?

  • 比如金额交易,数据的批量删除和存储等。比如现在要进行银行转账,不可能扣了A的钱,但是B没有收到,然后A的钱就不知道哪里去了,再比如,现在要备份短信,要么成功备份到磁盘,要么备份失败,而不可能在没有备份成功的情况就把本地给删除了。
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于Android SQLite数据库的封装示例: 1. 创建DatabaseHelper类 ```java public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "mydatabase.db"; private static final int DATABASE_VERSION = 1; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // 创建表格 String createTable = "CREATE TABLE IF NOT EXISTS mytable" + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)"; db.execSQL(createTable); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 升级数据库 db.execSQL("DROP TABLE IF EXISTS mytable"); onCreate(db); } } ``` 2. 创建DatabaseManager类 ```java public class DatabaseManager { private static DatabaseManager instance; private SQLiteDatabase database; private DatabaseHelper dbHelper; public static synchronized void initialize(Context context) { if (instance == null) { instance = new DatabaseManager(); instance.dbHelper = new DatabaseHelper(context); } } public static synchronized DatabaseManager getInstance() { if (instance == null) { throw new IllegalStateException(DatabaseManager.class.getSimpleName() + " is not initialized, call initialize(..) method first."); } return instance; } public synchronized SQLiteDatabase openDatabase() { if (database == null) { database = dbHelper.getWritableDatabase(); } return database; } public synchronized void closeDatabase() { if (database != null) { database.close(); database = null; } } } ``` 3. 创建实体类 ```java public class MyEntity { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } ``` 4. 创建DAO类 ```java public class MyEntityDao { private SQLiteDatabase database; public void open() { database = DatabaseManager.getInstance().openDatabase(); } public void close() { DatabaseManager.getInstance().closeDatabase(); } public void insert(MyEntity entity) { ContentValues values = new ContentValues(); values.put("name", entity.getName()); values.put("age", entity.getAge()); database.insert("mytable", null, values); } public void update(MyEntity entity) { ContentValues values = new ContentValues(); values.put("name", entity.getName()); values.put("age", entity.getAge()); database.update("mytable", values, "id=?", new String[]{String.valueOf(entity.getId())}); } public void delete(int id) { database.delete("mytable", "id=?", new String[]{String.valueOf(id)}); } public MyEntity findById(int id) { Cursor cursor = database.query("mytable", null, "id=?", new String[]{String.valueOf(id)}, null, null, null); if (cursor != null && cursor.moveToFirst()) { MyEntity entity = new MyEntity(); entity.setId(cursor.getInt(cursor.getColumnIndex("id"))); entity.setName(cursor.getString(cursor.getColumnIndex("name"))); entity.setAge(cursor.getInt(cursor.getColumnIndex("age"))); cursor.close(); return entity; } return null; } public List<MyEntity> findAll() { List<MyEntity> entities = new ArrayList<>(); Cursor cursor = database.query("mytable", null, null, null, null, null, null); if (cursor != null && cursor.moveToFirst()) { do { MyEntity entity = new MyEntity(); entity.setId(cursor.getInt(cursor.getColumnIndex("id"))); entity.setName(cursor.getString(cursor.getColumnIndex("name"))); entity.setAge(cursor.getInt(cursor.getColumnIndex("age"))); entities.add(entity); } while (cursor.moveToNext()); cursor.close(); } return entities; } } ``` 5. 在Activity中使用 ```java public class MainActivity extends AppCompatActivity { private MyEntityDao dao; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DatabaseManager.initialize(getApplicationContext()); dao = new MyEntityDao(); dao.open(); // 插入数据 MyEntity entity = new MyEntity(); entity.setName("Tom"); entity.setAge(20); dao.insert(entity); // 更新数据 entity.setName("Jerry"); dao.update(entity); // 删除数据 dao.delete(entity.getId()); // 查询数据 MyEntity e = dao.findById(1); List<MyEntity> entities = dao.findAll(); dao.close(); } @Override protected void onDestroy() { super.onDestroy(); DatabaseManager.getInstance().closeDatabase(); } } ``` 这样就完成了基于Android SQLite数据库的封装,使得操作更加简单方便,同时也提高了代码的可维护性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值