当前位置:网站首页>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

边栏推荐
- Problems needing attention in mobile terminal testing
- 新手第一次怎么买股票 哪家证券公司开户最好最安全
- Fraud detection cases and Titanic rescued cases
- Differences between C language pointer and array A and &a, &a[0], etc
- Rasa 3.x learning series -rasa [3.2.3] - new version released on July 18, 2022
- Caffe framework and production data source for deep learning
- How vscode debug nodejs
- Time series of machine learning
- Preparation of mobile end test cases
- Research Summary / programming FAQs
猜你喜欢

Overall testing framework for performance testing

spark:获取日志中每个时间段的访问量(入门级-简单实现)

Not configured in app.json (uni releases wechat applet)

Maotai ice cream "bucked the trend" and became popular, but its cross-border meaning was not "selling ice cream"

Spark: get the access volume of each time period in the log (entry level - simple implementation)

Jmmert aggregation test report

Video game design report template and resources over the years

mysql
![Rasa 3.x learning series -rasa [3.2.3] - new version released on July 18, 2022](/img/fd/c7bff1ce199e8b600761d77828c674.png)
Rasa 3.x learning series -rasa [3.2.3] - new version released on July 18, 2022

Activity Registration: how to quickly start the open source tapdata live data platform on a zero basis?
随机推荐
DS binary tree - parent and child nodes of binary tree
The difference and relation among list, set and map
Tiger mouth waterfall: Tongliang version of xiaohukou waterfall
Date processing bean
Leetcode 1288. delete the covered interval (yes, solved)
VS编译后的应用缺少dll
Video game design report template and resources over the years
DS graph - minimum spanning tree
JS judge whether the data is empty
在哪家证券公司开户最好最安全 如何开户炒股票
Differences between C language pointer and array A and &a, &a[0], etc
SQL的SELF JOIN用法
异或程序
“00后”来了!数睿数据迎来新生代「无代码」生力军
CSDN garbage has no bottom line!
Wildfire STM32 domineering, through the firmware library to achieve water light
Simple understanding and implementation of unity delegate
Time series of machine learning
Is it safe for Huatai Securities to open an account? Can it be handled on the mobile phone?
股票开户之后就可以购买6%的理财产品了?