Android Studio中如何选取SQLite指定行数据并传递至其他Activity
修复你的SQLite查询并实现Activity间数据传递
首先得说,你当前的senderMobile方法有个关键问题:cursor.getColumnIndex("mobile")返回的是列在游标中的索引位置,不是你要的实际手机号值!而且你没有将游标移动到查询结果的行上,直接操作会导致空指针或者错误的返回值。我来一步步帮你修正:
第一步:修正DatabaseHelper中的查询方法
修改方法来获取实际的手机号数据,同时处理查询不到结果的情况,还要记得关闭游标和数据库避免资源泄漏:
public String getSenderMobile(String activeuser){ SQLiteDatabase db = this.getReadableDatabase(); String mobile = null; // 执行查询 Cursor cursor = db.rawQuery("select mobile from user where email=?", new String[]{activeuser}); // 检查游标是否有数据,并移动到第一行 if (cursor != null && cursor.moveToFirst()) { // 根据列名获取对应的值(如果你的mobile是整数类型,就用cursor.getInt()) int mobileColumnIndex = cursor.getColumnIndex("mobile"); if (mobileColumnIndex != -1) { // 确保列存在 mobile = cursor.getString(mobileColumnIndex); } } // 关闭游标和数据库 if (cursor != null) { cursor.close(); } db.close(); return mobile; }
第二步:将数据传递到其他Activity
在你获取到手机号的当前Activity中,使用Intent的putExtra方法传递数据:
// 假设你已经拿到了当前用户的邮箱activeUser String activeUser = "example@mail.com"; // 替换成你的实际用户邮箱 DatabaseHelper dbHelper = new DatabaseHelper(this); String userMobile = dbHelper.getSenderMobile(activeUser); // 启动目标Activity并传递手机号 Intent intent = new Intent(this, YourTargetActivity.class); intent.putExtra("KEY_USER_MOBILE", userMobile); // KEY_USER_MOBILE是自定义的键,后面接收要用 startActivity(intent);
第三步:在目标Activity中接收数据
在目标Activity的onCreate方法里,通过getIntent()获取传递过来的数据:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_target); // 获取传递的手机号 String receivedMobile = getIntent().getStringExtra("KEY_USER_MOBILE"); // 这里可以使用数据,比如显示到TextView TextView mobileTextView = findViewById(R.id.tv_mobile); if (receivedMobile != null) { mobileTextView.setText("用户手机号:" + receivedMobile); } else { mobileTextView.setText("未查询到手机号"); } }
额外注意事项
- 如果你的
mobile字段是整数类型(比如存的是数字),把代码里的getString换成getInt,传递和接收时对应使用putExtra("KEY", intValue)和getIntExtra("KEY", 默认值)。 - 一定要确保查询的
email参数是正确的,否则会返回null。 - 操作数据库时,尽量避免在主线程做耗时查询,如果数据量大,建议用AsyncTask或者Coroutines处理。
内容的提问来源于stack exchange,提问作者Pranit Darekar
相关产品推荐
相关产品推荐

