用android studio,点击按钮可以在Dairy数据库中查看所有记录并显示在listview中,写出SQLite数据库创建和功能实现的完整过程
时间: 2023-11-26 09:06:02 浏览: 156
Android Studio如何获取SQLite数据并显示到ListView上
好的,下面是SQLite数据库创建和功能实现的完整过程:
1. 在 Android Studio 中创建一个新项目,并在项目的 `app/build.gradle` 文件中添加以下依赖项:
```gradle
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.recyclerview:recyclerview:1.2.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.room:room-runtime:2.3.0'
annotationProcessor 'androidx.room:room-compiler:2.3.0'
}
```
2. 创建一个名为 `Diary` 的类,并使用 `@Entity` 注释将其标记为 Room 数据库表。
```java
@Entity(tableName = "diary_table")
public class Diary {
@PrimaryKey(autoGenerate = true)
private int id;
private String title;
private String content;
private String date;
public Diary(String title, String content, String date) {
this.title = title;
this.content = content;
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
```
3. 创建一个名为 `DiaryDao` 的接口,并使用 `@Dao` 注释将其标记为 Room 数据库访问对象。
```java
@Dao
public interface DiaryDao {
@Insert
void insert(Diary diary);
@Update
void update(Diary diary);
@Delete
void delete(Diary diary);
@Query("DELETE FROM diary_table")
void deleteAllDiaries();
@Query("SELECT * FROM diary_table ORDER BY id DESC")
LiveData<List<Diary>> getAllDiaries();
}
```
4. 创建一个名为 `DiaryDatabase` 的类,并扩展 `RoomDatabase` 类。在 `DiaryDatabase` 类中,创建一个名为 `diaryDao` 的抽象方法,该方法返回 `DiaryDao` 接口的实现。
```java
@Database(entities = {Diary.class}, version = 1)
public abstract class DiaryDatabase extends RoomDatabase {
private static DiaryDatabase instance;
public abstract DiaryDao diaryDao();
public static synchronized DiaryDatabase getInstance(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(context.getApplicationContext(),
DiaryDatabase.class, "diary_database")
.fallbackToDestructiveMigration()
.build();
}
return instance;
}
}
```
5. 在 MainActivity 类中,实例化 `DiaryViewModel` 类,并观察 `getAllDiaries()` 方法返回的 `LiveData` 对象,以便在数据库中添加,更新和删除数据时及时更新 UI。
```java
public class MainActivity extends AppCompatActivity {
private DiaryViewModel viewModel;
private RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
final DiaryAdapter adapter = new DiaryAdapter();
recyclerView.setAdapter(adapter);
viewModel = new ViewModelProvider(this).get(DiaryViewModel.class);
viewModel.getAllDiaries().observe(this, new Observer<List<Diary>>() {
@Override
public void onChanged(List<Diary> diaries) {
adapter.submitList(diaries);
}
});
}
}
```
6. 在 `MainActivity` 中实现添加、更新和删除数据的功能,以及在 `DiaryAdapter` 中实现 `ViewHolder` 和 `RecyclerView.Adapter` 的相关方法。
```java
public class MainActivity extends AppCompatActivity {
private DiaryViewModel viewModel;
private RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
final DiaryAdapter adapter = new DiaryAdapter();
recyclerView.setAdapter(adapter);
viewModel = new ViewModelProvider(this).get(DiaryViewModel.class);
viewModel.getAllDiaries().observe(this, new Observer<List<Diary>>() {
@Override
public void onChanged(List<Diary> diaries) {
adapter.submitList(diaries);
}
});
FloatingActionButton buttonAddDiary = findViewById(R.id.button_add_diary);
buttonAddDiary.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddEditDiaryActivity.class);
startActivityForResult(intent, ADD_DIARY_REQUEST);
}
});
adapter.setOnItemClickListener(new DiaryAdapter.OnItemClickListener() {
@Override
public void onItemClick(Diary diary) {
Intent intent = new Intent(MainActivity.this, AddEditDiaryActivity.class);
intent.putExtra(AddEditDiaryActivity.EXTRA_ID, diary.getId());
intent.putExtra(AddEditDiaryActivity.EXTRA_TITLE, diary.getTitle());
intent.putExtra(AddEditDiaryActivity.EXTRA_CONTENT, diary.getContent());
intent.putExtra(AddEditDiaryActivity.EXTRA_DATE, diary.getDate());
startActivityForResult(intent, EDIT_DIARY_REQUEST);
}
});
}
public static final int ADD_DIARY_REQUEST = 1;
public static final int EDIT_DIARY_REQUEST = 2;
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ADD_DIARY_REQUEST && resultCode == RESULT_OK) {
String title = data.getStringExtra(AddEditDiaryActivity.EXTRA_TITLE);
String content = data.getStringExtra(AddEditDiaryActivity.EXTRA_CONTENT);
String date = data.getStringExtra(AddEditDiaryActivity.EXTRA_DATE);
Diary diary = new Diary(title, content, date);
viewModel.insert(diary);
Toast.makeText(this, "Note saved", Toast.LENGTH_SHORT).show();
} else if (requestCode == EDIT_DIARY_REQUEST && resultCode == RESULT_OK) {
int id = data.getIntExtra(AddEditDiaryActivity.EXTRA_ID, -1);
if (id == -1) {
Toast.makeText(this, "Note can't be updated", Toast.LENGTH_SHORT).show();
return;
}
String title = data.getStringExtra(AddEditDiaryActivity.EXTRA_TITLE);
String content = data.getStringExtra(AddEditDiaryActivity.EXTRA_CONTENT);
String date = data.getStringExtra(AddEditDiaryActivity.EXTRA_DATE);
Diary diary = new Diary(title, content, date);
diary.setId(id);
viewModel.update(diary);
Toast.makeText(this, "Note updated", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Note not saved", Toast.LENGTH_SHORT).show();
}
}
}
```
```java
public class DiaryAdapter extends ListAdapter<Diary, DiaryAdapter.DiaryHolder> {
private OnItemClickListener listener;
public DiaryAdapter() {
super(DIFF_CALLBACK);
}
private static final DiffUtil.ItemCallback<Diary> DIFF_CALLBACK = new DiffUtil.ItemCallback<Diary>() {
@Override
public boolean areItemsTheSame(@NonNull Diary oldItem, @NonNull Diary newItem) {
return oldItem.getId() == newItem.getId();
}
@Override
public boolean areContentsTheSame(@NonNull Diary oldItem, @NonNull Diary newItem) {
return oldItem.getTitle().equals(newItem.getTitle()) &&
oldItem.getContent().equals(newItem.getContent()) &&
oldItem.getDate().equals(newItem.getDate());
}
};
@NonNull
@Override
public DiaryHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.diary_item, parent, false);
return new DiaryHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull DiaryHolder holder, int position) {
Diary currentDiary = getItem(position);
holder.textViewTitle.setText(currentDiary.getTitle());
holder.textViewContent.setText(currentDiary.getContent());
holder.textViewDate.setText(currentDiary.getDate());
}
public Diary getDiaryAt(int position) {
return getItem(position);
}
class DiaryHolder extends RecyclerView.ViewHolder {
private TextView textViewTitle;
private TextView textViewContent;
private TextView textViewDate;
public DiaryHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.text_view_title);
textViewContent = itemView.findViewById(R.id.text_view_content);
textViewDate = itemView.findViewById(R.id.text_view_date);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getAdapterPosition();
if (listener != null && position != RecyclerView.NO_POSITION) {
listener.onItemClick(getItem(position));
}
}
});
}
}
public interface OnItemClickListener {
void onItemClick(Diary diary);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
}
```
7. 创建一个名为 `AddEditDiaryActivity` 的活动,并在其中实现添加和更新数据的功能。同时,将数据传递回 `MainActivity`。
```java
public class AddEditDiaryActivity extends AppCompatActivity {
public static final String EXTRA_ID = "com.example.diary.EXTRA_ID";
public static final String EXTRA_TITLE = "com.example.diary.EXTRA_TITLE";
public static final String EXTRA_CONTENT = "com.example.diary.EXTRA_CONTENT";
public static final String EXTRA_DATE = "com.example.diary.EXTRA_DATE";
private EditText editTextTitle;
private EditText editTextContent;
private TextView textViewDate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit_diary);
editTextTitle = findViewById(R.id.edit_text_title);
editTextContent = findViewById(R.id.edit_text_content);
textViewDate = findViewById(R.id.text_view_date);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
Intent intent = getIntent();
if (intent.hasExtra(EXTRA_ID)) {
setTitle("Edit Note");
editTextTitle.setText(intent.getStringExtra(EXTRA_TITLE));
editTextContent.setText(intent.getStringExtra(EXTRA_CONTENT));
textViewDate.setText(intent.getStringExtra(EXTRA_DATE));
} else {
setTitle("Add Note");
textViewDate.setText(getCurrentDate());
}
}
private String getCurrentDate() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm");
return sdf.format(new Date());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.add_diary_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save_diary:
saveDiary();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void saveDiary() {
String title = editTextTitle.getText().toString();
String content = editTextContent.getText().toString();
String date = textViewDate.getText().toString();
if (title.trim().isEmpty() || content.trim().isEmpty()) {
Toast.makeText(this, "Please insert a title and content", Toast.LENGTH_SHORT).show();
return;
}
Intent data = new Intent();
data.putExtra(EXTRA_TITLE, title);
data.putExtra(EXTRA_CONTENT, content);
data.putExtra(EXTRA_DATE, date);
int id = getIntent().getIntExtra(EXTRA_ID, -1);
if (id != -1) {
data.putExtra(EXTRA_ID, id);
}
setResult(RESULT_OK, data);
finish();
}
}
```
这就是使用 SQLite 数据库在 Android Studio 中创建和实现功能的完整过程。
阅读全文