怎能写在 SQLite 注册与登录系统 Android studio?

发布时间: 2016/6/26 4:20:43
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我写了一个简单的 SQLite 研发 L 系统。但我有一个问题后运行的-系统总是弹出 toast "交流不存在"。当我按 loginBtn。

这是代码 ︰ 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:

我现在解决这个问题。 更改用户 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;
}
官方微信
官方QQ群
31647020