Подключение к базе данных Android Studio - PullRequest
0 голосов
/ 14 октября 2018

Это модель бумаги, которую я получил.Я должен убедиться, что мои коды на 100% верны.а.Создайте Activity под названием Home и спроектируйте данный макет. Создайте Activity под названием ProfileManagement и спроектируйте данный макет.Создайте Activity под названием EditProfile и спроектируйте данный макет.(Я сделал все эти части макета)

Финальный класс под названием UserProfile.Сделайте конструктор по умолчанию закрытым.Создайте внутренний класс с именем «Users», реализовав интерфейс «BaseColumn».Внутри внутреннего класса определите нужные столбцы вместе с таблицей.б.Реализуйте метод с именем addInfo () для хранения сведений о пользователе.с.Реализуйте метод с именем updateInfor () для изменения сохраненных пользовательских данных на основе идентификатора пользователя.Метод должен возвращать логическое значение, основанное на успехе или неудаче.д.Реализуйте метод с именем readAllInfor () для извлечения всех пользовательских данных, хранящихся в таблице базы данных.е.Перегрузите метод readAllInfor (), чтобы получить сведения о пользователе на основе первичного ключа.е.Реализуйте метод с именем 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";
    }
}

Создайте еще один класс с именем DBHelper в папке базы данных, расширив класс SQLiteOpenHelper в качестве его суперкласса.Реализуйте соответствующие методы и конструкторы.

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

Создайте объекты намерений для запуска a.Управление профилями с помощью кнопки «Зарегистрироваться» b.Действие EditProfile с помощью кнопки «Обновить профиль» a.Вызовите метод addInfor (), реализованный в классе DbHandler, из события onClick кнопки Register.Отображение сообщения о тосте, указывающего на успех или неудачу

Домашняя активность

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.Вызовите метод readAllInfor (), реализованный в классе DbHandler, из события onClick кнопки «Поиск», чтобы получить профиль определенного пользователя.б.Вызвать метод updateInfor (), реализованный в классе DbHandler, из события onClick кнопки «Изменить» для обновления сведений о пользователе c.Вызовите метод deleteinfor (), реализованный в классе DbHandler, из события onClick кнопки Delete, чтобы удалить пользователя

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

Активность управления профилем

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

Этомои файлы макетов.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>

Ответы [ 2 ]

0 голосов
/ 14 октября 2018

Пожалуйста, проверьте ваши объекты Intent и макеты.

0 голосов
/ 14 октября 2018

Ваш код работает нормально.Но я думаю, что в ваших макетах может быть ошибка.пожалуйста, убедитесь, что ваши макеты верны.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...