1. 程式人生 > >android的資料儲存(3)(LitePal)

android的資料儲存(3)(LitePal)

在上一章的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"