如何在Android Studio中将数据库列数据显示到TextView中?
Got it, let's break this down step by step. You've already nailed the core registration and database setup, so we just need to tie the login process to fetching user data and displaying it in a new activity. Here's how to make it work:
Step 1: Add a User Query Method to DatabaseHelper
First, let's add a helper method to your DatabaseHelper class to fetch user data by email and password. This keeps your code clean and avoids repeating database logic in the login activity.
Update your databasehelper.java with this method:
// Add this method inside the DatabaseHelper class public Cursor getUserByEmailAndPassword(String email, String password) { SQLiteDatabase db = this.getReadableDatabase(); // Query for the user matching the provided email and password return db.query(TABLE_NAME, null, COL_6 + "=? AND " + COL_7 + "=?", new String[]{email, password}, null, null, null); }
Step 2: Complete the Login Activity Logic
Your login.java is incomplete—let's finish it to handle login validation, fetch user data, and navigate to a profile activity.
Full login.java Code:
package easy.eightfivehundred.easy; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteOpenHelper; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class login extends AppCompatActivity { SQLiteOpenHelper openHelper; SQLiteDatabase db; Button btnLogin; EditText etEmail, etPassword; Cursor cursor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // Make sure you create this layout file openHelper = new DatabaseHelper(this); btnLogin = findViewById(R.id.btn_login); etEmail = findViewById(R.id.et_login_email); etPassword = findViewById(R.id.et_login_password); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email = etEmail.getText().toString().trim(); String password = etPassword.getText().toString().trim(); // Basic input validation if (email.isEmpty() || password.isEmpty()) { Toast.makeText(login.this, "Please fill all fields", Toast.LENGTH_SHORT).show(); return; } db = openHelper.getReadableDatabase(); // Fetch user using our helper method cursor = ((DatabaseHelper) openHelper).getUserByEmailAndPassword(email, password); if (cursor != null && cursor.moveToFirst()) { // Extract user data from the cursor String firstName = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_2)); String lastName = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_3)); String homeAddress = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_4)); String phone = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_5)); String userEmail = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_6)); // Pass data to ProfileActivity via Intent Intent intent = new Intent(login.this, ProfileActivity.class); intent.putExtra("FIRST_NAME", firstName); intent.putExtra("LAST_NAME", lastName); intent.putExtra("HOME_ADDRESS", homeAddress); intent.putExtra("PHONE", phone); intent.putExtra("EMAIL", userEmail); startActivity(intent); finish(); // Close login screen so users can't go back Toast.makeText(login.this, "Login Successful!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(login.this, "Invalid Email or Password", Toast.LENGTH_SHORT).show(); } // Clean up resources to avoid memory leaks if (cursor != null) cursor.close(); if (db != null) db.close(); } }); } }
Create the Login Layout (activity_login.xml)
You'll need a simple layout for the login screen:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" android:gravity="center"> <EditText android:id="@+id/et_login_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Email" android:inputType="textEmailAddress"/> <EditText android:id="@+id/et_login_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Password" android:inputType="textPassword" android:layout_marginTop="16dp"/> <Button android:id="@+id/btn_login" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Login" android:layout_marginTop="24dp"/> </LinearLayout>
Step 3: Create a Profile Activity to Display User Data
Now let's make the activity that shows the user's info after login.
Profile Layout (activity_profile.xml)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" android:gap="12dp"> <TextView android:id="@+id/tv_full_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:textStyle="bold"/> <TextView android:id="@+id/tv_email" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp"/> <TextView android:id="@+id/tv_phone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp"/> <TextView android:id="@+id/tv_address" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp"/> </LinearLayout>
Profile Activity Code (ProfileActivity.java)
package easy.eightfivehundred.easy; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class ProfileActivity extends AppCompatActivity { TextView tvFullName, tvEmail, tvPhone, tvAddress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); tvFullName = findViewById(R.id.tv_full_name); tvEmail = findViewById(R.id.tv_email); tvPhone = findViewById(R.id.tv_phone); tvAddress = findViewById(R.id.tv_address); // Retrieve data from the Intent Bundle extras = getIntent().getExtras(); if (extras != null) { String firstName = extras.getString("FIRST_NAME"); String lastName = extras.getString("LAST_NAME"); String email = extras.getString("EMAIL"); String phone = extras.getString("PHONE"); String address = extras.getString("HOME_ADDRESS"); // Populate TextViews with user data tvFullName.setText("Name: " + firstName + " " + lastName); tvEmail.setText("Email: " + email); tvPhone.setText("Phone: " + phone); tvAddress.setText("Address: " + address); } } }
Step 4: Register the Profile Activity in AndroidManifest.xml
Don't forget to add the new activity to your manifest so Android recognizes it:
<activity android:name=".login"/> <activity android:name=".ProfileActivity"/> <!-- Add this line -->
Quick Tips for Improvement
- Password Security: Never store passwords in plain text! For a production app, use encryption like SHA-256 or Android's
EncryptedSharedPreferences. - Async Database Calls: Database operations can block the main thread—use
CoroutinesorAsyncTaskto run them in the background for smoother performance. - Error Handling: Add more checks for null values or database errors to make your app more robust.
内容的提问来源于stack exchange,提问作者Luis Garcia

