当前位置:网站首页>Android SQLite database practice
Android SQLite database practice
2022-07-24 15:05:00 【Xiayu_】
Catalog
SQLite Database actual combat project
Add : Because of the need to recyclerview Control , For specific use, please refer to
Android- Section 7 RecyclerView Detailed explanation
1. Build table
MySQLiteOpenHelper The entity class 
package com.hnucm.a_test133;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
public MySQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql="create table student(id integer primary key autoincrement,stuid varchar(50), stuname varchar(20),stuclass varchar(20))";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
stay activity in 
package com.hnucm.a_test133;
import androidx.appcompat.app.AppCompatActivity;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(this,"students.db",null,1);
SQLiteDatabase sqLiteDatabase=mySQLiteOpenHelper.getWritableDatabase();
}
}

2. To write ui

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">
<EditText
android:id="@+id/editTextTextPersonName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint=" Please enter the student number "
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editTextTextPersonName2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint=" Please enter a name "
app:layout_constraintStart_toStartOf="@+id/editTextTextPersonName"
app:layout_constraintTop_toBottomOf="@+id/editTextTextPersonName" />
<EditText
android:id="@+id/editTextTextPersonName3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint=" Please enter class "
app:layout_constraintStart_toStartOf="@+id/editTextTextPersonName2"
app:layout_constraintTop_toBottomOf="@+id/editTextTextPersonName2" />
<EditText
android:id="@+id/editTextTextPersonName4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint=" Search for student information "
app:layout_constraintStart_toStartOf="@+id/editTextTextPersonName3"
app:layout_constraintTop_toBottomOf="@+id/editTextTextPersonName3" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Add students "
app:layout_constraintBottom_toBottomOf="@+id/editTextTextPersonName3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/editTextTextPersonName3" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Ask the students "
app:layout_constraintBottom_toBottomOf="@+id/editTextTextPersonName4"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/editTextTextPersonName4" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recylerview"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@id/button2"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Available by operation students.db file 
3. Set the add data button

package com.hnucm.a_test133;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText editText;
EditText editText2;
EditText editText3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(this,"students.db",null,1);
SQLiteDatabase sqLiteDatabase=mySQLiteOpenHelper.getWritableDatabase();
editText=findViewById(R.id.editTextTextPersonName);
editText2=findViewById(R.id.editTextTextPersonName2);
editText3=findViewById(R.id.editTextTextPersonName3);
Button button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues contentValues=new ContentValues();
contentValues.put("stuid",editText.getText().toString());
contentValues.put("stuname",editText2.getText().toString());
contentValues.put("stuclass",editText3.getText().toString());
sqLiteDatabase.insert("student",null,contentValues);
Toast.makeText(MainActivity.this," Increase student success ",Toast.LENGTH_LONG).show();
}
});
}
}

4. add to Recyclerview View
First , Before, I added Recyclerview Control , One more needs to be built item Layout file 
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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="150dp">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="42dp"
android:layout_marginLeft="42dp"
android:text="TextView"
app:layout_constraintBottom_toTopOf="@+id/textView2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="@+id/textView2"
app:layout_constraintTop_toBottomOf="@+id/textView2" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintBottom_toTopOf="@+id/textView3"
app:layout_constraintStart_toStartOf="@+id/textView"
app:layout_constraintTop_toBottomOf="@+id/textView" />
</androidx.constraintlayout.widget.ConstraintLayout>
The second step : Create entity class 
The third step : To write myholder,myadapter And the assignment 
package com.hnucm.a_test133;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
EditText editText;
EditText editText2;
EditText editText3;
RecyclerView recyclerView;
List<Student> list=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(this,"students.db",null,1);
SQLiteDatabase sqLiteDatabase=mySQLiteOpenHelper.getWritableDatabase();
editText=findViewById(R.id.editTextTextPersonName);
editText2=findViewById(R.id.editTextTextPersonName2);
editText3=findViewById(R.id.editTextTextPersonName3);
recyclerView=findViewById(R.id.recylerview);// Instantiation
Cursor cursor=sqLiteDatabase.query("student",null,null,null,null,null,null);// It means to get the data of all fields
while (cursor.moveToNext()){//cursor The cursor defaults to the first line , Data can be obtained by moving the cursor
Student student=new Student();
// Sometimes it is necessary to modify multiple identical field names at the same time You can hold down the alt+shift+r
// Fetch data through cursor
student.id=cursor.getInt(0);
student.stuid=cursor.getString(1);
student.stuname=cursor.getString(2);
student.stuclass=cursor.getString(3);
list.add(student);
}
cursor.close();// close cursor, Prevent memory leaks
recyclerView.setAdapter(new MyAdapter());
// Express RecyclerView Arrange in a linear way , One line shows one
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Button button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues contentValues=new ContentValues();
contentValues.put("stuid",editText.getText().toString());
contentValues.put("stuname",editText2.getText().toString());
contentValues.put("stuclass",editText3.getText().toString());
sqLiteDatabase.insert("Student",null,contentValues);
Toast.makeText(MainActivity.this," Increase student success ",Toast.LENGTH_LONG).show();
}
});
}
public class MyAdapter extends RecyclerView.Adapter<MyHolder>{
@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(MainActivity.this).inflate(R.layout.item,parent,false);// load view
MyHolder myHolder=new MyHolder(view);// return view
return myHolder;
}
@Override
public void onBindViewHolder(@NonNull MyHolder holder, int position) {
Student student=list.get(position);
holder.textView.setText(" Student number : "+student.stuid);
holder.textView1.setText(" full name : "+student.stuname);
holder.textView2.setText(" class : "+student.stuclass);
}
@Override
public int getItemCount() {
return list.size();
}
}
public class MyHolder extends RecyclerView.ViewHolder{
TextView textView;// Member variables
TextView textView1;
TextView textView2;
public MyHolder(@NonNull View itemView) {
super(itemView);
textView=itemView.findViewById(R.id.textView);
textView1=itemView.findViewById(R.id.textView2);
textView2=itemView.findViewById(R.id.textView3);
}
}
}
function :
But every time you add data, you just add it to the database , Our list will not refresh the data , So we need to add data to the list every time we click add data

