简体   繁体   English

Android Studio 数据库连接

[英]Android Studio Database Connection

This is a model paper I got.这是我得到的模型纸。 I need to make sure that, my codes are 100% correct.我需要确保,我的代码是 100% 正确的。 a.一种。 Create an Activity called Home and design the given layout Create an Activity called ProfileManagement and design the given layout.创建一个名为 Home 的活动并设计给定的布局 创建一个名为 ProfileManagement 的活动并设计给定的布局。 Create an Activity called EditProfile and design the given layout.创建一个名为 EditProfile 的活动并设计给定的布局。 (I did all these layout parts) (我做了所有这些布局部分)

Final class called 'UserProfile'.名为“UserProfile”的最终类。 Make the default constructor private.将默认构造函数设为私有。 Create an inner class called 'Users' by implementing 'BaseColumn' interface.通过实现“BaseColumn”接口创建一个名为“Users”的内部类。 Inside the inner class, define the columns you need along with the table.在内部类中,定义您需要的列以及表。 b.Implement a method named addInfo() to store user details details .实现名为 addInfo() 的方法来存储用户详细信息 details 。 c. C。 Implement a method named updateInfor() to modify stored user details based on the user ID.实现名为 updateInfor() 的方法以根据用户 ID 修改存储的用户详细信息。 Method must return a Boolean value based on the success or failure.方法必须根据成功或失败返回布尔值。 d. d. Implement a method named readAllInfor() to retrieve all the user details stored in the database table.实现一个名为 readAllInfor() 的方法来检索存储在数据库表中的所有用户详细信息。 e. e. Overload the method readAllInfor() to retrieve the user details based on the primary key.重载方法 readAllInfor() 以根据主键检索用户详细信息。 f. F。 Implement a method named deleteInfo() to delete a specific user实现一个名为 deleteInfo() 的方法来删除特定用户

import android.provider.BaseColumns;

public final class UserProfile {

    private UserProfile() { }

    public class User implements BaseColumns {
        public static final String TABLE_NAME = "UserInfo";
        public static final String COLUMN_USERNAME = "username";
        public static final String COLUMN_DOB = "dob";
        public static final String COLUMN_PASSWORD = "password";
        public static final String COLUMN_GENDER = "gender";
    }
}

Create another class called DBHelper inside the database folder by extending the class SQLiteOpenHelper as its superclass.通过扩展类 SQLiteOpenHelper 作为其超类,在数据库文件夹中创建另一个名为 DBHelper 的类。 Implement the relevant methods and constructors.实现相关的方法和构造函数。

package com.bla.androidsqlitebasics.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import static com.bla.androidsqlitebasics.database.UserProfile.User.*;

