如何在Android中使用RecyclerView与数据库?
此示例演示了如何在Android中使用RecyclerView与数据库。
步骤1 - 在Android Studio中创建一个新项目,转到文件 ⇒ 新建项目,并填写所有必需的详细信息以创建新项目。
在build.gradle (Module: app)中添加以下依赖项
implementation 'com.android.support:recyclerview-v7:28.0.0' implementation 'com.android.support:cardview-v7:28.0.0' implementation 'com.android.support:design:28.0.0'
步骤2 - 将以下代码添加到res/layout/activity_main.xml。
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="4dp" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:layout_marginBottom="50dp" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="8dp" android:id="@+id/myContactList" /> <Button android:id="@+id/btnAdd" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_marginEnd="16dp" android:text="ADD" android:padding="2dp" android:layout_marginBottom="4dp"/> </FrameLayout>
步骤3 - 创建如下所述的布局资源文件并添加相应的代码 -
add_contacts.xml -
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/enterName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Name" android:textSize="12dp" android:inputType="text" android:maxLines="1" android:layout_marginEnd="8dp" android:padding="12dp"/> <EditText android:id="@+id/enterPhoneNum" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Number" android:layout_marginTop="10dp" android:textSize="12sp" android:inputType="phone" android:maxLines="1" android:layout_marginEnd="8dp" android:padding="12dp"/> </LinearLayout>
contact_list_layout.xml -
<?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="1dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="12dp"> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/contactName" android:layout_width="220dp" android:layout_height="wrap_content" android:textSize="12sp" android:textStyle="bold" /> <TextView android:layout_below="@+id/contactName" android:id="@+id/phoneNum" android:layout_width="220dp" android:layout_height="wrap_content" android:textSize="12sp" android:textStyle="bold" /> </RelativeLayout> <ImageView android:id="@+id/editContact" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_weight="1" android:src="@drawable/ic_edit" android:contentDescription="TODO" /> <ImageView android:id="@+id/deleteContact" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="1" android:src="@drawable/ic_remove" android:contentDescription="TODO" /> </LinearLayout> </androidx.cardview.widget.CardView>
步骤4 - 创建一个Java类,并将以下代码添加到ContactAdapter.java
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Objects;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;
class ContactAdapter extends RecyclerView.Adapter<ContactViewHolder>
implements Filterable {
private Context context;
private ArrayList<Contacts> listContacts;
private ArrayList<Contacts> mArrayList;
private SqliteDatabase mDatabase;
ContactAdapter(Context context, ArrayList<Contacts> listContacts) {
this.context = context;
this.listContacts = listContacts;
this.mArrayList = listContacts;
mDatabase = new SqliteDatabase(context);
}
@Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.contact_list_layout, parent, false);
return new ContactViewHolder(view);
}
@Override
public void onBindViewHolder(ContactViewHolder holder, int position) {
final Contacts contacts = listContacts.get(position);
holder.tvName.setText(contacts.getName());
holder.tvPhoneNum.setText(contacts.getPhno());
holder.editContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
editTaskDialog(contacts);
}
});
holder.deleteContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mDatabase.deleteContact(contacts.getId());
((Activity) context).finish();
context.startActivity(((Activity) context).getIntent());
}
});
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
listContacts = mArrayList;
}
else {
ArrayList<Contacts> filteredList = new ArrayList<>();
for (Contacts contacts : mArrayList) {
if (contacts.getName().toLowerCase().contains(charString)) {
filteredList.add(contacts);
}
}
listContacts = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = listContacts;
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
listContacts = (ArrayList<Contacts>) filterResults.values;
notifyDataSetChanged();
}
};
}
@Override
public int getItemCount() {
return listContacts.size();
}
private void editTaskDialog(final Contacts contacts) {
LayoutInflater inflater = LayoutInflater.from(context);
View subView = inflater.inflate(R.layout.add_contacts, null);
final EditText nameField = subView.findViewById(R.id.enterName);
final EditText contactField = subView.findViewById(R.id.enterPhoneNum);
if (contacts != null) {
nameField.setText(contacts.getName());
contactField.setText(String.valueOf(contacts.getPhno()));
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Edit contact");
builder.setView(subView);
builder.create();
builder.setPositiveButton("EDIT CONTACT", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final String name = nameField.getText().toString();
final String ph_no = contactField.getText().toString();
if (TextUtils.isEmpty(name)) {
Toast.makeText(context, "Something went wrong. Check your input values", Toast.LENGTH_LONG).show();
} else {
mDatabase.updateContacts(new
Contacts(Objects.requireNonNull(contacts).getId(), name, ph_no));
((Activity) context).finish();
context.startActivity(((Activity)
context).getIntent());
}
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "Task cancelled",Toast.LENGTH_LONG).show();
}
});
builder.show();
}
}步骤5 - 创建一个Java类,并将以下代码添加到Contacts.java
public class Contacts {
private int id;
private String name;
private String phoneNumber;
Contacts(String name, String phno) {
this.name = name;
this.phoneNumber = phno;
}
Contacts(int id, String name, String phno) {
this.id = id;
this.name = name;
this.phoneNumber = phno;
}
int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
String getPhno() {
return phoneNumber;
}
public void setPhno(String phno) {
this.phoneNumber = phno;
}
}步骤6 - 创建一个Java类,并将以下代码添加到ContactViewHolder.java
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
class ContactViewHolder extends RecyclerView.ViewHolder {
TextView tvName, tvPhoneNum;
ImageView deleteContact;
ImageView editContact;
ContactViewHolder(View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.contactName);
tvPhoneNum = itemView.findViewById(R.id.phoneNum);
deleteContact = itemView.findViewById(R.id.deleteContact);
editContact = itemView.findViewById(R.id.editContact);
}
}步骤7 - 创建一个Java类,并将以下代码添加到SqliteDatabase.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class SqliteDatabase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "Contacts";
private static final String TABLE_CONTACTS = "Contacts";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_NAME = "contactName";
private static final String COLUMN_NO = "phoneNumber";
SqliteDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE "
+ TABLE_CONTACTS + "(" + COLUMN_ID
+ " INTEGER PRIMARY KEY,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_NO + " INTEGER" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}
ArrayList<Contacts> listContacts() {
String sql = "select * from " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Contacts> storeContacts = new ArrayList<>();
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
int id = Integer.parseInt(cursor.getString(0));
String name = cursor.getString(1);
String phno = cursor.getString(2);
storeContacts.add(new Contacts(id, name, phno));
}
while (cursor.moveToNext());
}
cursor.close();
return storeContacts;
}
void addContacts(Contacts contacts) {
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, contacts.getName());
values.put(COLUMN_NO, contacts.getPhno());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_CONTACTS, null, values);
}
void updateContacts(Contacts contacts) {
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, contacts.getName());
values.put(COLUMN_NO, contacts.getPhno());
SQLiteDatabase db = this.getWritableDatabase();
db.update(TABLE_CONTACTS, values, COLUMN_ID + " = ?", new String[]{String.valueOf(contacts.getId())});
}
void deleteContact(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, COLUMN_ID + " = ?", new String[]{String.valueOf(id)});
}
}步骤8 - 将以下代码添加到src/MainActivity.java
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private SqliteDatabase mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView contactView = findViewById(R.id.myContactList);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
contactView.setLayoutManager(linearLayoutManager);
contactView.setHasFixedSize(true);
mDatabase = new SqliteDatabase(this);
ArrayList<Contacts> allContacts = mDatabase.listContacts();
if (allContacts.size() > 0) {
contactView.setVisibility(View.VISIBLE);
ContactAdapter mAdapter = new ContactAdapter(this, allContacts);
contactView.setAdapter(mAdapter);
}
else {
contactView.setVisibility(View.GONE);
Toast.makeText(this, "There is no contact in the database. Start adding now", Toast.LENGTH_LONG).show();
}
Button btnAdd = findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addTaskDialog();
}
});
}
private void addTaskDialog() {
LayoutInflater inflater = LayoutInflater.from(this);
View subView = inflater.inflate(R.layout.add_contacts, null);
final EditText nameField = subView.findViewById(R.id.enterName);
final EditText noField = subView.findViewById(R.id.enterPhoneNum);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add new CONTACT");
builder.setView(subView);
builder.create();
builder.setPositiveButton("ADD CONTACT", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final String name = nameField.getText().toString();
final String ph_no = noField.getText().toString();
if (TextUtils.isEmpty(name)) {
Toast.makeText(MainActivity.this, "Something went wrong. Check your input values", Toast.LENGTH_LONG).show();
}
else {
Contacts newContact = new Contacts(name, ph_no);
mDatabase.addContacts(newContact);
finish();
startActivity(getIntent());
}
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Task cancelled", Toast.LENGTH_LONG).show();
}
});
builder.show();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mDatabase != null) {
mDatabase.close();
}
}
}步骤9 - 将以下代码添加到androidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
让我们尝试运行您的应用程序。我假设您已将您的实际Android移动设备连接到您的计算机。要从Android Studio运行应用程序,请打开您的一个项目活动文件,然后点击运行
工具栏中的图标。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕 -


点击这里下载项目代码。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP