在上一章的SQLiteDatebase来操作数据库好用吗?不同的人有不同的答案,接下来你将接触一个开源库LitePal,它采用了对象关系映射的(ORM)的模式,并将我们平常用到的数据库功能进行封装,使用一行sql语句就可以完成各种建表和增删改查的操作。
一、配置LitePal
1、要想使用开源库LitePal就添加依赖库,在配置文件中添加如下的:
implementation 'org.litepal.android:core:1.4.1'
2、上面步骤就将LitePal成功引入项目中来了,接下来就是配置litepal.xml文件,右击app/src/main目录-->new-->Directory,创建一个assets目录,然后在assets目录下面再创建一个litepal.xml文件
<?xml version="1.0" encoding="utf-8" ?> <litepal> <dbname value="bookStoress"></dbname> //数据库名 <version value="2"></version> //数据库的版本号 <list> <mapping class="com.example.asus.summary3.Pictrue"></mapping> //用map对应映射模式(这里需要写类,让继承DataSupport,这里一定是完整的类名, <mapping class="com.example.asus.summary3.User"></mapping> </list> </litepal>
3、还需要配置一下AndroidManifest.xml文件
在Application下面添加
android:name="org.litepal.LitePalApplication"
4、写类,继承DataSupport
5、创建数据库,调用 LitePal.getDatabase()方法就创建了数据库
6、在升级数据库,以及需要修改表结构时,就没必要像SQLiteDatabase那样麻烦避免数据丢失。
LitePal就不存在这样的问题,要升级数据库只需要将版本号加1,要添加一张表,只需要在litepal.xml文件中的<list>...</list>
中添加对应的map映射就可以了
7、添加数据
很简单,只需要创建对应类的实例,调用一下save()方法就保存了
例如:
Point p=new Point(2,10);
p.save() ;
8、更新数据
对于LitePal而言,对象是否已经存储可以调用model.isSave()方法的结果来判断,返回true就表示已经存储,返回false就表示为】未存储,
例如:
Book book=new Book("高数",20,"西华大学"); book.save(); //对book第一次存储 book.setPrice(30); //修改书的价格 book.save(); //重新保存
例如:
Book book=new Book(); book.setPrice(30); book.setName("英语"); //将name="高数" author="李" 的书的价格改为30,name改为英语 book.updateAll("name=? and author=?","高数","李");
8、删除数据,简单
例如:
DataSupport.deleteAll(Book.class,"price>?","15"); //将数据库中的全部数据中,书价格大于15的全部删除掉
9、查询
LitePal查询返回的是一个List<Object>的集合
例如:
List<Book> books=DataSupport.findAll(Book.class); //查询全部的数据
Book book=DateSupport.findFirst(Book.class)://查询第一个记录
Book book=DataSupport.findLast(Book.class) //查询最后一条记录
除此之外,还可以通过连缀的方式查询更多查询方式
select()方法查询哪几列:
List<Book> books=DataSupport.select("name","price").find(Book.class);
where()指定查询的约束条件:
List<Book> books=DtaSupport.where("price>?","30").find(Book.class);
order()方法指定结果的排序,
List<Book> books=DataSupport.order("price desc").find(Book.class);
其中desc表式降序,asc表示升序
limit()方法指定偏移数量,比如只看表中的前3条数据,
List<Book> books=DataSupport.limit(3).find(Book.class);
offset()方法指定查询结果的偏移量
List<Book> books=DtaSupport.limit(3).offset(1).find(Book.class);
几个方法中和:
List<Book> books=DataSupport.select("name","price","page")
.where("page>?","40")
.order("page desc")
.limit(10)
.offset(10)
.find(Book.class);
查询Book表中的第10条到20条的页数大于20页的条件的name,price,page这三项数据,按page降序
最后还可以,用原生的SQL语句
例:Cursor c=DataSupport.findSQL("select * from Book ");
实例:
1、litepal_activity.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.v4.view.ViewPager android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:id="@+id/pager"> <android.support.v4.view.PagerTabStrip android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="top" android:id="@+id/pager_title"> </android.support.v4.view.PagerTabStrip> </android.support.v4.view.ViewPager> </LinearLayout>
2、litepal_fragment1.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/b1" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:orientation="vertical"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/pictrue_messge" android:hint="pictrue"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/add_pictrue" android:layout_gravity="center" android:text="添加图"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:id="@+id/litepal_f1" android:orientation="vertical"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/user_messge" android:hint="user"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/add_user" android:layout_gravity="center" android:text="添加用户"/> </LinearLayout> </LinearLayout>
3、litepal_fragment2.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/litepal_f2" android:orientation="vertical"> <android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/picture_recyclerview"> </android.support.v7.widget.RecyclerView> </LinearLayout>
4、litepal_fragment3.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/litepal_f3" android:orientation="vertical"> <android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/uer_recyclerview"> </android.support.v7.widget.RecyclerView> </LinearLayout>
5、pic_recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:layout_width="70dp" android:layout_height="70dp" android:layout_marginRight="10dp" android:id="@+id/pic_item_picid"/> <TextView android:layout_width="match_parent" android:layout_height="70dp" android:textSize="25sp" android:gravity="center_vertical" android:id="@+id/pic_item_name"/> </LinearLayout>
6、user_recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:layout_width="70dp" android:layout_height="70dp" android:layout_marginRight="10dp" android:id="@+id/user_item_picid"/> <TextView android:layout_width="match_parent" android:layout_height="70dp" android:textSize="25sp" android:gravity="center_vertical" android:id="@+id/user_item_name"/> </LinearLayout>
7、User.class
public class User extends DataSupport { private String name; private int u_picId; private int id; public User(String name, int u_picId, int id) { this.name = name; this.u_picId = u_picId; this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getU_picId() { return u_picId; } public void setU_picId(int u_picId) { this.u_picId = u_picId; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
8、Pictrue.class
public class Pictrue extends DataSupport{ private int id; private int p_picId; private String name; public Pictrue(int id, int p_picId, String name) { this.id = id; this.p_picId = p_picId; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getP_picId() { return p_picId; } public void setP_picId(int p_picId) { this.p_picId = p_picId; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
9、PictureRecyclerViewAdapter.class
public class PictureRecyclerViewAdapter extends RecyclerView.Adapter<PictureRecyclerViewAdapter.ViewHolder> { private List<Pictrue> pictrueList; public PictureRecyclerViewAdapter(List<Pictrue> pictrueList) { this.pictrueList = pictrueList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.pic_recyclerview_item,parent,false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { Pictrue pictrue=pictrueList.get(position); holder.pic_name.setText(pictrue.getName()); holder.pic_image.setImageResource(pictrue.getP_picId()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(holder.itemView.getContext(),pictrueList.get(position).getName(),Toast.LENGTH_SHORT).show(); } }); } @Override public int getItemCount() { return pictrueList.size(); } class ViewHolder extends RecyclerView.ViewHolder{ ImageView pic_image; TextView pic_name; public ViewHolder(View itemView) { super(itemView); pic_image=itemView.findViewById(R.id.pic_item_picid); pic_name=itemView.findViewById(R.id.pic_item_name); } } }
10、UserRecyclerViewAdapter.class
public class UserRecyclerViewAdapter extends RecyclerView.Adapter<UserRecyclerViewAdapter.ViewHolder> { private List<User> userList; public UserRecyclerViewAdapter(List<User> userList) { this.userList = userList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.user_recyclerview_item,parent,false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { User user=userList.get(position); holder.userName.setText(user.getName()); holder.userImage.setImageResource(user.getU_picId()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(holder.itemView.getContext(),userList.get(position).getName(),Toast.LENGTH_SHORT).show(); } }); } @Override public int getItemCount() { return userList.size(); } class ViewHolder extends RecyclerView.ViewHolder{ ImageView userImage; TextView userName; public ViewHolder(View itemView) { super(itemView); userImage=itemView.findViewById(R.id.user_item_picid); userName=itemView.findViewById(R.id.user_item_name); } } }
11、ListepalFragment1.class
public class ListepalFragment1 extends Fragment implements View.OnClickListener { Context context; EditText pic_messgae; EditText user_message; Button add_pic; Button add_user; int []pic_ids=new int[]{R.drawable.friend3,R.drawable.txxw,R.drawable.p8yx,R.drawable.part3_1,R.drawable.p6txkt}; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) { View view=inflater.inflate(R.layout.litepal_fragment1,container,false); this.context=container.getContext(); pic_messgae=view.findViewById(R.id.pictrue_messge); user_message=view.findViewById(R.id.user_messge); add_pic=view.findViewById(R.id.add_pictrue); add_user=view.findViewById(R.id.add_user); add_user.setOnClickListener(this); add_pic.setOnClickListener(this); return view; } @Override public void onClick(View view) { switch (view.getId()){ case R.id.add_pictrue:{ String picName=pic_messgae.getText().toString(); int i=(int)(Math.random()*pic_ids.length); Pictrue pictrue=new Pictrue(0,pic_ids[i],picName); pictrue.save(); pic_messgae.setText(""); LitepalFragment2 fragment2=((LitePalActivity)context).f2; fragment2.init(); fragment2.adapter.notifyDataSetChanged(); break; } case R.id.add_user:{ String name=user_message.getText().toString(); int i=(int)(Math.random()*pic_ids.length); User user=new User(name,pic_ids[i],0); user.save(); user_message.setText(""); LitepalFragment3 fragment3=((LitePalActivity)context).f3; fragment3.init(); fragment3.adapter.notifyDataSetChanged(); break; } } } }
12、LitepalFragment2.class
public class LitepalFragment2 extends Fragment { List<Pictrue> pictrueList; RecyclerView recyclerView; PictureRecyclerViewAdapter adapter; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) { View view=inflater.inflate(R.layout.litepal_fragment2,container,false); init(); recyclerView=view.findViewById(R.id.picture_recyclerview); LinearLayoutManager layoutManager=new LinearLayoutManager(getContext()); recyclerView.setLayoutManager(layoutManager); adapter=new PictureRecyclerViewAdapter(pictrueList); recyclerView.setAdapter(adapter); return view; } public void init(){ pictrueList= DataSupport.findAll(Pictrue.class); } }
13、LitepalFragment3.class
public class LitepalFragment3 extends Fragment { List<User> userList; RecyclerView recyclerView; UserRecyclerViewAdapter adapter; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) { View view=inflater.inflate(R.layout.litepal_fragment3,container,false); init(); recyclerView=view.findViewById(R.id.uer_recyclerview); LinearLayoutManager layoutManager=new LinearLayoutManager(getContext()); recyclerView.setLayoutManager(layoutManager); adapter=new UserRecyclerViewAdapter(userList); recyclerView.setAdapter(adapter); return view; } public void init(){ userList= DataSupport.findAll(User.class); } }
14、LitePalActivity.class
public class LitePalActivity extends FragmentActivity { private List<String> pagertitle=new ArrayList<String>(); private List<Fragment> fragmentList=new ArrayList<Fragment>(); ViewPager pager; PagerTabStrip pagerTabStrip; MyViewPagerAdapter adapter; ListepalFragment1 f1=new ListepalFragment1(); LitepalFragment2 f2=new LitepalFragment2(); LitepalFragment3 f3=new LitepalFragment3(); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.litepal_activity); init(); LitePal.getDatabase(); pager=findViewById(R.id.pager); adapter=new MyViewPagerAdapter(getSupportFragmentManager(),pagertitle,fragmentList); pager.setAdapter(adapter); pagerTabStrip=findViewById(R.id.pager_title); } private void init(){ pagertitle.add("录入"); pagertitle.add("图片"); pagertitle.add("用户"); fragmentList.add(f1); fragmentList.add(f2); fragmentList.add(f3); for(int i=0;i<2;i++){ new Pictrue(0+1,R.drawable.rj,"p"+i).save(); new User("u"+i,R.drawable.txkt,0+1).save(); } } }
15、配置LitePal
在assets文件下面的litepal.xml
<?xml version="1.0" encoding="utf-8" ?> <litepal> <dbname value="bookStoress"></dbname> <version value="2"></version> <list> <mapping class="com.example.asus.summary3.Pictrue"></mapping> <mapping class="com.example.asus.summary3.User"></mapping> </list> </litepal>
添加依赖库:
implementation 'org.litepal.android:core:1.4.1'
在配置文件:
android:name="org.litepal.LitePalApplication"