gpt4 book ai didi

java - 如何在 Android Studio 中将数据库中的列显示到 TextView 中?

转载 作者:太空宇宙 更新时间:2023-11-04 10:25:41 25 4
gpt4 key购买 nike

嘿伙计们,我已经尝试了两天了,但我似乎无法让它发挥作用。我已经尝试了每个教程!我是 android studio 的新手,一直在尝试制作一个可以注册和登录的简单应用程序。我能够创建数据库并向数据库插入新行(用户)。[注册用户]。而且我还能够让用户登录。

我现在想做的是从行中检索一列或一列并将其显示在 TextView 中。

例如,一旦我使用用户登录,我想从列中显示他们的信息,例如电话号码、地址等。

当应用程序首次启动时,会有一个注册 Activity 。您可以注册或继续登录 Activity 。一旦您从登录 Activity 登录,就会有一个新 Activity ,我想在其中显示该登录用户的信息。

数据库助手.java

package easy.eightfivehundred.easy;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME="register.db";
public static final String TABLE_NAME="register";
public static final String COL_1="ID";
public static final String COL_2="FirstName";
public static final String COL_3="LastName";
public static final String COL_4="HomeAddress";
public static final String COL_5="Phone";
public static final String COL_6="Email";
public static final String COL_7="Password";

public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, FirstName TEXT, LastName TEXT, HomeAddress TEXT, Phone TEXT, Email TEXT, Password TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}

}

主要 Activity

package easy.eightfivehundred.easy;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
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 MainActivity extends AppCompatActivity {

SQLiteOpenHelper openHelper;
SQLiteDatabase db;
Button Registerbutton, Loginbutton;
EditText Firstnametxt, Lastnametxt, Homeaddresstxt, Phonenumbertxt, Emailtext, Passwordtext;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openHelper = new DatabaseHelper(this);
Registerbutton =(Button)findViewById(R.id.RegisterButton);
Loginbutton = (Button)findViewById(R.id.LogInButton);
Firstnametxt =(EditText)findViewById(R.id.FirstNameText);
Lastnametxt =(EditText)findViewById(R.id.LastNameText);
Homeaddresstxt =(EditText)findViewById(R.id.HomeAddressText);
Phonenumbertxt =(EditText)findViewById(R.id.PhoneText);
Emailtext =(EditText)findViewById(R.id.EmailText);
Passwordtext =(EditText)findViewById(R.id.PasswordText);
Registerbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
db = openHelper.getWritableDatabase();
String first = Firstnametxt.getText().toString();
String last = Lastnametxt.getText().toString();
String address = Homeaddresstxt.getText().toString();
String phone = Phonenumbertxt.getText().toString();
String email = Emailtext.getText().toString();
String password = Passwordtext.getText().toString();

insertData(first, last, address, phone, email, password);
Toast.makeText(getApplicationContext(), "You Registered Successfully!", Toast.LENGTH_LONG).show();
}
});

Loginbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, login.class);
startActivity(intent);
}
});

}

public void insertData(String first, String last, String address, String phone, String email, String password) {
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.COL_2, first);
contentValues.put(DatabaseHelper.COL_3, last);
contentValues.put(DatabaseHelper.COL_4, address);
contentValues.put(DatabaseHelper.COL_5, phone);
contentValues.put(DatabaseHelper.COL_6, email);
contentValues.put(DatabaseHelper.COL_7, password);
long id = db.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
}

}

登录

package easy.eightfivehundred.easy;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
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 {

SQLiteDatabase db;
SQLiteOpenHelper openHelper;
Button Loginbutton;
EditText Emailtext, Passwordtext;
Cursor cursor;

public static final String EXTRA_MESSAGE = " ";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
openHelper = new DatabaseHelper(this);
db = openHelper.getReadableDatabase();
Loginbutton = (Button)findViewById(R.id.loginbutton);
Emailtext = (EditText)findViewById(R.id.emaillogintext);
Passwordtext = (EditText)findViewById(R.id.passwordlogintext);
Loginbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = Emailtext.getText().toString();
String password = Passwordtext.getText().toString();
cursor = db.rawQuery("SELECT * FROM " + DatabaseHelper.TABLE_NAME + " WHERE " + DatabaseHelper.COL_6 + "=? AND " + DatabaseHelper.COL_7 + "=? ", new String[]{email, password});
if(cursor != null){
if(cursor.getCount() > 0){
cursor.moveToNext();
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_LONG).show();

Intent intent = new Intent(login.this, UserHome.class);
intent.putExtra(EXTRA_MESSAGE, email);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG).show();
}
}
}
});

}
}

用户主页

package easy.eightfivehundred.easy;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import static easy.eightfivehundred.easy.DatabaseHelper.TABLE_NAME;

public class UserHome extends AppCompatActivity {

SQLiteDatabase db;
SQLiteOpenHelper openHelper;
Cursor cursor;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_home);

Intent intent = getIntent();
String email = intent.getStringExtra(login.EXTRA_MESSAGE);
}
}

在 userhome.java 文件中我遇到了麻烦。我只想在此页面上显示登录用户的列。

最佳答案

这应该能让你上路:-

第 1 步。

修改布局以包含带有 ID 的 TextView,用于显示提取的数据,例如:-

<TextView
android:id="@+id/firstname"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/lastname"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/homaddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

第 2 步。

添加一个方法(添加到 DatabAseHelper.java,尽管也可以在其他地方,例如 MainActivity.java 中的 InsertData 方法)以获取游标形式的数据。

例如:-

public Cursor getUserInfo(String email) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = COL_6 + "=?"; //<<<< select according to email
String[] whereargs = new String[]{email};
return db.query(
TABLE_NAME,
null,
whereclause,
whereargs,
null,null,null
);
}
  • 以上等价于从寄存器中选择 * WHERE Email = '??????'
    • 哪里????将字符串传递给该方法。

第 3 步。

Userhome.java中声明TextViews的类变量、您的DatabaseHelper实例(不是SQLiteOpenHelper)和Cursor(您已经有了这个)。

例如:-

TextView mFirstName, mLastName, mHomeAddress, mPhone, mEmail, mPassword;
DatabaseHelper mDBHlpr;
Cursor cursor;

第 4 步。

再次在UserHome.java中作为onCreate方法使用:-

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //<<<< USE YOUR LAYOUT


Intent intent = getIntent();
String email = intent.getStringExtra(login.EXTRA_MESSAGE);

//<<<<<<<<<< NEW CODE >>>>>>>>>>
mFirstName = (TextView) this.findViewById(R.id.firstname);
mLastName = (TextView) this.findViewById(R.id.lastname);
mHomeAddress = (TextView) this.findViewById(R.id.homaddress);
mPhone = (TextView) this.findViewById(R.id.phone);
mEmail = (TextView) this.findViewById(R.id.email);
mPassword = (TextView) this.findViewById(R.id.password);

mDBHlpr = new DatabaseHelper(this); //<<<< get Instance of DatbaseHelper
cursor = mDBHlpr.getUserInfo(email); //<<< get the Cursor according to email
if (cursor.moveToFirst()) {
mFirstName.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_2)));
mLastName.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_3)));
mHomeAddress.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_4)));
mPhone.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_5)));
mEmail.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_6)));
mPassword.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_7)));
} else {
// HANDLE NO DATA THAT MATCHES WHERE CLAUSE
mFirstName.setText("Sorry No User found that has email as :- " + email);
}
cursor.close(); //<<<< DONE WITH THE CURSOR SO CLOSE IT
}
  • 返回时光标将定位在第一行之前的位置(位置-1)。要获取数据,您需要移动到一行。
  • move?????? 方法返回 true 或 false。前者如果可以进行移动(因此 moveToFirst,如果没有行将返回 false,如果至少有一行则返回 true)。因此,您可以如何使用 if (cursor.moveToFirst()){.....}
  • 因此,如果有数据(一行或多行,则假定有一个,因为可能不应该有具有相同电子邮件地址的用户),TextView 就会被填充(否则,即,名字 TextView 表示未找到用户(不过不应发生))。
  • 使用get??????Cursor中提取数据(本例中为getString,还有其他方法如getIntgetLong……)。
  • get?????? 方法采用一个整数,即列偏移量(第一列ID 是偏移量0,第二列firstname 是偏移量1 ......)。不过,使用硬编码的偏移量很容易出现问题,因此建议使用 Cursor getColumnIndex,它根据列名返回列偏移量(更灵活)。
  • 请注意如何从DatabaseHelper检索列名称,使用这种方式可以减少输入错误的机会。
    • 您可以考虑更改 DatabaseHelper 中的 onCreate 方法,以便通过使用(已注释掉的替换代码)也使用此单一源作为列名称。

:-

@Override
public void onCreate(SQLiteDatabase db) {

String crt_sql = "CREATE TABLE " + TABLE_NAME + "(" +
// Note AUTOINCREMENT is very likely not needed
// refer to https://sqlite.org/autoinc.html
COL_1 + " INTEGER PRIMARY KEY, " +
COL_2 + " TEXT, " +
COL_3 + " TEXT, " +
COL_4 + " TEXT, " +
COL_5 + " TEXT, " +
COL_6 + " TEXT, " +
COL_7 + " TEXT " +
")";
db.execSQL(crt_sql);
/*
db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"FirstName TEXT, LastName TEXT, HomeAddress TEXT, Phone TEXT, Email TEXT, Password TEXT)");
*/
}
  • 您不妨查看SQLite Autoincrement就排除 AUTOINCRMENT 关键字而言。

  • 您可能还希望查看Cursor对于众多 Cursor 方法(例如 get??????move??????)

测试

通过使用以下代码 fragment 添加一个名字为 Fred、姓氏为 FlitStone 的用户来测试上述内容:-

        mDBHlpr.insertUser("Fred",
"Flintsone",
"1 The Caves, Bedrock",
"01 2345 6789",
email_for_testing,
"fredflintsone"
);

结果:-

enter image description here

关于java - 如何在 Android Studio 中将数据库中的列显示到 TextView 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50557389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com