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

Android SQLite用户ID关联及addReading方法调用技术咨询

Solution for Android Database Association & Data Storage Issues

Hey there, let's break down solutions for your two core technical problems with clear code examples tailored to your existing setup:


1. Get Logged-in User's user_id for reading_user_reference

To link readings to the correct user, you first need to retrieve the user_id after successful login, then make it accessible across activities. Here's how to implement this:

Step 1: Add a User ID Fetch Method in DatabaseHelper

Add this method inside your DatabaseHelper class to get the user ID using their login email (since login typically relies on email/password verification):

/**
 * Fetch user ID by email after successful login
 * @param email User's login email
 * @return user_id if found, -1 if no match
 */
public int getUserIdByEmail(String email) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_USER,
            new String[]{COLUMN_USER_ID},
            COLUMN_USER_EMAIL + " = ?",
            new String[]{email},
            null, null, null);
    
    int userId = -1;
    if (cursor != null && cursor.moveToFirst()) {
        userId = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_USER_ID));
        cursor.close();
    }
    db.close();
    return userId;
}

Step 2: Store User ID Globally After Login

Once your login logic confirms the user's credentials are valid, call the above method to get the user_id, then save it to SharedPreferences so it's accessible in any activity:

// Inside your LoginActivity after successful authentication
String userEmail = "user@example.com"; // Replace with actual input email
DatabaseHelper dbHelper = new DatabaseHelper(this);
int userId = dbHelper.getUserIdByEmail(userEmail);

// Save userId to SharedPreferences for global access
SharedPreferences prefs = getSharedPreferences("AppPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("CURRENT_USER_ID", userId);
editor.apply();

2. Call addReading from Calories Activity

In your CaloriesActivity, retrieve the stored user ID, collect input data, then call addReading with default values (set to 0) for unused fields as requested:

Step 1: Complete the Calories Activity Logic

Here's how to integrate data storage into your existing CaloriesActivity code:

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class CaloriesActivity extends AppCompatActivity {

    private EditText etAge, etHeight, etWeight, etCalories;
    private Button btnSave;
    private DatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calories); // Replace with your actual layout ID

        // Initialize views
        etAge = findViewById(R.id.et_age);
        etHeight = findViewById(R.id.et_height);
        etWeight = findViewById(R.id.et_weight);
        etCalories = findViewById(R.id.et_calories);
        btnSave = findViewById(R.id.btn_save);
        dbHelper = new DatabaseHelper(this);

        // Set click listener for save button
        btnSave.setOnClickListener(v -> saveReadingData());
    }

    private void saveReadingData() {
        // Retrieve current user ID from SharedPreferences
        SharedPreferences prefs = getSharedPreferences("AppPrefs", MODE_PRIVATE);
        int currentUserId = prefs.getInt("CURRENT_USER_ID", -1);

        if (currentUserId == -1) {
            Toast.makeText(this, "Please log in first!", Toast.LENGTH_SHORT).show();
            return;
        }

        // Collect and validate input data
        String ageStr = etAge.getText().toString().trim();
        String heightStr = etHeight.getText().toString().trim();
        String weightStr = etWeight.getText().toString().trim();
        String caloriesStr = etCalories.getText().toString().trim();

        if (TextUtils.isEmpty(ageStr) || TextUtils.isEmpty(heightStr) || TextUtils.isEmpty(weightStr) || TextUtils.isEmpty(caloriesStr)) {
            Toast.makeText(this, "Fill all required fields!", Toast.LENGTH_SHORT).show();
            return;
        }

        // Parse inputs to correct data types
        int age = Integer.parseInt(ageStr);
        int height = Integer.parseInt(heightStr);
        int weight = Integer.parseInt(weightStr);
        double calories = Double.parseDouble(caloriesStr);

        // Use current system timestamp for datetime
        long currentDatetime = System.currentTimeMillis();

        // Call addReading with default 0 values for unused fields
        long result = dbHelper.addReading(
                currentUserId,
                currentDatetime,
                age,
                weight,
                height,
                calories,
                0.0, // Default BMI value
                0.0, // Default BMR value
                0.0, // Default BF value
                0.0  // Default FFMI value
        );

        // Show feedback to user
        if (result != -1) {
            Toast.makeText(this, "Data saved successfully!", Toast.LENGTH_SHORT).show();
            // Clear input fields if needed
            etAge.setText("");
            etHeight.setText("");
            etWeight.setText("");
            etCalories.setText("");
        } else {
            Toast.makeText(this, "Failed to save data!", Toast.LENGTH_SHORT).show();
        }
    }

    // Your existing menu methods (example included for logout)
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.your_menu_layout, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_logout) {
            // Clear stored user ID on logout
            SharedPreferences prefs = getSharedPreferences("AppPrefs", MODE_PRIVATE);
            prefs.edit().remove("CURRENT_USER_ID").apply();
            startActivity(new Intent(this, LoginActivity.class));
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Quick Notes:

  • Ensure your CaloriesActivity layout has matching IDs for the EditText and Button views used in the code.
  • The addReading method uses a formatted datetime string; passing System.currentTimeMillis() ensures a valid timestamp for formatting.
  • Always clear the stored user ID from SharedPreferences when the user logs out to prevent unauthorized data access.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:35:52