Android Studio SQLite实现收藏功能
时间: 2023-11-11 19:05:17 浏览: 149
Android Studio SQLite数据库使用
实现收藏功能,需要使用Android Studio中内置的SQLite数据库来存储用户收藏的数据。下面是一个简单的实现步骤:
1. 创建数据库表
在SQLite数据库中创建一个收藏表,其中包含收藏的id、名称、描述和图片等字段。可以使用以下代码创建表:
```java
public class DBHelper extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "my_database";
private static final String TABLE_NAME = "favorites";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_DESCRIPTION = "description";
private static final String KEY_IMAGE = "image";
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_DESCRIPTION + " TEXT,"
+ KEY_IMAGE + " BLOB"
+ ")";
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
```
2. 实现添加收藏
在用户点击“添加收藏”按钮时,将用户收藏数据插入到SQLite数据库中。可以使用以下代码实现:
```java
public class FavoritesActivity extends AppCompatActivity {
private EditText mNameEditText;
private EditText mDescriptionEditText;
private ImageView mImageView;
private byte[] mImageBytes;
private DBHelper mDBHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
mNameEditText = findViewById(R.id.name_edit_text);
mDescriptionEditText = findViewById(R.id.description_edit_text);
mImageView = findViewById(R.id.image_view);
mDBHelper = new DBHelper(this);
}
public void onAddFavoriteClick(View view) {
String name = mNameEditText.getText().toString();
String description = mDescriptionEditText.getText().toString();
// 插入数据到数据库中
SQLiteDatabase db = mDBHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBHelper.KEY_NAME, name);
values.put(DBHelper.KEY_DESCRIPTION, description);
values.put(DBHelper.KEY_IMAGE, mImageBytes);
db.insert(DBHelper.TABLE_NAME, null, values);
Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
finish();
}
public void onImageClick(View view) {
// 选择图片
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
// 获取选择的图片
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
mImageView.setImageBitmap(bitmap);
// 将图片转换为字节数组
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
mImageBytes = baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
3. 实现查询收藏
在用户进入“我的收藏”页面时,从SQLite数据库中查询出所有收藏的数据并显示到RecyclerView中。可以使用以下代码实现:
```java
public class MyFavoritesActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private FavoritesAdapter mAdapter;
private List<FavoriteItem> mFavoriteItems = new ArrayList<>();
private DBHelper mDBHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_favorites);
mRecyclerView = findViewById(R.id.recycler_view);
mAdapter = new FavoritesAdapter(mFavoriteItems);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
mDBHelper = new DBHelper(this);
// 查询数据库中的数据
SQLiteDatabase db = mDBHelper.getReadableDatabase();
Cursor cursor = db.query(DBHelper.TABLE_NAME, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex(DBHelper.KEY_ID));
String name = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_NAME));
String description = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_DESCRIPTION));
byte[] imageBytes = cursor.getBlob(cursor.getColumnIndex(DBHelper.KEY_IMAGE));
// 将查询到的数据添加到列表中
FavoriteItem item = new FavoriteItem(id, name, description, imageBytes);
mFavoriteItems.add(item);
} while (cursor.moveToNext());
}
mAdapter.notifyDataSetChanged();
}
private class FavoritesAdapter extends RecyclerView.Adapter<FavoritesAdapter.ViewHolder> {
private List<FavoriteItem> mItems;
public FavoritesAdapter(List<FavoriteItem> items) {
mItems = items;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_favorite, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
FavoriteItem item = mItems.get(position);
holder.mNameTextView.setText(item.getName());
holder.mDescriptionTextView.setText(item.getDescription());
if (item.getImageBytes() != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(item.getImageBytes(), 0, item.getImageBytes().length);
holder.mImageView.setImageBitmap(bitmap);
}
}
@Override
public int getItemCount() {
return mItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView mNameTextView;
private TextView mDescriptionTextView;
private ImageView mImageView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
mNameTextView = itemView.findViewById(R.id.name_text_view);
mDescriptionTextView = itemView.findViewById(R.id.description_text_view);
mImageView = itemView.findViewById(R.id.image_view);
}
}
}
}
```
以上就是使用Android Studio内置的SQLite数据库实现收藏功能的步骤。
阅读全文