package com.hnucm.a_test133;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
EditText editText;
EditText editText2;
EditText editText3;
RecyclerView recyclerView;
MyAdapter myAdapter;
List<Student> list=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(this,"students.db",null,1);
SQLiteDatabase sqLiteDatabase=mySQLiteOpenHelper.getWritableDatabase();
editText=findViewById(R.id.editTextTextPersonName);
editText2=findViewById(R.id.editTextTextPersonName2);
editText3=findViewById(R.id.editTextTextPersonName3);
recyclerView=findViewById(R.id.recylerview);// Instantiation
Cursor cursor=sqLiteDatabase.query("student",null,null,null,null,null,null);// It means to get the data of all fields
while (cursor.moveToNext()){//cursor The cursor defaults to the first line , Data can be obtained by moving the cursor
Student student=new Student();
// Sometimes it is necessary to modify multiple identical field names at the same time You can hold down the alt+shift+r
// Fetch data through cursor
student.id=cursor.getInt(0);
student.stuid=cursor.getString(1);
student.stuname=cursor.getString(2);
student.stuclass=cursor.getString(3);
list.add(student);
}
cursor.close();// close cursor, Prevent memory leaks
myAdapter = new MyAdapter();
recyclerView.setAdapter(myAdapter);
// Express RecyclerView Arrange in a linear way , One line shows one
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Button button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues contentValues=new ContentValues();
contentValues.put("stuid",editText.getText().toString());
contentValues.put("stuname",editText2.getText().toString());
contentValues.put("stuclass",editText3.getText().toString());
long id = sqLiteDatabase.insert("student", null, contentValues);
Student student=new Student();
student.stuid=editText.getText().toString();
student.stuname=editText2.getText().toString();
student.stuclass=editText3.getText().toString();
student.id= (int) id;
list.add(student);
myAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this," Increase student success ",Toast.LENGTH_LONG).show();
}
});
}
public class MyAdapter extends RecyclerView.Adapter<MyHolder>{
@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(MainActivity.this).inflate(R.layout.item,parent,false);// load view
MyHolder myHolder=new MyHolder(view);// return view
return myHolder;
}
@Override
public void onBindViewHolder(@NonNull MyHolder holder, int position) {
Student student=list.get(position);
holder.textView.setText(" Student number : "+student.stuid);
holder.textView1.setText(" full name : "+student.stuname);
holder.textView2.setText(" class : "+student.stuclass);
}
@Override
public int getItemCount() {
return list.size();
}
}
public class MyHolder extends RecyclerView.ViewHolder{
TextView textView;// Member variables
TextView textView1;
TextView textView2;
public MyHolder(@NonNull View itemView) {
super(itemView);
textView=itemView.findViewById(R.id.textView);
textView1=itemView.findViewById(R.id.textView2);
textView2=itemView.findViewById(R.id.textView3);
}
}
}
function , You can see that we didn't load data at the beginning of the pull-down refresh , After clicking the button, a new piece of data is added 
5. Set query data button

