Android Studio中实现通讯录代码
时间: 2023-07-15 08:12:30 浏览: 250
以下是一个简单的示例,演示如何在Android Studio中实现通讯录代码。该示例使用SQLite数据库来存储联系人信息。
1. 创建一个新的Android Studio项目,包含一个Activity和一个布局文件。
2. 在布局文件中添加一个RecyclerView,用于显示联系人列表。
3. 创建一个数据模型类,用于表示联系人信息。例如:
```java
public class Contact {
private int id;
private String name;
private String phoneNumber;
public Contact(int id, String name, String phoneNumber) {
this.id = id;
this.name = name;
this.phoneNumber = phoneNumber;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
}
```
4. 创建一个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_NAME = "contacts";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_PHONE_NUMBER = "phone_number";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_PHONE_NUMBER + " TEXT)";
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
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_NUMBER, contact.getPhoneNumber());
db.insert(TABLE_NAME, null, values);
db.close();
}
public Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] { COLUMN_ID, COLUMN_NAME, COLUMN_PHONE_NUMBER },
COLUMN_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
cursor.close();
db.close();
return contact;
}
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<>();
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), 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_NUMBER, contact.getPhoneNumber());
db.update(TABLE_NAME, values, COLUMN_ID + "=?", new String[] { String.valueOf(contact.getId()) });
db.close();
}
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, COLUMN_ID + "=?", new String[] { String.valueOf(contact.getId()) });
db.close();
}
}
```
5. 在Activity中初始化RecyclerView和数据库帮助类,并为其提供数据源。例如:
```java
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<Contact> contactList = new ArrayList<>();
private DatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
databaseHelper = new DatabaseHelper(this);
contactList = databaseHelper.getAllContacts();
adapter = new ContactAdapter(contactList);
recyclerView.setAdapter(adapter);
}
}
```
6. 创建一个RecyclerView的适配器,用于将联系人信息显示在列表中。例如:
```java
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ViewHolder> {
private List<Contact> contactList;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView nameTextView;
public TextView phoneNumberTextView;
public ViewHolder(View view) {
super(view);
nameTextView = view.findViewById(R.id.name_text_view);
phoneNumberTextView = view.findViewById(R.id.phone_number_text_view);
}
}
public ContactAdapter(List<Contact> contactList) {
this.contactList = contactList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.contact_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Contact contact = contactList.get(position);
holder.nameTextView.setText(contact.getName());
holder.phoneNumberTextView.setText(contact.getPhoneNumber());
}
@Override
public int getItemCount() {
return contactList.size();
}
}
```
7. 最后,我们可以在Activity中添加一些逻辑来处理用户添加、编辑和删除联系人的操作。例如:
```java
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<Contact> contactList = new ArrayList<>();
private DatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
databaseHelper = new DatabaseHelper(this);
contactList = databaseHelper.getAllContacts();
adapter = new ContactAdapter(contactList);
recyclerView.setAdapter(adapter);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showAddContactDialog();
}
});
}
private void showAddContactDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add contact");
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_add_contact, null);
final EditText nameEditText = dialogView.findViewById(R.id.name_edit_text);
final EditText phoneNumberEditText = dialogView.findViewById(R.id.phone_number_edit_text);
builder.setView(dialogView);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String name = nameEditText.getText().toString();
String phoneNumber = phoneNumberEditText.getText().toString();
Contact contact = new Contact(-1, name, phoneNumber);
databaseHelper.addContact(contact);
contactList.add(contact);
adapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("Cancel", null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
```
这样,我们就完成了一个简单的通讯录应用程序。用户可以使用该应用程序添加、编辑和删除联系人,并在RecyclerView中查看所有联系人信息。
阅读全文