You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将League ID写入Bowler表以实现ListView筛选功能求助

解决主键ID传递与关联Bowler表的问题

首先看你现在遇到的核心问题:League的ID传递到Main2Activity后没有显示,我们先把这个问题解决,再聊Bowler表关联的事情。

1. 修复ID传递与接收的错误

你在MainActivity里传递的是int类型的leagueId,但在Main2Activity里用了getStringExtra()去接收,这就导致类型不匹配,自然拿不到正确的值!而且你代码里那行final String s = myText.toString();完全是多余的,直接删掉就行。

修改后的Main2Activity代码应该是这样:

public class Main2Activity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.league_id );
        Toolbar toolbar = (Toolbar) findViewById( R.id.toolbar );
        setSupportActionBar( toolbar );

        // 用getIntExtra接收int类型的参数,第二个参数是默认值(如果没拿到就用0)
        int leagueId = getIntent().getIntExtra( "value1", 0 );
        TextView myText = (TextView) findViewById(R.id.tvLeagueId);
        // 把int转成String显示到TextView
        myText.setText(String.valueOf(leagueId));
    }
}

2. 验证ID是否成功传递的小技巧

为了确认ID确实传过来了,可以加个Log打印辅助排查:

// 在Main2Activity的onCreate里添加
Log.d("LeagueID", "传递过来的ID是:" + leagueId);

这样你就能在Logcat里看到是否拿到了正确的ID,方便快速定位问题。

3. 关联Bowler表的实现建议

现在ID能正常传递了,接下来要实现“把League ID写入Bowler表,后续只查询该League关联的Bowler”:

3.1 添加Bowler时存入League ID

当用户在Main2Activity创建Bowler的时候,把刚才拿到的leagueId赋值给Bowler对象的league_id字段,然后插入数据库:

// 示例:创建Bowler对象并插入
int leagueId = getIntent().getIntExtra( "value1", 0 );
Bowler newBowler = new Bowler();
newBowler.setName("张三");
newBowler.setLeagueId(leagueId); // 这里传入传递过来的League ID
// 调用你的数据库操作类插入这条Bowler数据
dbHelper.insertBowler(newBowler);

3.2 查询指定League的Bowler

当需要显示某个League下的所有Bowler时,在你的数据库查询方法里添加条件过滤:

// 示例:查询指定leagueId的所有Bowler
public List<Bowler> getBowlersByLeagueId(int leagueId) {
    List<Bowler> bowlerList = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(Bowler.TABLE_NAME,
            null,
            Bowler.COLUMN_LEAGUE_ID + "=?", // 条件:league_id等于传入的ID
            new String[]{String.valueOf(leagueId)},
            null, null, null);

    if (cursor.moveToFirst()) {
        do {
            Bowler bowler = new Bowler();
            bowler.setId(cursor.getInt(cursor.getColumnIndexOrThrow(Bowler.COLUMN_ID)));
            bowler.setLeagueId(cursor.getInt(cursor.getColumnIndexOrThrow(Bowler.COLUMN_LEAGUE_ID)));
            bowler.setName(cursor.getString(cursor.getColumnIndexOrThrow(Bowler.COLUMN_NAME)));
            bowler.setTimestamp(cursor.getString(cursor.getColumnIndexOrThrow(Bowler.COLUMN_TIMESTAMP)));
            bowlerList.add(bowler);
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return bowlerList;
}

这样就能精准获取指定League下的所有Bowler数据了。

内容的提问来源于stack exchange,提问作者Robert Vogl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:18:36