public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "User.db";
    public static final int DATABASE_VERSION = 3;

    public static final String CREATE_TABLE_QUERY = "CREATE TABLE IF NOT EXISTS "+ TABLE_NAME +"( "+
            _ID + " INTEGER PRIMARY KEY, " +
            COLUMN_USERNAME +" TEXT, "+
            COLUMN_PASSWORD +" TEXT, "+
            COLUMN_DOB +" DATE, " +
            COLUMN_GENDER + ")";

    public static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS "+ TABLE_NAME;

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_QUERY);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(SQL_DELETE_ENTRIES);
        onCreate(db);
    }

    //Supposed if question asked to implement add, update, read methods in this class
    //to check user when login
    public long checkUser(String username, String password) {
        SQLiteDatabase db = getReadableDatabase();

        //check if entered username and password exists in the users table
        String[] selectionArgs = {username, password};
        String query = "SELECT * FROM " + TABLE_NAME + " WHERE "+ COLUMN_USERNAME + " = ? AND " +
                COLUMN_PASSWORD + " = ?";

        Cursor cursor = db.rawQuery(query, selectionArgs);

        //if username and password match and row count is greater than 1 get that userId or else assign -1 to @useerId
        long userId = -1;
        if (cursor.moveToFirst()) {
            userId = (cursor.getCount() >= 1) ? cursor.getLong(0) : -1;
        }
        //if the user count greater than(shoul be equal to if properly check) 1 user exists and return true
        //return cursor.getCount() >= 1;

        //to login user from primary key
        return userId;
    }

    //register/add user to db table
    public long addInfo(String username, String password) {
        SQLiteDatabase db = getWritableDatabase();

        ContentValues cv = new ContentValues();
        cv.put(COLUMN_USERNAME, username);
        cv.put(COLUMN_PASSWORD, password);

        return db.insert(TABLE_NAME, null, cv);
    }

    public boolean updateInfo(long userId, String username, String password, String dob, String gender) {
        SQLiteDatabase db = getWritableDatabase();

        //to check for the user to update
        String[] selectionArgs = {userId+""};
        String whereClause = _ID + " = ?";

        ContentValues cv = new ContentValues();
        cv.put(COLUMN_USERNAME, username);
        cv.put(COLUMN_PASSWORD, password);
        cv.put(COLUMN_DOB, dob);
        cv.put(COLUMN_GENDER, gender);

        return db.update(TABLE_NAME, cv, whereClause, selectionArgs) > 0;
    }

    public Cursor readAllInfor() {
        SQLiteDatabase db = getReadableDatabase();

        String[] projection = {
                _ID,
                COLUMN_USERNAME,
                COLUMN_PASSWORD,
                COLUMN_DOB,
                COLUMN_GENDER
        };

        Cursor cursor = db.query(
                TABLE_NAME,
                projection,
                null,
                null,
                null,
                null,
                null);

        //if the user count greater than(shoul be equal to if properly check) 1 user exists and return true
        return cursor;
    }

    public Cursor readAllInfor(long userId) {
        SQLiteDatabase db = getReadableDatabase();

        //retrieve the user using primary key
        String[] selectionArgs = {userId+""};
        String query = "SELECT * FROM " + TABLE_NAME + " WHERE "+ _ID + " = ? ";

        Cursor cursor = db.rawQuery(query, selectionArgs);

        //if the user count greater than(shoul be equal to if properly check) 1 user exists and return true
        return cursor;
    }

    public boolean deleteInfo(long userId) {
        SQLiteDatabase db = getWritableDatabase();

        //delete user from db table
        String[] selectionArgs = {userId+""};
        String whereClause = _ID + " = ?";

        return db.delete(TABLE_NAME, whereClause, selectionArgs) > 0;
    }
}

Create intent objects to start a.创建意图对象以启动一个。 ProfileManagement activity from 'Register' button b.来自“注册”按钮的 ProfileManagement 活动 b. EditProfile activity from 'Update Profile' button a.来自“更新配置文件”按钮的 EditProfile 活动Call addInfor() method implemented in DbHandler class from the onClick event of Register button.从注册按钮的 onClick 事件调用在 DbHandler 类中实现的 addInfor() 方法。 Display a Toast Message indicating success or failure显示指示成功或失败的 Toast 消息

Home Activity家庭活动

package com.bla.androidsqlitebasics.activity;

import android.content.Intent;
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;

import com.bla.androidsqlitebasics.database.DBHelper;
import com.live.sinhalacoder.androidsqlitebasics.R;

public class HomeActivity extends AppCompatActivity {

    EditText usernameEt, passwordEt;
    Button loginBt, registerBt;

    //to get access to database table
    DBHelper mHelper;

    //newly added user primary key
    long userId = -1;

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

        usernameEt = findViewById(R.id.idUsernameEt);
        passwordEt = findViewById(R.id.idPasswordEt);

        loginBt = findViewById(R.id.idLoginBt);
        registerBt = findViewById(R.id.idRegisterBt);

        //initialize db helper when app create
        mHelper = new DBHelper(this);

        //if user clicked login button
        loginBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //login existing user
                login();
            }
        });

        //if user clicked register button
        registerBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //add new user to the database
                registerUser();
            }
        });
    }

    private void login() {
        String username = usernameEt.getText().toString();
        String password = passwordEt.getText().toString();

        //if username and pass does not match -1 will return from checkUser function and if not -1 logged in
        userId = mHelper.checkUser(username, password);
        if (userId != -1) {
            Intent intent = new Intent(HomeActivity.this, ProfileManagementActivity.class);
            intent.putExtra("userId", userId);
            startActivity(intent);
        } else {
            Toast.makeText(this, "Err.. Try again!", Toast.LENGTH_SHORT).show();
        }
    }

    public void registerUser() {
        String username = usernameEt.getText().toString();
        String password = passwordEt.getText().toString();

        userId = mHelper.addInfo(username, password);
        if (userId == -1) {
            Toast.makeText(this, "Err.. Try again!", Toast.LENGTH_SHORT).show();
        } else {
            //Toast.makeText(this, "Successfully registed!", Toast.LENGTH_SHORT).show();
            login();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHelper.close();
    }
}

