android中LitePal的使用

网上有一篇文章写的挺好的,推荐给大家:安卓项目实战之:数据库框架 LitePal 3.0 的使用详解

 

LitePal是对SQLite数据库操作进行了封装,采用对象映射的方式操作SQLite数据库,简化了对SQLiter的操作

我也是使用的是最新的LitePal3.0

1、首先添加依赖,引入LitePal3.0,在build.gradle中添加如下内容:

implementation group: 'org.litepal.android', name: 'java', version: '3.0.0'

 

2、在assets目录下创建litepal.xml文件:

<?xml version="1.0" encoding="utf-8" ?>
<litepal>
    <dbname value="db1"></dbname>
    <version value="1"></version>
    <list>
        <mapping class="com.example.chenrui.common.Student"></mapping>
    </list>
</litepal>

dbname是指的是sqlite数据库的名称

version是指的是sqlite数据库的版本号

list是指的表跟对应pojo类的映射关系,需要创建几个表,就对应创建几个pojo类,并在这个配置文件中进行注册,需要注意的是,这些pojo类,必须要继承LitePalSupport类。

 

3、修改AndroidManifest.xml文件:

在application标签中添加:

android:name="org.litepal.LitePalApplication"

 

4、现在开始编写实例代码,本例是通过LitePal3.0对学生进行管理,实现新增、查询、删除学生的功能

 

添加Student.java类:

package com.example.chenrui.common;

import org.litepal.crud.LitePalSupport;

public class Student extends LitePalSupport {

    private Long id;
    private String username;
    private String phone;
    private String city;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

 

列表使用的是RecyclerView组件,这里开始编写RecyclerView组件对应的内容

RecyclerView数据项student_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/username"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textSize="32dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/city"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textSize="32dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/username" />

    <TextView
        android:id="@+id/phone"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textSize="32dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/city" />

    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="20dp"
        android:background="?android:attr/listDivider"
        app:layout_constraintBottom_toBottomOf="parent" />
</android.support.constraint.ConstraintLayout>

注意我是添加了一个View组件,用来实现在每一项之间添加一个分割线

 

适配器类StudentAdapter.java:

package com.example.chenrui.app1;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.chenrui.common.Student;

import java.util.List;

public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.ViewHolder> {

    private List<Student> studentList;

    public StudentAdapter() {
    }

    public List<Student> getStudentList() {
        return studentList;
    }

    public void setStudentList(List<Student> studentList) {
        this.studentList = studentList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.student_item,viewGroup,false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int i) {
        Student student = studentList.get(i);
        viewHolder.username.setText("姓名:" + student.getUsername());
        viewHolder.city.setText("城市:" + student.getCity());
        viewHolder.phone.setText("手机号:" + student.getPhone());

        if(onItemClickListener!=null) {
            viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    onItemClickListener.onItemLongClick(viewHolder.itemView,i);
                    return false;
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return studentList.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView username;
        TextView city;
        TextView phone;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            username = itemView.findViewById(R.id.username);
            city = itemView.findViewById(R.id.city);
            phone = itemView.findViewById(R.id.phone);
        }
    }

    private OnItemClickListener onItemClickListener;
    public interface OnItemClickListener{
        void onItemLongClick(View view , int pos);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

}

 

列表Activity的代码

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Main33Activity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/studentView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout6"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:id="@+id/linearLayout6"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent">

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="新增" />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

MainActivity.java:

package com.example.chenrui.app1;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;

import com.example.chenrui.common.Student;

import org.litepal.LitePal;
import org.litepal.crud.LitePalSupport;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    RecyclerView view;
    StudentAdapter adapter;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(resultCode==RESULT_OK) {
            BindData(view);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Main33Activity.this,Main2Activity.class);
                startActivityForResult(intent,1);
            }
        });

        view = findViewById(R.id.studentView);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        view.setLayoutManager(layoutManager);
        adapter = new StudentAdapter();
        BindData(view);

        adapter.setOnItemClickListener(new StudentAdapter.OnItemClickListener() {
            @Override
            public void onItemLongClick(View view, final int pos) {
                PopupMenu popupMenu = new PopupMenu(Main33Activity.this,view);
                popupMenu.getMenuInflater().inflate(R.menu.menu1,popupMenu.getMenu());

                //弹出式菜单的菜单项点击事件
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        if(item.getItemId()==R.id.delete) {
                            Long id = adapter.getStudentList().get(pos).getId();
                            adapter.getStudentList().remove(pos);
                            LitePal.delete(Student.class,id);
                            adapter.notifyItemRemoved(pos);
                        }
                        return false;
                    }
                });
                popupMenu.show();
            }
        });
    }

    private void BindData(RecyclerView view) {
        //List list = LitePal.findAll(Student.class);
        List list = LitePal.order("id desc").find(Student.class);
        adapter.setStudentList(list);
        view.setAdapter(adapter);


    }
}

上面的代码,删除功能折腾了半天,删除完了不生效,后来添加上adapter.getStudentList().remove(pos);问题解决,需要把adapter绑定的数据也进行更新,问题就解决了。

 

PopupMenu菜单项menu1.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/delete"
        android:title="删除" />
</menu>

 

点击“添加”按钮会进入添加Activity,对应添加的Activity

activity_main2.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Main2Activity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout7"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/textView13"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="姓名:"
            android:textSize="32dp" />

        <EditText
            android:id="@+id/editText7"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName" />

        <TextView
            android:id="@+id/textView14"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="城市:"
            android:textSize="32dp" />

        <EditText
            android:id="@+id/editText8"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName" />

        <TextView
            android:id="@+id/textView15"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="号码:"
            android:textSize="32dp" />

        <EditText
            android:id="@+id/editText9"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout7"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="取消" />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="确定"
            app:layout_constraintStart_toStartOf="parent" />

    </LinearLayout>
</android.support.constraint.ConstraintLayout>

 

Main2Activity.java:

package com.example.chenrui.app1;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.chenrui.common.Student;

import org.litepal.tablemanager.Connector;

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        Button button = findViewById(R.id.button2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                setResult(RESULT_CANCELED,intent);
                Main32Activity.this.finish();
            }
        });

        final EditText username = findViewById(R.id.editText7);
        final EditText city = findViewById(R.id.editText8);
        final EditText phone = findViewById(R.id.editText9);

        Button button2 = findViewById(R.id.button3);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Student student = new Student();
                student.setUsername(username.getText().toString());
                student.setCity(city.getText().toString());
                student.setPhone(phone.getText().toString());
                student.save();

                Intent intent = new Intent();
                setResult(RESULT_OK,intent);
                Main32Activity.this.finish();
            }
        });
    }
}

 

实现的效果:

 

posted @ 2019-01-18 10:19  魔豆  阅读(5410)  评论(1编辑  收藏  举报