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

Android Sqlite登录页面:如何获取当前登录用户的ID?

Fixing the "Can't Retrieve Logged-In User ID" Issue in SQLite-Based Android Login

Got it, let's sort out this issue for you! The main problem right now is that your current database check only verifies if the user exists, but doesn't pull their unique ID. Here's a straightforward way to adjust your code to get that ID once login is successful:

Step 1: Modify Your Database Query to Fetch the User ID

Instead of just checking for a matching user count, adjust your database method to return the user's ID when their credentials are valid. Let's assume your users table has columns id, username, and password:

// Inside your SQLiteOpenHelper subclass or database access class
public int getUserIdFromCredentials(String username, String password) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(
        "users", // Target table
        new String[]{"id"}, // Columns to retrieve (just the ID here)
        "username = ? AND password = ?", // Where clause
        new String[]{username, password}, // Values for the where clause
        null, null, null // Group by, having, order by (not needed here)
    );

    int userId = -1; // Default to -1 if no match found
    if (cursor.moveToFirst()) {
        // Get the ID from the cursor
        userId = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
    }

    // Always close cursors and databases to avoid leaks
    cursor.close();
    db.close();
    return userId;
}

Step 2: Update Your Login Button Logic to Use the New Method

In your LoginActivity's button click listener, call this method. If the returned ID isn't -1, login is successful, and you now have the user's ID to work with:

loginButton.setOnClickListener(v -> {
    String inputUsername = usernameEt.getText().toString().trim();
    String inputPassword = passwordEt.getText().toString().trim();

    YourDatabaseHelper dbHelper = new YourDatabaseHelper(this);
    int loggedInUserId = dbHelper.getUserIdFromCredentials(inputUsername, inputPassword);

    if (loggedInUserId != -1) {
        // Success! You have the user ID now
        Toast.makeText(this, "Login successful! User ID: " + loggedInUserId, Toast.LENGTH_SHORT).show();

        // Store the ID in SharedPreferences for easy access across the app
        SharedPreferences prefs = getSharedPreferences("AppSession", MODE_PRIVATE);
        prefs.edit().putInt("current_user_id", loggedInUserId).apply();

        // Navigate to your main screen
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    } else {
        // Invalid credentials
        Toast.makeText(this, "Wrong username or password", Toast.LENGTH_SHORT).show();
    }
});

Step 3: Access the User ID Anywhere in Your App

Once stored in SharedPreferences, you can retrieve the user ID from any Activity/Fragment like this:

SharedPreferences prefs = getSharedPreferences("AppSession", MODE_PRIVATE);
int currentUserId = prefs.getInt("current_user_id", -1);
if (currentUserId != -1) {
    // Use this ID for fetching user-specific data, etc.
    Log.d("USER_SESSION", "Current user ID: " + currentUserId);
}

Key Best Practices to Keep in Mind

  • Never store plain-text passwords: For production apps, always hash passwords with a strong algorithm (like bcrypt or Argon2) before saving them to SQLite. Storing plain text is a huge security risk.
  • Clean up resources: Always close Cursor and SQLiteDatabase instances to prevent memory leaks.
  • Consider Room Persistence Library: If you're open to refactoring, Google's Room is a modern, abstraction layer over SQLite that simplifies database operations and reduces boilerplate code.

内容的提问来源于stack exchange,提问作者Umut Tekin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:17:57