EditProfile Activty编辑档案活动

a.一种。 Call readAllInfor() method implemented in DbHandler class from the onClick event of the Search button to retrieve profile of a specific user.从 Search 按钮的 onClick 事件调用在 DbHandler 类中实现的 readAllInfor() 方法以检索特定用户的个人资料。 b.Call updateInfor() method implemented in DbHandler class from the onClick event of the Edit button to update user details c.从 Edit 按钮的 onClick 事件调用 DbHandler 类中实现的 updateInfor() 方法来更新用户详细信息 c. Call deleteinfor() method implemented in DbHandler class from the onClick event of the Delete button to delete a user从Delete按钮的onClick事件调用DbHandler类中实现的deleteinfor()方法删除一个用户

package com.bla.androidsqlitebasics.activity;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.bla.androidsqlitebasics.database.DBHelper;
import com.live.sinhalacoder.androidsqlitebasics.R;

public class EditProfileActivity extends AppCompatActivity {

    EditText usernameEt, passwordEt, dobEt;
    RadioGroup genderRadio;
    Button editBt, searchBt, deleteBt;

    //to get access to database table
    DBHelper mHelper;

    long userId;

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

        usernameEt = findViewById(R.id.idUsernameEt);
        passwordEt = findViewById(R.id.idPasswordEt);
        dobEt = findViewById(R.id.idBirthdayEt);

        genderRadio = findViewById(R.id.radioGroup);

        editBt = findViewById(R.id.idEditBt);
        searchBt = findViewById(R.id.idSearchBt);
        deleteBt = findViewById(R.id.idDeleteBt);

        //initialize db helper when app create
        mHelper = new DBHelper(this);

        //TODO: get userId that is coming from the home activity to search using user Id(not sure this way or using search username)
        //If press update or delete without searching user id coming from the home activity will be deleted
        Intent intent = getIntent();
        if (intent != null) {
            userId = intent.getLongExtra("userId", -1);
        }

        //if user clicked edit button
        editBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String uname = usernameEt.getText().toString();
                String pass = passwordEt.getText().toString();
                String dob = dobEt.getText().toString();
                String gender = "";
                if (genderRadio.getCheckedRadioButtonId() == R.id.idMaleRadio) {
                    gender = "Male";
                } else if (genderRadio.getCheckedRadioButtonId() == R.id.idFemaleRadio) {
                    gender = "Female";
                }

