利用SQLite数据库相关知识,制作一个简易的通讯录,将界面需要的图片导入drawable文件夹中,在MainActivity中编写逻辑代码,实现联系人信息的添加、查询、修改以及删除功能。
时间: 2023-06-02 16:05:10 浏览: 289
好的,这是一个技术问题,我可以回答。首先,需要创建一个SQLite数据库来存储联系人信息,可以使用Android内置的SQLiteOpenHelper类来创建和管理数据库。然后,需要在界面中添加相应的输入框和按钮来实现联系人信息的添加、查询、修改和删除功能,并在MainActivity中编写逻辑代码来处理用户的操作。具体实现细节可以参考相关的Android开发教程和示例代码。
相关问题
用android studio,点击按钮可以在Dairy数据库中查看所有记录并显示在listview中,写出SQLite数据库创建和功能实现的完整过程
好的,下面是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 中创建和实现功能的完整过程。
Android studio通讯录制作代码
好的,下面是一个简单的 Android Studio 通讯录制作代码示例,使用 SQLite 数据库来存储联系人信息:
1. 创建一个名为 "Contact" 的 Java 类,用于存储联系人信息。
```java
public class Contact {
private int id;
private String name;
private String phoneNumber;
public Contact() {}
public Contact(int id, String name, String phoneNumber) {
this.id = id;
this.name = name;
this.phoneNumber = phoneNumber;
}
public 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;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
```
2. 创建一个名为 "DatabaseHelper" 的 Java 类,用于管理 SQLite 数据库。
```java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "contacts.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_CONTACTS = "contacts";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_PHONE = "phone_number";
public DatabaseHelper(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_PHONE + " TEXT" + ")";
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);
}
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, contact.getName());
values.put(COLUMN_PHONE, contact.getPhoneNumber());
db.insert(TABLE_CONTACTS, null, values);
db.close();
}
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
contactList.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return contactList;
}
public void updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, contact.getName());
values.put(COLUMN_PHONE, contact.getPhoneNumber());
db.update(TABLE_CONTACTS, values, COLUMN_ID + " = ?",
new String[] { String.valueOf(contact.getId()) });
db.close();
}
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, COLUMN_ID + " = ?",
new String[] { String.valueOf(contact.getId()) });
db.close();
}
}
```
3. 在布局文件中添加一个 RecyclerView 和一个 FloatingActionButton。
```xml
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@android:drawable/ic_input_add"/>
```
4. 在 MainActivity 类中实现 RecyclerView 和 FloatingActionButton 的逻辑。
```java
public class MainActivity extends AppCompatActivity {
private List<Contact> contactList = new ArrayList<>();
private RecyclerView recyclerView;
private ContactAdapter adapter;
private DatabaseHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
adapter = new ContactAdapter(contactList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
db = new DatabaseHelper(this);
contactList.addAll(db.getAllContacts());
adapter.notifyDataSetChanged();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddContactActivity.class);
startActivityForResult(intent, 1);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Contact contact = (Contact) data.getSerializableExtra("contact");
db.addContact(contact);
contactList.clear();
contactList.addAll(db.getAllContacts());
adapter.notifyDataSetChanged();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onDestroy() {
super.onDestroy();
db.close();
}
}
```
5. 在 AddContactActivity 类中实现添加联系人的逻辑。
```java
public class AddContactActivity extends AppCompatActivity {
private EditText inputName;
private EditText inputPhoneNumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contact);
inputName = findViewById(R.id.input_name);
inputPhoneNumber = findViewById(R.id.input_phone_number);
Button btnSave = findViewById(R.id.btn_save);
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = inputName.getText().toString();
String phoneNumber = inputPhoneNumber.getText().toString();
if (!name.isEmpty() && !phoneNumber.isEmpty()) {
Contact contact = new Contact();
contact.setName(name);
contact.setPhoneNumber(phoneNumber);
Intent intent = new Intent();
intent.putExtra("contact", contact);
setResult(RESULT_OK, intent);
finish();
}
}
});
}
}
```
这样一个简单的 Android Studio 通讯录制作代码就完成了。当用户点击 FloatingActionButton 时,将跳转到 AddContactActivity 界面,用户可以输入联系人的姓名和电话号码,并保存到 SQLite 数据库中。在 MainActivity 中使用 RecyclerView 显示所有保存的联系人信息。
阅读全文