You need to enable JavaScript to run this app. 如何通过SQLite数据库实现将ListView条目保存到其他Activity的收藏列表
优惠活动
大模型
产品
解决方案
定价
更多

如何通过SQLite数据库实现将ListView条目保存到其他Activity的收藏列表

实现步骤

1. 创建SQLite数据库帮助类

继承SQLiteOpenHelper创建专属的数据库管理类,用于初始化收藏表、管理数据库版本:

public class FavoritesDBHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "QuotesFavorites.db";
    private static final int DATABASE_VERSION = 1;
    // 表名与字段定义
    public static final String TABLE_FAVORITES = "favorites";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_QUOTE_CONTENT = "quote_content";
    public static final String COLUMN_ADD_TIME = "add_time";

    public FavoritesDBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建收藏表SQL语句
        String CREATE_FAVORITES_TABLE = "CREATE TABLE " + TABLE_FAVORITES + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + COLUMN_QUOTE_CONTENT + " TEXT NOT NULL,"
                + COLUMN_ADD_TIME + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP"
                + ")";
        db.execSQL(CREATE_FAVORITES_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 简单版本升级逻辑:删除旧表重建,生产环境可按需做数据迁移
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
        onCreate(db);
    }
}

2. 收藏按钮点击插入数据逻辑

首先在DBHelper中封装收藏插入方法:

// 新增收藏,返回值为插入行的id,返回-1代表插入失败
public long addFavorite(String quoteContent) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COLUMN_QUOTE_CONTENT, quoteContent);
    long result = db.insert(TABLE_FAVORITES, null, values);
    db.close();
    return result;
}

在ListView的Adapter的getView方法中给收藏按钮绑定点击事件,拿到当前条目的语录内容插入数据库:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // 原有视图绑定逻辑保留
    String currentQuote = quoteList.get(position); // 取当前条目对应的语录内容
    Button favoriteBtn = convertView.findViewById(R.id.favorite_btn);
    favoriteBtn.setOnClickListener(v -> {
        FavoritesDBHelper dbHelper = new FavoritesDBHelper(v.getContext());
        long insertRes = dbHelper.addFavorite(currentQuote);
        if (insertRes != -1) {
            Toast.makeText(v.getContext(), "收藏成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(v.getContext(), "收藏失败", Toast.LENGTH_SHORT).show();
        }
    });
    return convertView;
}

3. 收藏页加载展示数据

首先在DBHelper中封装全量收藏查询方法:

public List<String> getAllFavorites() {
    List<String> favoriteList = new ArrayList<>();
    String selectQuery = "SELECT * FROM " + TABLE_FAVORITES + " ORDER BY " + COLUMN_ADD_TIME + " DESC";
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            String quote = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_QUOTE_CONTENT));
            favoriteList.add(quote);
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return favoriteList;
}

在FavoriteActivity中查询数据并绑定到列表,这里放在onResume中执行保证新增收藏后回到页面能自动刷新:

public class FavoriteActivity extends AppCompatActivity {
    private ListView favListView;
    private ArrayAdapter<String> favAdapter;
    private List<String> favList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_favorite);
        favListView = findViewById(R.id.fav_list_view);
        favList = new ArrayList<>();
        // 可替换为你自定义的Adapter实现自定义条目样式
        favAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, favList);
        favListView.setAdapter(favAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        FavoritesDBHelper dbHelper = new FavoritesDBHelper(this);
        List<String> newFavList = dbHelper.getAllFavorites();
        favList.clear();
        favList.addAll(newFavList);
        favAdapter.notifyDataSetChanged();
    }
}
补充注意点
  • 数据库操作属于IO操作,数据量大时建议放到子线程执行,避免阻塞主线程触发ANR
  • 若需要支持去重收藏,插入前先查询数据库中是否存在相同语录内容,已存在则直接提示已收藏即可
  • 若要实现取消收藏功能,新增删除方法,根据条目id调用SQLite的delete方法删除对应数据即可

内容的提问来源于stack exchange,提问作者AYOUB ES SARGHINI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 08:54:04