package com.hnucm.a_test133;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
EditText editText;
EditText editText2;
EditText editText3;
EditText editText4;
RecyclerView recyclerView;
MyAdapter myAdapter;
List<Student> list=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(this,"students.db",null,1);
SQLiteDatabase sqLiteDatabase=mySQLiteOpenHelper.getWritableDatabase();
editText=findViewById(R.id.editTextTextPersonName);
editText2=findViewById(R.id.editTextTextPersonName2);
editText3=findViewById(R.id.editTextTextPersonName3);
editText4=findViewById(R.id.editTextTextPersonName4);
recyclerView=findViewById(R.id.recylerview);// Instantiation
Cursor cursor=sqLiteDatabase.query("student",null,null,null,null,null,null);// It means to get the data of all fields
while (cursor.moveToNext()){//cursor The cursor defaults to the first line , Data can be obtained by moving the cursor
Student student=new Student();
// Sometimes it is necessary to modify multiple identical field names at the same time You can hold down the alt+shift+r
// Fetch data through cursor
student.id=cursor.getInt(0);
student.stuid=cursor.getString(1);
student.stuname=cursor.getString(2);
student.stuclass=cursor.getString(3);
list.add(student);
}
cursor.close();// close cursor, Prevent memory leaks
myAdapter = new MyAdapter();
recyclerView.setAdapter(myAdapter);
// Express RecyclerView Arrange in a linear way , One line shows one
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Button button1=findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
list.clear();// Empty data
String content="%"+editText4.getText().toString()+"%";
//like Represents a fuzzy match where stuname like %name%
Cursor cursor= sqLiteDatabase.query("student",null,"stuclass like ?",new String[]{content},null,null,null);// It means to get the data of all fields
while (cursor.moveToNext()) {//cursor The cursor defaults to the first line , Data can be obtained by moving the cursor
Student student=new Student();
// Fetch data through cursor
student.id=cursor.getInt(0);
student.stuid=cursor.getString(1);
student.stuname=cursor.getString(2);
student.stuclass=cursor.getString(3);
list.add(student);
}
cursor.close();// close cursor, Prevent memory leaks
myAdapter.notifyDataSetChanged();// Interface update
}
});
Button button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues contentValues=new ContentValues();
contentValues.put("stuid",editText.getText().toString());
contentValues.put("stuname",editText2.getText().toString());
contentValues.put("stuclass",editText3.getText().toString());
long id = sqLiteDatabase.insert("student", null, contentValues);
Student student=new Student();
student.stuid=editText.getText().toString();
student.stuname=editText2.getText().toString();
student.stuclass=editText3.getText().toString();
student.id= (int) id;
list.add(student);
myAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this," Increase student success ",Toast.LENGTH_LONG).show();
}
});
}
public class MyAdapter extends RecyclerView.Adapter<MyHolder>{
@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(MainActivity.this).inflate(R.layout.item,parent,false);// load view
MyHolder myHolder=new MyHolder(view);// return view
return myHolder;
}
@Override
public void onBindViewHolder(@NonNull MyHolder holder, int position) {
Student student=list.get(position);
holder.textView.setText(" Student number : "+student.stuid);
holder.textView1.setText(" full name : "+student.stuname);
holder.textView2.setText(" class : "+student.stuclass);
}
@Override
public int getItemCount() {
return list.size();
}
}
public class MyHolder extends RecyclerView.ViewHolder{
TextView textView;// Member variables
TextView textView1;
TextView textView2;
public MyHolder(@NonNull View itemView) {
super(itemView);
textView=itemView.findViewById(R.id.textView);
textView1=itemView.findViewById(R.id.textView2);
textView2=itemView.findViewById(R.id.textView3);
}
}
}
function :
Fuzzy matching multiple fields :
Cursor cursor= sqLiteDatabase.query("student",null,"stuclass like ? or stuid like ?",new String[]{content,content},null,null,null);// It means to get the data of all fields

边栏推荐
- Leetcode-09 (next rank + happy number + full rank)
- spark:获取日志中每个时间段的访问量(入门级-简单实现)
- Kotlin类与继承
- Problems needing attention in mobile terminal testing
- A common Dao class and util
- Date processing bean
- PrestoUserError: PrestoUserError(type=USER_ERROR, name=INVALID_FUNCTION_ARGUMENT, message=“Escape st
- C operator priority memory formula
- Intelligent operation and maintenance scenario analysis: how to detect abnormal business system status through exception detection
- Which securities company is the best and safest to open an account? How to open an account and speculate in stocks
猜你喜欢

mysql

Similarities and differences between nor flash and NAND flash

Unity 使用NVIDIA FleX for Unity插件实现制作软体、水流流体、布料等效果学习教程

Leetcode high frequency question 56. merge intervals, merge overlapping intervals into one interval, including all intervals

DS binary tree - maximum distance of binary tree nodes

Leetcode · daily question · 1184. distance between bus stops · simulation

Getting started with mongodb

Overview of dobesie wavelet (DB wavelet function) in wavelet transform

onBlur和onChange冲突解决方法

Grpc middleware implements grpc call retry
随机推荐
Wildfire STM32 domineering, through the firmware library to achieve water light
Route planning method for UAV in unknown environment based on improved SAS algorithm
深入浅出边缘云 | 2. 架构
kali简洁转换语言方法(图解)
Fraud detection cases and Titanic rescued cases
DS diagram - the shortest path of the diagram (excluding the code framework)
Learning rate adjustment strategy in deep learning (1)
Kali concise language transformation method (illustration)
Preparation of mobile end test cases
Here comes the problem! Unplug the network cable for a few seconds and plug it back in. Does the original TCP connection still exist?
How to set packet capturing mobile terminal
Can't remember regular expressions? Here I have sorted out 99 common rules
Outlook tutorial, how to set rules in outlook?
Research Summary / programming FAQs
Summary of Baimian machine learning
Sword finger offer II 001. integer division
Simple encapsulation of wechat applet wx.request
DDD based on ABP -- Entity creation and update
Huawei camera capability
Detailed explanation of address bus, data bus and control bus