Android 数据库编程——使用litpal框架

本文主要是介绍Android数据库基于litpal框架的编写,包括注释部分的增删改查。方便今后查看,做下笔记。

1.下载 litepal-1.1.1-src.jar(其他版本也可),网上有很多下载连接。下载完成之后,把它放到工程目录的libs目录下。

2.新建litpal.xml文件。把它放到工程目录的assets目录下。

<?xml version="1.0" encoding="utf-8"?>  
<litepal>  
    <dbname value="demo" ></dbname>  
  
    <version value="4" ></version>  
  
    <list>  
        <mapping class="com.example.databasetest.model.News"></mapping>  
         <mapping class="com.example.databasetest.model.Comment"></mapping>  
          <mapping class="com.example.databasetest.model.Introduction"></mapping>  
        <mapping class="com.example.databasetest.model.Category"></mapping>  
    </list>  
</litepal>  

注意:<list>下的子标签<mapping>是根据后边的具体情况添加进去的。


3.在AndroidManifest.xml中的<application>标签里加上这一句 android:name="org.litepal.LitePalApplication" 。

注意:(1)有些程序可能会有自己的Application,并在这里配置过了。比如说有一个MyApplication,没有关系,这时只需要修改一下MyApplication的继承结构,让它不要直接继承Application类,而是继承LitePalApplication类,就可以使用一切都能正常工作了。

(2)但是,有些程序可能会遇到一些更加极端的情况,比如说MyApplication需要继承另外一个AnotherApplication,并且这个AnotherApplication还是在jar包当中的,不能修改它的代码。这种情况应该算是比较少见了,但是如果你遇到了的话也不用急,仍然是有解释方案的。你可以把LitePal的源码下载下来,然后把src目录下的所有代码直接拷贝到你项目的src目录下面,接着打开LitePalApplication类,将它的继承结构改成继承自AnotherApplication,再让MyApplication继承自LitePalApplication,这样所有的Application就都可以在一起正常工作了。


4.MainActivity.java

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //创建表 SQLiteDatabase db = Connector.getDatabase();  
      //增加表 SQLiteDatabase db = Connector.getDatabase();  
     //增加列 SQLiteDatabase db = Connector.getDatabase();
 
     /* //存储一条数据到news表中
        News news = new News();  
        news.setTitle("这是一条新闻标题");  
        news.setContent("这是一条新闻内容");  
        news.setPublishDate(new Date());  
        Log.d("TAG", "news id is " + news.getId());  
        //news.saveThrows();  可以抛出异常
        news.save();  
        Log.d("TAG", "news id is " + news.getId());  
        if (news.save()) {  
            Toast.makeText(getApplicationContext(), "存储成功", Toast.LENGTH_SHORT).show();  
        } else {  
            Toast.makeText(getApplicationContext(), "存储失败", Toast.LENGTH_SHORT).show();  
        }  */
        
     /*   Comment comment1 = new Comment();  
        comment1.setContent("好评!");  
        comment1.setPublishDate(new Date());  
        comment1.save();  
        Comment comment2 = new Comment();  
        comment2.setContent("赞一个");  
        comment2.setPublishDate(new Date());  
        comment2.save();  
        News news = new News();  
        news.getCommentList().add(comment1);  
        news.getCommentList().add(comment2);  
        news.setTitle("第二条新闻标题");  
        news.setContent("第二条新闻内容");  
        news.setPublishDate(new Date());  
        news.setCommentCount(news.getCommentList().size());  
        news.save();  */
        
      /* 存储集合数据  List<News> newsList = null;  
        DataSupport.saveAll(newsList);  */
    /*    //把news表中id为2的记录的标题改成“今日iPhone6发布”
        ContentValues values = new ContentValues();  
        values.put("title", "今日iPhone6发布");  
        DataSupport.update(News.class, values, 2);  */
        
   /* 或者  News updateNews = new News();  
		updateNews.setTitle("今日iPhone6发布");  
		updateNews.update(2); */
        
      /*  //把news表中标题为“今日iPhone6发布”的所有新闻的标题改成“今日iPhone6 Plus发布”
        ContentValues values = new ContentValues();  
        values.put("title", "今日iPhone6 Plus发布");  
        DataSupport.updateAll(News.class, values, "title = ?", "今日iPhone6发布");*/
        
    /*   // 把news表中标题为“今日iPhone6发布”且评论数量大于0的所有新闻的标题改成“今日iPhone6 Plus发布”
        ContentValues values = new ContentValues();  
        values.put("title", "今日iPhone6 Plus发布");  
        DataSupport.updateAll(News.class, values, "title = ? and commentcount > ?", "今日iPhone6发布", "0");*/
        
       /* 或者 News updateNews = new News();  
        updateNews.setTitle("今日iPhone6发布");  
        updateNews.updateAll("title = ? and commentcount > ?", "今日iPhone6发布", "0");*/
        //把news表中所有新闻的标题都改成“今日iPhone6发布”
        ContentValues values = new ContentValues();  
        values.put("title", "今日iPhone6 Plus发布");  
        DataSupport.updateAll(News.class, values);  
        
      /*  //把news表中所有新闻的评论数清零,
        //将评论数修改成0,只是调用updateNews.setCommentCount(0)这样是不能修改成功的,
        //因为即使不调用这行代码,commentCount的值也默认是0。
        News updateNews = new News();  
        updateNews.setToDefault("commentCount");  
        updateNews.updateAll();  
        
        //删除news表中id为2的记录
        DataSupport.delete(News.class, 2);  
        
        //把news表中标题为“今日iPhone6发布”且评论数等于0的所有新闻都删除掉
        DataSupport.deleteAll(News.class, "title = ? and commentcount = ?", "今日iPhone6发布", "0");  
        
        //把news表中所有的数据全部删除掉
        DataSupport.deleteAll(News.class); */
        
       /* //查询news表中id为1的这条记录
        News news = DataSupport.find(News.class, 1);  
        */
        /*//获取news表中的第一条数据
        News firstNews = DataSupport.findFirst(News.class);  
        //获取News表中的最后一条数据
        News lastNews = DataSupport.findLast(News.class);  
        //把news表中id为1、3、5、7的数据都查出来
        List<News> newsList = DataSupport.findAll(News.class, 1, 3, 5, 7);  */
       
    /*    //查询的多个id已经封装到一个数组里
        long[] ids = new long[] { 1, 3, 5, 7 };  
        List<News> newsList = DataSupport.findAll(News.class, ids);  
        
        //查询所有数据
        List<News> allNews = DataSupport.findAll(News.class);*/
        
        /*//查询news表中所有评论数大于零的新闻,等同于:select * from users where commentcount > 0;
        List<News> newsList = DataSupport.where("commentcount > ?", "0").find(News.class);  
        或者
        Cursor cursor = DataSupport.findBySQL("select * from news where commentcount>?", "0"); //findBySQL()方法返回的是一个Cursor对象
        */
        
        /*//查询news表中所有评论数大于零的新闻,只要title和content这两列数据:select title,content from users where commentcount > 0; 
        List<News> newsList = DataSupport.select("title", "content")  
                .where("commentcount > ?", "0").find(News.class);*/
        
    /*    //将查询出的新闻按照发布的时间倒序排列,
        //即最新发布的新闻放在最前面:
        //等同于select title,content from users where commentcount > 0 order by publishdate desc;
        List<News> newsList = DataSupport.select("title", "content")  
                .where("commentcount > ?", "0")  
                .order("publishdate desc").find(News.class);  */
      
       /* //将查询出的新闻按照发布的时间倒序排列,只查询出前10条数据
        //等同于select title,content from users where commentcount > 0 order by publishdate desc limit 10;
        List<News> newsList = DataSupport.select("title", "content")  
                .where("commentcount > ?", "0")  
                .order("publishdate desc").limit(10).find(News.class); */
        
        //对新闻进行分页展示,翻到第二页时,展示第11到第20条新闻
        //等同于:select title,content from users where commentcount > 0 order by publishdate desc limit 10,10;  
        List<News> newsList = DataSupport.select("title", "content")  
                .where("commentcount > ?", "0")  
                .order("publishdate desc").limit(10).offset(10)  
                .find(News.class);  
        
        //激进查询,查询news表中id为1的新闻,并且把这条新闻所对应的评论也一起查询出来
        //激进查询只能查询出指定表的关联表数据,但是没法继续迭代查询关联表的关联表数据
        News news = DataSupport.find(News.class, 1, true);  
        List<Comment> commentList = news.getCommentList();  
        
    /*    //统计news表中一共有多少行
        int result = DataSupport.count(News.class); */
        
    /*    //统计一共有多少条新闻是零评论的
        //连缀不仅适用于count()方法,也同样适用于下面我们将要介绍的所有方法
        int result = DataSupport.where("commentcount = ?", "0").count(News.class);  */
        
       /* //统计news表中评论的总数量
        int result = DataSupport.sum(News.class, "commentcount", int.class);  */
        
   /*     //统计news表中平均每条新闻有多少评论
        double result = DataSupport.average(News.class, "commentcount");  */
        
     /*   //news表中所有新闻里面最高的评论数是多少
        int result = DataSupport.max(News.class, "commentcount", int.class);  */
        
        //news表中所有新闻里面最少的评论数是多少
        int result = DataSupport.min(News.class, "commentcount", int.class); 
        
    }

}

5.News.java

public class News extends DataSupport{
	private int id;  
    private String title;       
    private String content;      
    private Date publishDate;        
    private int commentCount;
    //建立表关联一对一
    private Introduction introduction;  
  //建立表关联多对一
    private List<Comment> commentList = new ArrayList<Comment>();  
    //建立表关联多对多
    private List<Category> categoryList = new ArrayList<Category>();  
    
    
    // 自动生成get、set方法  
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public Date getPublishDate() {
		return publishDate;
	}
	public void setPublishDate(Date publishDate) {
		this.publishDate = publishDate;
	}
	public int getCommentCount() {
		return commentCount;
	}
	public void setCommentCount(int commentCount) {
		this.commentCount = commentCount;
	}
	public Introduction getIntroduction() {
		return introduction;
	}
	public void setIntroduction(Introduction introduction) {
		this.introduction = introduction;
	}
	public List<Comment> getCommentList() {
		//return commentList;
		return DataSupport.where("news_id = ?", String.valueOf(id)).find(Comment.class);  
	}
	public void setCommentList(List<Comment> commentList) {
		this.commentList = commentList;
	}
	public List<Category> getCategoryList() {
		return categoryList;
	}
	public void setCategoryList(List<Category> categoryList) {
		this.categoryList = categoryList;
	}  
    
    
    
}

6.Comment.java

public class Comment extends DataSupport{
	
	  private int id;      
	  private String content;
	  private Date publishDate;
	  //建立表关联多对一
	  private News news;
	// 自动生成get、set方法   
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public Date getPublishDate() {
		return publishDate;
	}
	public void setPublishDate(Date publishDate) {
		this.publishDate = publishDate;
	}  
	      
	  
}

7.Introduction.java

public class Introduction extends DataSupport{
	private int id;     
    private String guide;       
    private String digest;
    
    // 自动生成get、set方法 
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getGuide() {
		return guide;
	}
	public void setGuide(String guide) {
		this.guide = guide;
	}
	public String getDigest() {
		return digest;
	}
	public void setDigest(String digest) {
		this.digest = digest;
	}  
      
}

8.Category.java

public class Category extends DataSupport{
	  private int id;   
	  private String name;
	  //建立表关联多对多
	  private List<News> newsList = new ArrayList<News>();  
	  // 自动生成get、set方法  
	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;
	}  
	      
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值