简体   繁体   English

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

[英]How can I display a column from my database into a text view in Android Studio?

Hey guys I have been trying this for 2 days now and I cant seem to get it to work. 嗨,我已经尝试了2天了,我似乎无法正常工作。 I have tried every tutorial! 我已经尝试了所有教程! I am new to android studio and have been trying to make a simple app where I can register and login. 我是android studio的新手,一直在尝试制作一个简单的应用程序,以便我可以注册和登录。 I was able to create the database and insert a new row(user) to the database.[Register user]. 我能够创建数据库并将新行(用户)插入数据库。[注册用户]。 And also I was able to log the user in. 而且我也能够登录用户。

What I am trying to do now, is retrieve a column or column from the row and display it in a text view. 我现在想做的是从行中检索一列或一列,并在文本视图中显示它。

For example, once I login with a user, I want to display their information from the columns, such as phone number, address, etc. 例如,一旦我与用户登录,我想从列中显示他们的信息,例如电话号码,地址等。

When the app is first launched, there is a registration activity. 首次启动该应用程序时,将进行注册活动。 you can either register or proceed to the login activity. 您可以注册或继续登录活动。 Once you are logged in from the login activity, there is a new activity where I want to display the information of that logged in user. 从登录活动登录后,将有一个新的活动,我要在其中显示该登录用户的信息。

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

}

login 登录

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

In the userhome.java file is where I'm having trouble at. 我在userhome.java文件中遇到了麻烦。 I simply want to display the columns from the logged in user on this page. 我只想在此页面上显示已登录用户的列。

This should get you on your way:- 这应该可以帮助您:-

Step 1. 第1步。

Amend the layout to include the TextViews with id's that will be used to show the extracted data eg :- 修改布局以包括带有ID的 TextView 这些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" />

Step 2. 第2步。

Add a method (added to DatabAseHelper.java although could be elsewhere like your InsertData method in MainActivity.java ) to get the data as a Cursor. 添加一个方法(添加到DatabAseHelper.java中,尽管可能在其他地方,例如MainActivity.java中InsertData方法),以将数据作为Cursor获取。

eg :- 例如:-

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
            );
}
  • The above will equate to SELECT * FROM register WHERE Email = '??????' 上面的内容等同于SELECT * FROM register WHERE Email = '??????'
    • where ?????? 哪里?????? will the string as passed to the method. 将字符串传递给方法。

Step 3. 第三步

In Userhome.java declare the class variables for the TextViews , an instance of YOUR DatabaseHelper (not SQLiteOpenHelper) and the Cursor (you already have this). Userhome.java中,声明TextViews的类变量,YOUR DatabaseHelper (不是SQLiteOpenHelper)和Cursor (您已经拥有)的实例

eg :- 例如:-

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

Step 4. 第四步。

Again in UserHome.java as the onCreate method use :- 再次在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
}
  • A Cursor when returned will be positioned at a position before the first row (position -1). 游标返回时将位于第一行之前的位置(位置-1)。 To get to the data you need to move to a row. 要获取数据,您需要移至一行。
  • The move????? move????? methods return true or false. 方法返回true或false。 The former if the move could be made (so moveToFirst , if there are no rows will return false, or true if there is at least one row). 前者(如果可以进行移动)(所以moveToFirst ,如果没有行将返回false,或者如果有至少一行则返回true)。 Hence how you can use if (cursor.moveToFirst()){.....} . 因此,如何使用if (cursor.moveToFirst()){.....}
  • So if there is data (a row or more, one is assumed as there should probably not be users with the same email) the TextView's are populated (otherwise ie else, the firstname TextView indicates user not found (shouldn't happen though)). 因此,如果有数据(行或更多,假设有一个,因为可能不应该有使用同一封电子邮件的用户),将填充TextView(否则,即,TextView的名字表示未找到用户(虽然应该不会发生)) 。
  • Data is extracted from the Cursor using get????? 使用get?????Cursor中提取数据 ( getString in this case, there are other methods such as getInt , getLong ......). (在这种情况下, getString还有其他方法,例如getIntgetLong ......)。
  • The get???? get???? methods take an integer, the column offset (first column ID is offset 0 , the 2nd firstname is offset 1 ......). 方法采用整数,即列偏移量 (第一列ID为偏移量0 ,第二个名字为偏移量1 ......)。 However, using hard coded offsets can easily result in issues, so it's recommended to use the Cursor getColumnIndex , which returns the column offset according to the column name (more flexible). 但是,使用硬编码的偏移量很容易导致问题,因此建议使用Cursor getColumnIndex ,该方法根据列名返回列偏移量(更灵活)。
  • Note how the column names are retrieved from the DatabaseHelper , using this way reduces the chance for typing errors. 注意如何从DatabaseHelper中检索列名,使用这种方法减少了键入错误的机会。
    • You could consider changing your onCreate method in the DatabaseHelper to also utilise this single source for column names by using (replaced code commented out). 您可以考虑在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)");
            */
}
  • You may wish to have a look at SQLite Autoincrement in regads to the exclusion of the AUTOINCREMENT keyword. 您可能希望看看Regite中的SQLite Autoincrement,以排除AUTOINCREMENT关键字。

  • You may also wish to have a look at Cursor for the numerous Cursor methods (eg get???? and move????? ) 您可能还希望了解一下Cursor的众多Cursor方法(例如get????move????? )。

Testing 测试中

the above was tested by adding a user who's first name was Fred, lastname FlitStone ... using this snippet of code :- 上面的代码通过添加一个姓弗雷德,姓氏FlitStone的用户进行了测试...使用以下代码段:-

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

resulting in :- 导致 :-

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 android studio 中使用 recyclerview 显示我的数据库? - How do i display my database using recyclerview in android studio? 将数据库中的数据显示到文本视图(Android) - Display data from database into text view (Android) 如何在 function 中使用 textview Android Studio 在 Z93F725A074233FEC889ZDF48 中显示文本 - How can I display text in a function with textview Android Studio in java 如何在 android 工作室中将 boolean 解析为我的 SQL 数据库? - How can I parse a boolean to my SQL database in android studio? 如何每天在我的android应用中显示文本 - How can I display a text perday in my android app 我在Android Studio中使用Glide进行图像显示,但是如何在我的ListView中实现Glide? - i use Glide for my image display in android studio but how can i implement Glide to my listview? 如何显示数据库中的更新值-Android - How can i display the updated values from the database-Android 如何在列表视图中显示项目的文本Android Studio - How to display text for an item in a list view Android Studio 如何使用JSON和PHP从数据库显示数据到android app文本视图? - How to display data from database to android app text view using JSON and PHP? 如何在android studio中从mysql数据库检索和显示用户详细信息? - How do I retrieve and display user details from mysql database in android studio?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM