Android Room 数据库使用教程:实现简单的打卡应用
Android Room 数据库使用教程:实现简单的打卡应用
本教程将引导你使用 Android Room 数据库创建一个简单的打卡应用。你将学习如何创建数据库、定义实体、操作数据以及在应用中展示数据。
**以下是最终代码:**javaimport android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.CalendarView;import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;import androidx.room.Room;
import java.text.SimpleDateFormat;import java.util.Date;import java.util.List;
public class MainActivity extends AppCompatActivity {
private CalendarView calendarView; private Button checkInButton;
private AppDatabase appDatabase;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
calendarView = findViewById(R.id.calendarView); checkInButton = findViewById(R.id.checkInButton);
appDatabase = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, 'check-in-db') .allowMainThreadQueries() .build();
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() { @Override public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) { String selectedDate = formatDate(year, month, dayOfMonth); Toast.makeText(MainActivity.this, '选择的日期:' + selectedDate, Toast.LENGTH_SHORT).show(); } });
checkInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String currentDate = getCurrentDate(); String currentTime = getCurrentTime(); CheckIn checkIn = new CheckIn(currentDate, currentTime); appDatabase.checkInDao().insert(checkIn); Toast.makeText(MainActivity.this, '打卡成功:' + currentDate + ' ' + currentTime, Toast.LENGTH_SHORT).show();
int checkInCount = appDatabase.checkInDao().getCheckInCount(); Toast.makeText(MainActivity.this, '已打卡次数:' + checkInCount, Toast.LENGTH_SHORT).show(); } });
// 在应用启动时显示打卡次数 int checkInCount = appDatabase.checkInDao().getCheckInCount(); Toast.makeText(MainActivity.this, '已打卡次数:' + checkInCount, Toast.LENGTH_SHORT).show();
// 读取所有打卡记录并打印 List<CheckIn> checkIns = appDatabase.checkInDao().getAllCheckIns(); for (CheckIn checkIn : checkIns) { System.out.println('打卡记录:' + checkIn.getDate() + ' ' + checkIn.getTime()); } }
private String formatDate(int year, int month, int dayOfMonth) { SimpleDateFormat sdf = new SimpleDateFormat('yyyy-MM-dd'); Date date = new Date(year - 1900, month, dayOfMonth); return sdf.format(date); }
private String getCurrentDate() { SimpleDateFormat sdf = new SimpleDateFormat('yyyy-MM-dd'); Date date = new Date(); return sdf.format(date); }
private String getCurrentTime() { SimpleDateFormat sdf = new SimpleDateFormat('HH:mm:ss'); Date date = new Date(); return sdf.format(date); }}
注意:
- 这段代码需要你创建
CheckIn实体类、CheckInDao接口和AppDatabase数据库类。*allowMainThreadQueries()方法允许你在主线程进行数据库操作,这在实际应用中应该避免,因为它可能会导致应用卡顿。建议使用异步操作来处理数据库操作。
希望这篇教程能够帮助你理解如何使用 Android Room 数据库创建简单的打卡应用。如果你有任何问题,请随时提出。
原文地址: https://www.cveoy.top/t/topic/blMp 著作权归作者所有。请勿转载和采集!