梳理SQLiteDatabase、openOrCreateDatabase、context、SQLiteOpenHelper

本文深入探讨了Android中创建数据库的两种主要方式:通过SQLiteDatabase.openOrCreateDatabase方法和利用Context.openOrCreateDatabase方法,以及SQLiteOpenHelper类在简化数据库操作过程中的作用。重点分析了这些API的内部机制,包括如何处理数据库的创建、打开、读写以及版本更新等问题,并提供了实际应用示例。文章旨在为开发者提供清晰的理解和实用的指导,以便在实际项目中高效地进行数据库管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 梳理SQLiteDatabase、openOrCreateDatabase、SQLiteOpenHelper

 

                    据我所知,android创建数据库可以通过以下方法:

                                                  

一、 SQLiteDatabase.openOrCreateDatabase(file, factory):(以下都在这个SQLiteDatabase类中)

                         1. 一个类名+方法就是个static方法:

                            public static SQLiteDatabase openOrCreateDatabase(File file, CursorFactory factory) {
                                      return openOrCreateDatabase(file.getPath(), factory);
                             }

                         2. 换了绝对路径。

                             public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory) {
                                    return openDatabase(path, factory, CREATE_IF_NECESSARY);
                             }

                         3.去调用了openDatabase方法。

                                      public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags) {
                                              SQLiteDatabase db = null;
                                              try {
                                                  // Open the database.
                                                  return new SQLiteDatabase(path, factory, flags);
                                              } catch (SQLiteDatabaseCorruptException e) {
                                                  // Try to recover from this, if we can.
                                                  // TODO: should we do this for other open failures?
                                                  Log.e(TAG, "Deleting and re-creating corrupt database " + path, e);
                                                  EventLog.writeEvent(EVENT_DB_CORRUPT, path);
                                                  new File(path).delete();
                                                  return new SQLiteDatabase(path, factory, flags);
                                              }
                                          }

                        

                         4. 关键的就这行代码:return new SQLiteDatabase(path, factory, flags);其他的是异常处理。

                            也就是新建了这个类,我们创建数据库也可以这样直接new出来。

                         5.现在关键的工作就落在SQLiteDatabase这个类的构造函数上了。  

    private SQLiteDatabase(String path, CursorFactory factory, int flags) {
        if (path == null) {
            throw new IllegalArgumentException("path should not be null");
        }
        mFlags = flags;
        mPath = path;
        mLogStats = "1".equals(android.os.SystemProperties.get("db.logstats"));
        mSlowQueryThreshold = SystemProperties.getInt(LOG_SLOW_QUERIES_PROPERTY, -1);

        mLeakedException = new IllegalStateException(path +
            " SQLiteDatabase created and never closed");
        mFactory = factory;
        dbopen(mPath, mFlags);   <-----------------------------------------------------------
        mPrograms = new WeakHashMap<SQLiteClosable,Object>();
        try {
            setLocale(Locale.getDefault());
        } catch (RuntimeException e) {
            Log.e(TAG, "Failed to setLocale() when constructing, closing the database", e);
            dbclose();
            throw e;
        }
    }

                   6.起关键的就是 dbopen(mPath, mFlags);

                           private native void dbopen(String path, int flags);

                   7.看到这个native,就是jni咯!往下就是c++了。其中细体什么实现open或create就不用管了。感兴趣可以往下跟。

 

 

 二、context.openOrCreateDatabase(name, mode, factory);

                                     1、看android帮助是这样描述的:

                                      Open a new private SQLiteDatabase associated with this Context's application package.

                                      Create the database file if it doesn't exist.

                                      2 、看源码没发现细体的实现部分的代码,发现的话分享一下给我。搜了很多源码,只有这样:

                                           context.java中: 

                                           public abstract SQLiteDatabase openOrCreateDatabase(String name,int mode, CursorFactory factory);

                                           是个抽象方法,其子类ContextWrapper.java:

                                           public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) {
                                                         return mBase.openOrCreateDatabase(name, mode, factory);
                                          }

                                          又没见哪个子类去覆盖这个方法;

 

         小结:查网上一些资料也是说第二种通过context的方法,其实最终也是得通过SQLiteDatabase这个类中的方法。

                      我认为也是,因为1.context中也用到SQLiteDatabase 这个类啊,可以直接调用这个SQLiteDatabase 的方法嘛。

                                                      2.我们知道在data/data+加上这个应用的包名,就是这个应用程序存放私有数据的目录。那么这个应用程序

                                                       只要通过数据库名称就能找到其路径。而这个SQLiteDatabase的 openOrCreateDatabase(File file, CursorFactory factory)

                                                       再到openOrCreateDatabase(String path, CursorFactory factory);由此可猜这个openOrCreateDatabase(file...)应该是提供

                                                       给context的。

 

 

       (三) 剩下就是这个SQLiteOpenHelper

                        1. 都说这个SQLiteOpenHelper.java类是方便操作数据库的类。

                        2. 那分析一下源码

                                        public abstract class SQLiteOpenHelper

                         3.所以通常我们要使用个类就得去继承它。并去实现父类的抽象方法如:

                                        public class DatabaseHelper extends SQLiteOpenHelper
                                        {
                                         public DatabaseHelper(Context context, String name, CursorFactory cursorFactory, int version)
                                         {
                                          super(context, name, cursorFactory, version);
                                         }

                                         @Override
                                         public void onCreate(SQLiteDatabase db)
                                         {  
                                         }

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

                                         @Override
                                         public void onOpen(SQLiteDatabase db)
                                         {
                                          super.onOpen(db);
                                         }
                                        }

                         4. 好像就这么简单,其实什么也没做。那什么创建或打开数据库?

                         5.重要的是SQLiteOpenHelper中的getWritableDatabase和getReadableDatabase方法,你会发现getReadableDatabase中调用了getWritableDatabase

                         6.所以只要getWritableDatabase清楚getWritableDatabase是如何实现的,就很明朗了。

                                                                                                                                       看似复杂,  慢慢往下看,还有注释(同时要清楚这方法目的就是要创建或打开数据库)

 public synchronized SQLiteDatabase getWritableDatabase() {
        if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
            return mDatabase;  // The database is already open for business                  //如果已经打开了,直接返回。
        }

        if (mIsInitializing) {
            throw new IllegalStateException("getWritableDatabase called recursively");         
        }

        // If we have a read-only database open, someone could be using it
        // (though they shouldn't), which would cause a lock to be held on
        // the file, and our attempts to open the database read-write would
        // fail waiting for the file lock.  To prevent that, we acquire the
        // lock on the read-only database, which shuts out other users.

        boolean success = false;
        SQLiteDatabase db = null;
        if (mDatabase != null) mDatabase.lock();
        try {
            mIsInitializing = true;
            if (mName == null) {
                db = SQLiteDatabase.create(null);                                                                        //以上没多大意义,可以不管
            } else {
                db = mContext.openOrCreateDatabase(mName, 0, mFactory);                    //关键是这行代码,是不是很熟悉
            }

            int version = db.getVersion();
            if (version != mNewVersion) {
                db.beginTransaction();
                try {
                    if (version == 0) {
                           onCreate(db);  //子类我们实现的方法(其实什么也没做,要想这第一次创建时做一些操作,

                                                     //就自己在子类的方法实现,如创建表)                                                                            
                    } else {
                        onUpgrade(db, version, mNewVersion);  //子类我们实现的方法(版本发生变化)
                    }
                    db.setVersion(mNewVersion);
                    db.setTransactionSuccessful();
                } finally {
                    db.endTransaction();
                }
            }

            onOpen(db);                                    //子类我们实现的方法                                            
            success = true;
            return db;
        } finally {
            mIsInitializing = false;
            if (success) {
                if (mDatabase != null) {
                    try { mDatabase.close(); } catch (Exception e) { }
                    mDatabase.unlock();
                }
                mDatabase = db;
            } else {
                if (mDatabase != null) mDatabase.unlock();
                if (db != null) db.close();
            }
        }
    }

 

 

 

 

 

 

 

 

 

 

 

               
### 使用Transformer模型进行图像分类的方法 #### 方法概述 为了使Transformer能够应用于图像分类任务,一种有效的方式是将图像分割成固定大小的小块(patches),这些小块被线性映射为向量,并加上位置编码以保留空间信息[^2]。 #### 数据预处理 在准备输入数据的过程中,原始图片会被切分成多个不重叠的patch。假设一张尺寸为\(H \times W\)的RGB图像是要处理的对象,则可以按照设定好的宽度和高度参数来划分该图像。例如,对于分辨率为\(224\times 224\)像素的图像,如果选择每边切成16个部分的话,那么最终会得到\((224/16)^2=196\)个小方格作为单独的特征表示单元。之后,每一个这样的补丁都会通过一个简单的全连接层转换成为维度固定的嵌入向量。 ```python import torch from torchvision import transforms def preprocess_image(image_path, patch_size=16): transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), # 假设目标分辨率是224x224 transforms.ToTensor(), ]) image = Image.open(image_path).convert('RGB') tensor = transform(image) patches = [] for i in range(tensor.shape[-2] // patch_size): # 高度方向上的循环 row_patches = [] for j in range(tensor.shape[-1] // patch_size): # 宽度方向上的循环 patch = tensor[:, :, i*patch_size:(i+1)*patch_size, j*patch_size:(j+1)*patch_size].flatten() row_patches.append(patch) patches.extend(row_patches) return torch.stack(patches) ``` #### 构建Transformer架构 构建Vision Transformer (ViT),通常包括以下几个组成部分: - **Patch Embedding Layer**: 将每个图像块转化为低维向量; - **Positional Encoding Layer**: 添加绝对或相对位置信息给上述获得的向量序列; - **Multiple Layers of Self-Attention and Feed Forward Networks**: 多层自注意机制与前馈神经网络交替堆叠而成的核心模块; 最后,在顶层附加一个全局平均池化层(Global Average Pooling)以及一个多类别Softmax回归器用于预测类标签。 ```python class VisionTransformer(nn.Module): def __init__(self, num_classes=1000, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=False, drop_rate=0.): super().__init__() self.patch_embed = PatchEmbed(embed_dim=embed_dim) self.pos_embed = nn.Parameter(torch.zeros(1, self.patch_embed.num_patches + 1, embed_dim)) self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) dpr = [drop_rate for _ in range(depth)] self.blocks = nn.Sequential(*[ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=dpr[i], ) for i in range(depth)]) self.norm = nn.LayerNorm(embed_dim) self.head = nn.Linear(embed_dim, num_classes) def forward(self, x): B = x.shape[0] cls_tokens = self.cls_token.expand(B, -1, -1) x = self.patch_embed(x) x = torch.cat((cls_tokens, x), dim=1) x += self.pos_embed x = self.blocks(x) x = self.norm(x) return self.head(x[:, 0]) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值