数据库显示为空,但登录成功

时间:2019-06-17 07:52:43

标签: java android database sqlite

我正在创建一个数据库,如果用户单击“注册”,他们的用户名,电子邮件和密码等信息将记录到数据库中。

但是,问题是,每当我打开数据库时,它总是空的! 即使该应用程序允许我使用刚刚创建的帐户登录。

我设法两次在数据库中看到结果,但不知道我是如何做到的。 但是在大多数情况下,它只是打开表而没有结果

package com.example.finalyearproject;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class userDatabase
extends SQLiteOpenHelper {

public static String DATABASE_NAME = "User.db";
public static int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "user_table";
public static final String COL_ID = "ID";
public static final String COL_USERNAME = "USERNAME";
public static final String COL_EMAIL = "EMAIL";
public static final String COL_PASSWORD = "PASSWORD";

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

@Override
public void onCreate(SQLiteDatabase db) {
    String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +"(" +
            COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COL_USERNAME + " text, " +
            COL_PASSWORD + " text, " +
            COL_EMAIL + " text " +
            ")";
    db.execSQL(sql);
}


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

public boolean create (Account account) {
    boolean result = true;
    try
    {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_USERNAME, account.getUsername());
        contentValues.put(COL_EMAIL, account.getEmail());
        contentValues.put(COL_PASSWORD, account.getPassword());
        result = db.insert(TABLE_NAME, null, contentValues) > 0;
    } catch (Exception e) {
        result = false;
    }
    return result;
}

public Account login(String username, String password) {
    Account account = null;
    try {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from " + TABLE_NAME +
                " where username = ? and password = ?",
                new String[]{username, password});

        if (cursor.moveToFirst()) {
            account = new Account();
            account.setId(cursor.getInt(0));
            account.setUsername(cursor.getString(1));
            account.setEmail(cursor.getString(2));
            account.setPassword(cursor.getString(3));
        }
    } catch (Exception e) {
        account = null;
    }
    return account;
}

public Account checkUsername(String username) {
    Account account = null;
    try {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from " + TABLE_NAME +
                        " where username = ?",
                new String[]{username});

        if (cursor.moveToFirst()) {
            account = new Account();
            account.setId(cursor.getInt(0));
            account.setUsername(cursor.getString(1));
            account.setEmail(cursor.getString(2));
            account.setPassword(cursor.getString(3));
        }
    } catch (Exception e) {
        account = null;
    }
        return account;
}

}

这是我的注册表单的代码

    import android.content.DialogInterface;
    import android.content.Intent;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;

public class SignUp extends AppCompatActivity implements View.OnClickListener {

userDatabase myDb;

private EditText editUser, editPassword, editEmail, editCpassword;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_up);
    setTitle("Sign Up");
    myDb = new userDatabase(this);
    editUser = findViewById(R.id.editSignUpUser);
    editPassword = findViewById(R.id.editSignUpPassword);
    editEmail = findViewById(R.id.editSignUpEmail);
    editCpassword = findViewById(R.id.editConfirmpassword);
    Button buttonRegister = findViewById(R.id.buttonRegister);
    buttonRegister.setOnClickListener(SignUp.this);
}


@Override
public void onClick(View v) {
    if (v.getId() == R.id.buttonRegister) {
        try {
            userDatabase userDatabase = new userDatabase(getApplicationContext());
            Account account = new Account();
            account.setEmail(editEmail.getText().toString());
            account.setPassword(editPassword.getText().toString());
            account.setUsername(editUser.getText().toString());
            Account temp = userDatabase.checkUsername(editUser.getText().toString());

            if (temp == null) {
                if (userDatabase.create(account)) {
                    Intent intent = new Intent(SignUp.this, MainActivity.class);
                    startActivity(intent);
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                    builder.setTitle("Error");
                    builder.setMessage("Can not Create");
                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int which) {
                            dialogInterface.cancel();
                        }
                    });
                    builder.show();
                }
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                builder.setTitle("Error");
                builder.setMessage("Username Exists");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int which) {
                        dialogInterface.cancel();
                    }
                });
                builder.show();

            }

        } catch (Exception e) {
            AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
            builder.setTitle("Error");
            builder.setMessage(e.getMessage());
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int which) {
                    dialogInterface.cancel();
                }
            });
            builder.show();
        }
    }
}

}

这是我的MainActivity

public class MainActivity extends AppCompatActivity
implements View.OnClickListener {


private EditText editLoginUsername;
private EditText editLoginPassword;
private Button ButtonLectureLogin;
private Button ButtonStudentLogin;
private Button ButtonSignUp;



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

    editLoginUsername = findViewById(R.id.editLoginUser);
    editLoginPassword = findViewById(R.id.editLoginPassword);

    Button button = findViewById(R.id.buttonStudentLogin);
    button.setOnClickListener(MainActivity.this);
    button = findViewById(R.id.buttonLecturerLogin);
    button.setOnClickListener(MainActivity.this);
    button = findViewById(R.id.buttonSignUp);
    button.setOnClickListener(MainActivity.this);

}

@Override
public void onClick(View v) {

    if (v.getId()==R.id.buttonSignUp) {
        Intent intent  = new Intent(
                MainActivity.this,
                SignUp.class);

        startActivity(intent);
    }

    else if (v.getId()==R.id.buttonLecturerLogin) {
        userDatabase userDatabase = new userDatabase(getApplicationContext());
        String username = editLoginUsername.getText().toString();
        String password = editLoginPassword.getText().toString();
        Account account = userDatabase.login(username, password);

        if (account == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
            builder.setTitle("Error");
            builder.setMessage("Invalid Account");
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int which) {
                    dialogInterface.cancel();
                }
            });
            builder.show();
        } else {
            Intent intent = new Intent(MainActivity.this, Lecturer.class);
            intent.putExtra("Account", account);
            startActivity(intent);
        }
    }

    else if (v.getId()==R.id.buttonStudentLogin) {
        //code for when button is pressed, checks database then redirects accordingly
    }

}

}

它还没有完全完成,因为我试图在继续之前弄清楚数据库如何工作

1 个答案:

答案 0 :(得分:0)

我相信您的问题与采用何种方法得出结论的结论

  

每当我打开数据库时,它总是空的!

这就是复制您提供的代码,然后按照<->

添加 MainActivity.java
public class MainActivity extends AppCompatActivity {
    userDatabase myDb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myDb = new userDatabase(this);

        DatabaseUtils.dumpCursor(
                myDb.getWritableDatabase()
                        .query(userDatabase.TABLE_NAME,null,null,null,null,null,null)
        );

        Account a = myDb.login("Fred","password");
        Log.d(
                "ACCOUNTINFO",
                "Username = " + a.getUsername() +
                        " Email = " + a.getEmail() +
                        " Password = " + a.getPassword() +
                        " ID=" + String.valueOf(a.getId())
        );
    }
}

即使用:-

注册后从字面上转储光标
  • 用户名弗雷德
  • fred@fredmail.com
  • 发送电子邮件
  • 密码为密码
  • 确认密码为密码

日志中的输出为:-

2019-06-17 22:20:14.653 15017-15017/aso.so56626957signin I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@1b21f
2019-06-17 22:20:14.653 15017-15017/aso.so56626957signin I/System.out: 0 {
2019-06-17 22:20:14.653 15017-15017/aso.so56626957signin I/System.out:    ID=1
2019-06-17 22:20:14.653 15017-15017/aso.so56626957signin I/System.out:    USERNAME=Fred
2019-06-17 22:20:14.654 15017-15017/aso.so56626957signin I/System.out:    PASSWORD=password
2019-06-17 22:20:14.654 15017-15017/aso.so56626957signin I/System.out:    EMAIL=fred@fredmail.com
2019-06-17 22:20:14.654 15017-15017/aso.so56626957signin I/System.out: }
2019-06-17 22:20:14.654 15017-15017/aso.so56626957signin I/System.out: <<<<<
2019-06-17 22:20:14.656 15017-15017/aso.so56626957signin D/ACCOUNTINFO: Username = Fred Email = password Password = fred@fredmail.com ID=1

结论是上述所有代码似乎都在工作。您可能希望在MainActivity.java中尝试上面的代码。

但是,您可能会注意到密码和电子邮件已交换。这是由于交换了硬编码的偏移量。建议不要使用硬编码的偏移量从游标获取数据,而应根据列名获取偏移量。

还建议不要对列名进行硬编码,而应使用常量,并且还应使用 query 方法而不是 rawQuery 方法(如果可能)

因此,建议您更改:-

public Account login(String username, String password) {
    Account account = null;
    try {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from " + TABLE_NAME +
                        " where username = ? and password = ?",
                new String[]{username, password});

        if (cursor.moveToFirst()) {
            account = new Account();
            account.setId(cursor.getInt(0));
            account.setUsername(cursor.getString(1));
            account.setEmail(cursor.getString(2));
            account.setPassword(cursor.getString(3));
        }
    } catch (Exception e) {
        account = null;
    }
    return account;
}

至:-

public Account login(String username, String password) {
    Account account = null;
    try {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query(
                TABLE_NAME,
                null,
                COL_USERNAME + "=? AND " + COL_PASSWORD + "=?",
                new String[]{username,password},
                null,null,null
        );
        if (cursor.moveToFirst()) {
            account = new Account();
            account.setId(cursor.getInt(cursor.getColumnIndex(COL_ID)));
            account.setUsername(cursor.getString(cursor.getColumnIndex(COL_USERNAME)));
            account.setEmail(cursor.getString(cursor.getColumnIndex(COL_EMAIL)));
            account.setPassword(cursor.getString(cursor.getColumnIndex(COL_PASSWORD)));
        }
    } catch (Exception e) {
        account = null;
    }
    return account;
}

同样使用:-

