如何写注册&在Android Studio中使用SQLite登录系统?

时间:2015-09-24 19:22:45

标签: java android sqlite android-studio

我编写了一个简单的SQLite R& L系统。但是在我运行之后我遇到了一个问题 - 当我按下loginBtn时,系统总是会弹出一个“Ac不存在。”

这是代码: LoginActivity.java

package com.example;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class LoginActivity extends AppCompatActivity {

EditText usernameTxt, passwordTxt;
Button loginBtn, newAcBtn;
DatabaseHandler dbHelper;
List<UsersDatabase> Users = new ArrayList<UsersDatabase>();


public void define(){
    usernameTxt = (EditText)findViewById(R.id.txtUsername);
    passwordTxt = (EditText)findViewById(R.id.txtPassword);
    loginBtn = (Button)findViewById(R.id.btnLogin);
    newAcBtn = (Button)findViewById(R.id.btnNewAccount);

    dbHelper = new DatabaseHandler(getApplicationContext());
}

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

    define();
    NewAccountBtnOnClick();
    LoginBtnEnable();
    LoginBtnOnClick();
}

public void NewAccountBtnOnClick(){
    newAcBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent LoginToMain = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(LoginToMain);
        }
    });
}

public void LoginBtnEnable(){
    usernameTxt.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            if (String.valueOf(usernameTxt.getText()).trim().length() > 0) {
                passwordTxt.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
                        loginBtn.setEnabled(String.valueOf(passwordTxt.getText()).trim().length() > 0);
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                    }
                });
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
}

public void LoginBtnOnClick(){
    loginBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            UsersDatabase user = new UsersDatabase(dbHelper.getUserCount(), String.valueOf(usernameTxt.getText()), String.valueOf(passwordTxt.getText()));
            if (!userExists(user)) {
                Toast.makeText(getApplicationContext(), " Ac does not exist.", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent LoginToMain = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(LoginToMain);
        }
    });
}

private boolean userExists(UsersDatabase user)
{
    String name = user.getUsername();
    int userCount = Users.size();
    for (int i = 0; i < userCount; i++)
    {
        if (name.compareToIgnoreCase(Users.get(i).getUsername()) ==0)
            return true;
    }
    return false;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_login, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

UsersDatabase.java

package com.example;

public class UsersDatabase {

private String  _username, _password;
private int _uid;

public UsersDatabase(int uid, String username, String password)
{
    _uid = uid;
    _username = username;
    _password = password;
}

public String getUsername()
{
    return _username;
}

public int getUserId() { return _uid; }

public String getPassword()
{
    return _password;
}

}

和DatabaseHandler.java

package com.example;

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

import java.util.ArrayList;
import java.util.List;

public class DatabaseHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;

private static final String DATABASE_NAME = "usersManager",
        TABLE_USERS = "Users",
        KEY_UID = "uid",
        KEY_USERNAME = "username",
        KEY_PASSWORD = "password";

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

@Override
public void onCreate(SQLiteDatabase db)
{
    db.execSQL("CREATE TABLE " + TABLE_USERS + " (" + KEY_UID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USERNAME + " TEXT," + KEY_PASSWORD + " TEXT)");
}

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

    onCreate(db);
}

public void createUser(UsersDatabase user)
{
    SQLiteDatabase db = getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_USERNAME, user.getUsername());
    values.put(KEY_PASSWORD, user.getPassword());

    db.insert(TABLE_USERS, null, values);
    db.close();
}

public UsersDatabase getUser(int id)
{
    SQLiteDatabase db = getReadableDatabase();

    Cursor cursor = db.query(TABLE_USERS, new String[] { KEY_UID, KEY_USERNAME, KEY_PASSWORD}, KEY_UID + "=?", new String[] { String.valueOf(id)},null, null, null, null);

    if (cursor != null)
        cursor.moveToFirst();

    UsersDatabase user = new UsersDatabase(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2));
    db.close();
    cursor.close();
    return user;
}

public void deleteUser(UsersDatabase user)
{
    SQLiteDatabase db = getWritableDatabase();
    db.delete(TABLE_USERS, KEY_UID + "=?", new String[] { String.valueOf(user.getUserId())});
    db.close();
}

public int getUserCount()
{
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_USERS, null);
    int count = cursor.getCount();
    db.close();
    cursor.close();

    return count;
}

public int updateUser(UsersDatabase user)
{
    SQLiteDatabase db = getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_USERNAME, user.getUsername());
    values.put(KEY_PASSWORD, user.getPassword());

    int rowsAffected = db.update(TABLE_USERS, values, KEY_UID + "=?", new String[]{String.valueOf(user.getUserId())});
    db.close();

    return rowsAffected;
}

public List<UsersDatabase> getAllUsers()
{
    List<UsersDatabase> users = new ArrayList<UsersDatabase>();

    SQLiteDatabase db = getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_USERS, null);
    if (cursor.moveToFirst()) {
        do {
            users.add(new     UsersDatabase(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2)));
        }
        while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return users;
}
}

1 个答案:

答案 0 :(得分:0)

我现在解决了这个问题。 我将用户更改为dbHandler.getAllUsers()

    private boolean userExists(UsersDatabase user)
{
String name = user.getUsername();
int userCount = dbHandler.getAllUsers().size();
for (int i = 0; i < userCount; i++)
{
    if (name.compareToIgnoreCase(dbHandler.getAllUsers().get(i).getUsername()) ==0)
        return true;
}
return false;
}