数据库的使用

写基类的APP类,用于承接上下文

public classAppextendsApplication {

     public staticAppappcontext;

 @Override

      public voidonCreate() {

       super.onCreate();

      appcontext=this;

    }

      }

建一个工具类

 //加上Static 代表只运行一次,且只复制一次数据库
 static{    copyDB();     }

 public static voidcopyDB() {

        InputStream input =null;

       FileOutputStream output =null;

       try{

      input = App.appcontext.getAssets().open("db/commonnum.db");

           File file =newFile(DB_PATH);

       if(!file.exists()) file.mkdirs();

       output =newFileOutputStream(DB_PATH+ File.separator+DB_NAME);

      intlen =0;

      byte[] buffer =new byte[1024];

      while((len = input.read(buffer)) != -1) {

        output.write(buffer,0,len);

   }

            }catch(IOException e) {

          e.printStackTrace();

         }finally{

         try{

       if(output !=null) output.close();

      if(input !=null) input.close();

              }catch(IOException e) {

         e.printStackTrace();

}
}
}

举一个例子

  /**
 * 获取所有的服务类型的名字
 *
 * @return
 */
public static List<Tel> getTelServiceName() {
    List<Tel> tels = new ArrayList<>();
    //获取数据库
    SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH + "/" + DB_NAME, null);
    //那个要查询的数据库的名字
    Cursor cursor = db.rawQuery("select * from classlist;", null);
    while (cursor.moveToNext()) {
       //重数据库查询名字
        String name = cursor.getString(cursor.getColumnIndex("name"));
        //从数据库找到对应的ID
        int id = cursor.getInt(cursor.getColumnIndex("idx"));
        //自己的一个实例类
        Tel tel = new Tel(name, id);
        //添加到集合中
        tels.add(tel);
    }
    //关闭流,节省资源
    cursor.close();
    return tels;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,556评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • SQLite是一种嵌入式的数据库引擎,最后是以文件的形式保存数据的,专门适用于资源有限的设备上进行适量的数据存储,...
    李俊的博客阅读 3,609评论 0 8
  • swift开发需要应用数据库,fmdb笔记繁琐,在swift中准备放弃使用,看到了 Realm这个三方框架很强大,...
    Kean_Qi阅读 7,109评论 9 12
  • 早上出门太急,
    左清晨阅读 75评论 0 0