Android studio设计备忘录,要求实现增删改查功能的代码
时间: 2024-01-22 09:20:14 浏览: 124
以下是一个简单的 Android Studio 设计备忘录的增删改查功能的代码:
1. 创建一个新的 Android Studio 项目
2. 在 activity_main.xml 中添加一个 RecyclerView 和一个 FloatingActionButton
3. 创建一个新的 Java 类,并将其命名为 Memo
4. 在 Memo 类中添加以下代码:
```
public class Memo {
private int id;
private String title;
private String content;
private String date;
public Memo(int id, String title, String content, String date) {
this.id = id;
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;
}
}
```
5. 创建一个新的 Java 类,并将其命名为 MemoAdapter
6. 在 MemoAdapter 类中添加以下代码:
```
public class MemoAdapter extends RecyclerView.Adapter<MemoAdapter.MemoViewHolder> {
private ArrayList<Memo> memos;
private Context context;
public MemoAdapter(ArrayList<Memo> memos, Context context) {
this.memos = memos;
this.context = context;
}
@NonNull
@Override
public MemoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.memo_item, parent, false);
return new MemoViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MemoViewHolder holder, int position) {
holder.title.setText(memos.get(position).getTitle());
holder.content.setText(memos.get(position).getContent());
holder.date.setText(memos.get(position).getDate());
}
@Override
public int getItemCount() {
return memos.size();
}
public class MemoViewHolder extends RecyclerView.ViewHolder {
TextView title, content, date;
public MemoViewHolder(@NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title);
content = itemView.findViewById(R.id.content);
date = itemView.findViewById(R.id.date);
}
}
}
```
7. 在 res/layout 文件夹中创建一个名为 memo_item.xml 的新布局文件,并添加以下代码:
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textSize="16sp" />
<TextView
android:id="@+id/date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textSize="14sp"
android:textStyle="italic" />
</LinearLayout>
```
8. 在 MainActivity.java 中添加以下代码:
```
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MemoAdapter memoAdapter;
private ArrayList<Memo> memos = new ArrayList<>();
private FloatingActionButton addMemoButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
memoAdapter = new MemoAdapter(memos, this);
recyclerView.setAdapter(memoAdapter);
addMemoButton = findViewById(R.id.addMemoButton);
addMemoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddMemoActivity.class);
startActivityForResult(intent, 1);
}
});
loadMemos();
}
private void loadMemos() {
memos.clear();
Cursor cursor = getContentResolver().query(MemoContract.MemoEntry.CONTENT_URI,
null, null, null, null);
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex(MemoContract.MemoEntry._ID));
String title = cursor.getString(cursor.getColumnIndex(MemoContract.MemoEntry.COLUMN_TITLE));
String content = cursor.getString(cursor.getColumnIndex(MemoContract.MemoEntry.COLUMN_CONTENT));
String date = cursor.getString(cursor.getColumnIndex(MemoContract.MemoEntry.COLUMN_DATE));
memos.add(new Memo(id, title, content, date));
} while (cursor.moveToNext());
}
memoAdapter.notifyDataSetChanged();
cursor.close();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
loadMemos();
}
}
}
}
```
9. 在 res/menu 文件夹中创建一个名为 main.xml 的新菜单文件,并添加以下代码:
```
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/deleteAll"
android:title="Delete All" />
</menu>
```
10. 在 MainActivity.java 中添加以下代码:
```
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.deleteAll:
getContentResolver().delete(MemoContract.MemoEntry.CONTENT_URI, null, null);
loadMemos();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
```
11. 在 res/layout 文件夹中创建一个名为 activity_add_memo.xml 的新布局文件,并添加以下代码:
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/titleEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title"
android:textSize="20sp"
android:textStyle="bold" />
<EditText
android:id="@+id/contentEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:hint="Content"
android:textSize="16sp" />
<Button
android:id="@+id/saveButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Save" />
</LinearLayout>
```
12. 在 AddMemoActivity.java 中添加以下代码:
```
public class AddMemoActivity extends AppCompatActivity {
private EditText titleEditText, contentEditText;
private Button saveButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_memo);
titleEditText = findViewById(R.id.titleEditText);
contentEditText = findViewById(R.id.contentEditText);
saveButton = findViewById(R.id.saveButton);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues values = new ContentValues();
values.put(MemoContract.MemoEntry.COLUMN_TITLE, titleEditText.getText().toString());
values.put(MemoContract.MemoEntry.COLUMN_CONTENT, contentEditText.getText().toString());
values.put(MemoContract.MemoEntry.COLUMN_DATE, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
getContentResolver().insert(MemoContract.MemoEntry.CONTENT_URI, values);
setResult(RESULT_OK);
finish();
}
});
}
}
```
13. 在 MemoContract.java 中添加以下代码:
```
public class MemoContract {
private MemoContract() {}
public static final String CONTENT_AUTHORITY = "com.example.mymemoapp";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
public static final String PATH_MEMOS = "memos";
public static final class MemoEntry implements BaseColumns {
public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, PATH_MEMOS);
public static final String TABLE_NAME = "memos";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_CONTENT = "content";
public static final String COLUMN_DATE = "date";
}
}
```
14. 在 MemoDbHelper.java 中添加以下代码:
```
public class MemoDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "memo.db";
public static final int DATABASE_VERSION = 1;
public MemoDbHelper(@Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_MEMO_TABLE = "CREATE TABLE " +
MemoContract.MemoEntry.TABLE_NAME + " (" +
MemoContract.MemoEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
MemoContract.MemoEntry.COLUMN_TITLE + " TEXT NOT NULL, " +
MemoContract.MemoEntry.COLUMN_CONTENT + " TEXT NOT NULL, " +
MemoContract.MemoEntry.COLUMN_DATE + " TEXT NOT NULL" +
");";
db.execSQL(SQL_CREATE_MEMO_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + MemoContract.MemoEntry.TABLE_NAME);
onCreate(db);
}
}
```
15. 在 AndroidManifest.xml 中添加以下代码:
```
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<provider
android:name=".data.MemoProvider"
android:authorities="com.example.mymemoapp"
android:exported="false" />
<activity
android:name=".AddMemoActivity"
android:parentActivityName=".MainActivity" />
```
16. 在 MemoProvider.java 中添加以下代码:
```
public class MemoProvider extends ContentProvider {
public static final int MEMOS = 100;
public static final int MEMO_WITH_ID = 101;
private MemoDbHelper dbHelper;
private static final UriMatcher sUriMatcher = buildUriMatcher();
private static UriMatcher buildUriMatcher() {
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(MemoContract.CONTENT_AUTHORITY, MemoContract.PATH_MEMOS, MEMOS);
uriMatcher.addURI(MemoContract.CONTENT_AUTHORITY, MemoContract.PATH_MEMOS + "/#", MEMO_WITH_ID);
return uriMatcher;
}
@Override
public boolean onCreate() {
dbHelper = new MemoDbHelper(getContext());
return true;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection,
@Nullable String[] selectionArgs, @Nullable String sortOrder) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
int match = sUriMatcher.match(uri);
Cursor cursor;
switch (match) {
case MEMOS:
cursor = db.query(MemoContract.MemoEntry.TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
break;
case MEMO_WITH_ID:
selection = MemoContract.MemoEntry._ID + "=?";
selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };
cursor = db.query(MemoContract.MemoEntry.TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int match = sUriMatcher.match(uri);
Uri returnUri;
switch (match) {
case MEMOS:
long id = db.insert(MemoContract.MemoEntry.TABLE_NAME, null, values);
if (id > 0) {
returnUri = ContentUris.withAppendedId(MemoContract.MemoEntry.CONTENT_URI, id);
} else {
throw new SQLException("Failed to insert row into " + uri);
}
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return returnUri;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int match = sUriMatcher.match(uri);
int rowsDeleted;
switch (match) {
case MEMOS:
rowsDeleted = db.delete(MemoContract.MemoEntry.TABLE_NAME, selection, selectionArgs);
break;
case MEMO_WITH_ID:
selection = MemoContract.MemoEntry._ID + "=?";
selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };
rowsDeleted = db.delete(MemoContract.MemoEntry.TABLE_NAME, selection, selectionArgs);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
if (rowsDeleted != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsDeleted;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection,
@Nullable String[] selectionArgs) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
```
这样,就完成了一个简单的 Android Studio 设计备忘录的增删改查功能的代码。
阅读全文