如何在Android Studio中将数据库中的列显示为文本视图?

时间:2018-05-27 23:22:28

标签: java android database android-sqlite

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

我现在要做的是从行中检索列或列并在文本视图中显示它。

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

首次启动应用时,会有注册活动。您可以注册或继续登录活动。从登录活动登录后,有一个新活动,我想显示登录用户的信息。

databasehelper.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);
    }

}

mainactivity

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();
                    }
                }
            }
        });

    }
}

USERHOME

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 个答案:

答案 0 :(得分:0)

这应该可以帮助你: -

第1步。

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

<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方法),以将数据作为光标获取。

e.g。 : -

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
            );
}
  • 以上等同于 SELECT * FROM register WHERE Email = '??????'
    • 其中??????将字符串传递给方法。

第3步。

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

e.g。 : -

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?????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)");
            */
}
  • 您可能希望在regad中查看SQLite Autoincrement以排除AUTOINCREMENT关键字。

  • 您可能还希望看一下Cursor的众多光标方法(例如get????move?????

测试

上面的测试是通过添加一个用户的名字是Fred,姓氏FlitStone ...使用这段代码: -

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

导致: -

enter image description here