public Account checkUsername(String username) {
    Account account = null;
    try {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query(
                TABLE_NAME,
                null,
                COL_USERNAME + "=?",
                new String[]{username},
                null,null,null
        );
        if (cursor.moveToFirst()) {
            account = new Account();
            account.setId(cursor.getInt(cursor.getColumnIndex(COL_ID)));
            account.setUsername(cursor.getString(cursor.getColumnIndex(COL_USERNAME)));
            account.setEmail(cursor.getString(cursor.getColumnIndex(COL_EMAIL)));
            account.setPassword(cursor.getString(cursor.getColumnIndex(COL_PASSWORD)));
        }
    } catch (Exception e) {
        account = null;
    }
    return account;
}

这将导致:-

2019-06-17 22:37:08.273 15361-15361/aso.so56626957signin D/ACCOUNTINFO: Username = Fred Email = fred@fredmail.com Password = password ID=1

其他评论

  

我也将在帖子中加入我的主要活动

简而言之,这与答案没什么区别,代码有效。所以无论您说什么

  

每当我打开数据库时,它总是空的!

那是问题。

  • 注释掉//intent.putExtra("Account“,account);

您可以按照以下说明通过修改MainActivity的 onCLick 方法中的登录处理来证明这种情况:-

@Override     public void onClick(View v){

    if (v.getId()==R.id.buttonSignUp) {
        Intent intent  = new Intent(
                MainActivity.this,
                SignUp.class);
        startActivity(intent);
    }

    else if (v.getId()==R.id.buttonLecturerLogin) {
        userDatabase userDatabase = new userDatabase(getApplicationContext());
        String username = editLoginUsername.getText().toString();
        String password = editLoginPassword.getText().toString();
        Account account = userDatabase.login(username, password);

        if (account == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
            builder.setTitle("Error");
            builder.setMessage("Invalid Account");
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int which) {
                    dialogInterface.cancel();
                }
            });
            builder.show();
        } else {
            Intent intent = new Intent(MainActivity.this, Lecturer.class);
            //intent.putExtra("Account", account);
            startActivity(intent);
        }
    }

    else if (v.getId()==R.id.buttonStudentLogin) {


        userDatabase myDb = new userDatabase(v.getContext()); //<<<<<<<<<< ADDED
        //Extract all users and dump them to the log
        DatabaseUtils.dumpCursor(
                myDb.getWritableDatabase()
                        .query(userDatabase.TABLE_NAME,null,null,null,null,null,null)
        );
        //LOGIN ATTEMPT
        Account a = myDb.login(editLoginUsername.getText().toString(),editLoginPassword.getText().toString()); //<<<<<<<<<< attempt to login is here
        String loginresult = "Failed"; // Default value
        if (a != null) {
            loginresult = "Worked."; // value set to worked if the login worked
        }
        Log.d("LOGINRESULT","The attempt to login " + loginresult); //<<<<<<< write result of the login attempt to the log
        //code for when button is pressed, checks database then redirects accordingly
    }
}

使用相同的用户名 Fred 和密码密码,然后单击“学生登录”按钮,您将获得:-

06-18 07:09:24.314 1881-1881/aso.so56626957signin I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@49e1d9f
06-18 07:09:24.314 1881-1881/aso.so56626957signin I/System.out: 0 {
06-18 07:09:24.314 1881-1881/aso.so56626957signin I/System.out:    ID=1
06-18 07:09:24.314 1881-1881/aso.so56626957signin I/System.out:    USERNAME=Fred
06-18 07:09:24.314 1881-1881/aso.so56626957signin I/System.out:    PASSWORD=password
06-18 07:09:24.314 1881-1881/aso.so56626957signin I/System.out:    EMAIL=fred@fredmail.com
06-18 07:09:24.314 1881-1881/aso.so56626957signin I/System.out: }
06-18 07:09:24.314 1881-1881/aso.so56626957signin I/System.out: <<<<<
06-18 07:09:24.314 1881-1881/aso.so56626957signin D/LOGINRESULT: The attempt to login Worked.

尝试使用其他凭据登录学生会导致:-

06-18 07:09:34.264 1881-1881/aso.so56626957signin I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@6bcb36d
06-18 07:09:34.264 1881-1881/aso.so56626957signin I/System.out: 0 {
06-18 07:09:34.264 1881-1881/aso.so56626957signin I/System.out:    ID=1
06-18 07:09:34.264 1881-1881/aso.so56626957signin I/System.out:    USERNAME=Fred
06-18 07:09:34.264 1881-1881/aso.so56626957signin I/System.out:    PASSWORD=password
06-18 07:09:34.264 1881-1881/aso.so56626957signin I/System.out:    EMAIL=fred@fredmail.com
06-18 07:09:34.264 1881-1881/aso.so56626957signin I/System.out: }
06-18 07:09:34.264 1881-1881/aso.so56626957signin I/System.out: <<<<<
06-18 07:09:34.265 1881-1881/aso.so56626957signin D/LOGINRESULT: The attempt to login Failed

即第一个显示有数据