                //edit logged in user
                if (mHelper.updateInfo(userId, uname, pass, dob, gender)) {
                    Toast.makeText(EditProfileActivity.this, "Updated!", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(EditProfileActivity.this, "Cannot update!", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //if user clicked search button
        searchBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //get typed username to search
                String username = usernameEt.getText().toString();

                //get current user values to textFields from readInfo
                Cursor cursor = mHelper.readAllInfor();

                //TODO: I think this way is not the perfect since, we can directly search using the query
                while (cursor.moveToNext()) {
                    //if typed username equals with table value
                    if (username.equals(cursor.getString(1))) {
                        //get the user id to update and delete
                        userId = cursor.getLong(0);
                        //if there is any matching username with db user table get those values and place into textfields
                        passwordEt.setText(cursor.getString(2));
                        dobEt.setText(cursor.getString(3));

                        if (cursor.getString(4) != null) {
                            if (cursor.getString(4).equals("Male")) {
                                genderRadio.check(R.id.idMaleRadio);
                            } else if (cursor.getString(4).equals("Female"))
                                genderRadio.check(R.id.idFemaleRadio);
                        }
                    }
                }
                cursor.close();

                //dumb trick to display if user not exists
                if (passwordEt.getText().toString().equals("")) {
                    //if searched user not exists
                    Toast.makeText(EditProfileActivity.this, "No user found!", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //if user clicked delete button
        deleteBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //delete user from table and if deleted count is greater than 0 display delete message
                if (mHelper.deleteInfo(userId)) {
                    Toast.makeText(EditProfileActivity.this, "Deleted!", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(EditProfileActivity.this, "User not in the table!", Toast.LENGTH_SHORT).show();
                }

                //clear out editText after deleted
                usernameEt.setText("");
                passwordEt.setText("");
                dobEt.setText("");
                genderRadio.clearCheck();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHelper.close();
    }
}

Profile Management Activity配置文件管理活动

package com.bla.androidsqlitebasics.activity;

import android.content.Intent;
import android.database.Cursor;
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.RadioGroup;
import android.widget.Toast;

import com.bla.androidsqlitebasics.database.DBHelper;
import com.live.sinhalacoder.androidsqlitebasics.R;

public class ProfileManagementActivity extends AppCompatActivity {

    EditText usernameEt, passwordEt, dobEt;
    RadioGroup genderRadio;
    Button updateProfileBt;

    //to get access to database table
    DBHelper mHelper;

    long userId;

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

        usernameEt = findViewById(R.id.idUsernameEt);
        passwordEt = findViewById(R.id.idPasswordEt);
        dobEt = findViewById(R.id.idBirthdayEt);

        genderRadio = findViewById(R.id.radioGroup);

        updateProfileBt = findViewById(R.id.idUpdateBt);

        //initialize db helper when app create
        mHelper = new DBHelper(this);

        //get userId that is coming from the home activity
        Intent intent = getIntent();
        if (intent != null) {
            userId = intent.getLongExtra("userId", -1);
        }

        //get logged in or registered user data from table and bind to editTexts
        Cursor cursor = mHelper.readAllInfor(userId);
        if (cursor.moveToFirst()) {
            usernameEt.setText(cursor.getString(1));
            passwordEt.setText(cursor.getString(2));
            dobEt.setText(cursor.getString(3));
            if (cursor.getString(4) != null) {
                if (cursor.getString(4).equals("Male")) {
                    genderRadio.check(R.id.idMaleRadio);
                } else {
                    genderRadio.check(R.id.idFemaleRadio);
                }
            }
        }
        //if user clicked edit button
        updateProfileBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //open update profile
                Intent intent = new Intent(ProfileManagementActivity.this, EditProfileActivity.class);
                intent.putExtra("userId", userId);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHelper.close();
    }
}

These are my layouts files.这些是我的布局文件。 ActivityHOme活动首页

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginHorizontal="@dimen/layout_margin_horizontal"
    tools:context="com.bla.androidsqlitebasics.activity.HomeActivity">

    <TextView
        android:id="@+id/usernameLabelTv"
        android:layout_width="@dimen/label_width"
        android:layout_height="@dimen/label_height"
        android:layout_marginTop="@dimen/username_label_margin_top"
        android:text="@string/username_tv"
        android:textSize="@dimen/labels_size"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/idUsernameEt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/username_et_margin_start"
        android:layout_marginTop="@dimen/username_et_margin_top"
        android:ems="10"
        android:hint="@string/username_tv"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.384"
        app:layout_constraintStart_toEndOf="@id/usernameLabelTv"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/passwordLabelTv"
        android:layout_width="@dimen/label_width"
        android:layout_height="@dimen/label_height"
        android:layout_marginTop="@dimen/password_label_margin_top"
        android:text="@string/password_label_tv"
        android:textSize="@dimen/labels_size"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/usernameLabelTv" />

    <EditText
        android:id="@+id/idPasswordEt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/username_et_margin_start"
        android:layout_marginTop="@dimen/password_et_margin_top"
        android:ems="10"
        android:hint="@string/password_label_tv"
        android:inputType="textPassword"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.384"
        app:layout_constraintStart_toEndOf="@id/passwordLabelTv"
        app:layout_constraintTop_toBottomOf="@id/idUsernameEt" />

    <Button
        android:id="@+id/idLoginBt"
        android:layout_width="@dimen/bt_width"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/log_bt_margin_top"
        android:text="@string/login_bt_label"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/passwordLabelTv"
        app:layout_constraintVertical_bias="0.023" />

    <Button
        android:id="@+id/idRegisterBt"
        android:layout_width="@dimen/bt_width"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/username_et_margin_start"
        android:layout_marginTop="@dimen/reg_bt_margin_top"
        android:text="@string/register_bt_label"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.395"
        app:layout_constraintStart_toEndOf="@id/idLoginBt"
        app:layout_constraintTop_toBottomOf="@id/idPasswordEt"
        app:layout_constraintVertical_bias="0.028" />
    </android.support.constraint.ConstraintLayout>

Your code seems to be working fine.您的代码似乎工作正常。 But I think there might be an error in your layouts.但我认为您的布局可能存在错误。 please make sure your layouts are correct.请确保您的布局正确。

请检查您的 Intent 对象和布局。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM