I am trying to implement a login/sign up feature to my application. I have a create user method that should create a new user and save it to my database (SQLite).
Not sure if it is relevant but the database already contains a lot of data that is the basis for the quiz application I am making. I made the database outside of the project and then added it into the assets folder and added the database path. All the getReadable functionality that is used for quiz generation works fine.
In the same database I have now added user table and the user entry is not visible in the database, using SQLite Studio to look at database (also where I created the tables in the first place) I have added a check to see if user already exists and upon starting the application I have added a query to the users table for logging purposes to try and decipher what is happening. If i click sign up i receive a toast saying a new user has been created, if i click again i have a toast saying user already exists. When i start the application i have a log saying there is x amount of users (depending on how many i have created). However if i delete the emulator completely and create a new one then the table contains 0 users again. No user is ever visible in the database in SQLite studio. It seems like the user is being stored in some local cache or something but never actually being persisted to the actual database.
The join button on click method
joinBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = signupUsername.getText().toString();
String password = signupPassword.getText().toString();
User user = new User(username, password);
if (!username.isEmpty() && !password.isEmpty()) {
DatabaseHelper db = new DatabaseHelper(MainActivity.this, null, null, DatabaseHelper.DB_VERSION);
db.createUser(user);
} else {
Toast.makeText(MainActivity.this, "Please fill in both fields", Toast.LENGTH_SHORT).show();
}
}
});
// My entire Database helper class minus all the other table creations
// The LoadHandler() method is called in the application activity
public class DatabaseHelper extends SQLiteOpenHelper {
public static final int DB_VERSION = 8;
private static final String DB_NAME = "GeoQuizDatabase.db";
private String DB_PATH = "/data/data/com.example.geoquiz/databases/";
SQLiteDatabase myDatabase;
private final Context mContext;
public DatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, DB_NAME, factory, DB_VERSION);
this.mContext = context;
}
public void onCreate(SQLiteDatabase db) {
// Creating the Users Table
String CREATE_USERS_TABLE = "CREATE TABLE IF NOT EXISTS users (" +
"user_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"username TEXT NOT NULL, " +
"password TEXT NOT NULL)";
db.execSQL(CREATE_USERS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS users");
// Create tables again
onCreate(db);
}
private boolean checkDatabase() {
try {
return mContext.getDatabasePath(DB_NAME).exists();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
private void copyDatabase() throws IOException {
try {
InputStream mInputStream = mContext.getAssets().open(DB_NAME);
String outFilename = DB_PATH + DB_NAME;
OutputStream mOutputStream = new FileOutputStream(outFilename);
byte[] buffer = new byte[1024];
int length;
while ((length = mInputStream.read(buffer)) > 0) {
mOutputStream.write(buffer, 0, length);
}
mOutputStream.flush();
mOutputStream.close();
mInputStream.close();
Log.d("DatabaseHelper", "Database copied successfully1.");
} catch (IOException e) {
Log.e("DatabaseHelper", "Failed to copy database", e);
}
}
@Override
public synchronized void close() {
if (myDatabase != null) {
myDatabase.close();
SQLiteDatabase.releaseMemory();
super.close();
}
}
public void loadHandler() {
try {
boolean mDatabaseExists = checkDatabase();
if (!mDatabaseExists) {
Log.i("DatabaseHelper", "Copying database...");
copyDatabase();
Log.i("DatabaseHelper", "Database copied successfully.");
}
copyDatabase();
myDatabase = this.getReadableDatabase();
Log.i("DatabaseHelper", "Database opened successfully.");
Cursor cursor = myDatabase.rawQuery("SELECT COUNT(*) FROM users", null);
if (cursor.moveToFirst()) {
int count = cursor.getInt(0);
Log.d("DatabaseHelper", "Query result: " + count);
} else {
Log.w("DatabaseHelper", "Cursor is empty");
}
cursor.close();
} catch (IOException | SQLException e) {
Log.e("DatabaseHelper", "Error loading database", e);
}
}
// -- ALL METHODS RELATED TO USERS AND LOGINS BELOW-- //
public void createUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.query("users", new String[]{"username"}, "username = ?", new String[]{user.getUsername()}, null, null, null);
if (cursor.getCount() > 0) {
cursor.close();
db.close();
Toast.makeText(this.mContext, "Username already exists!", Toast.LENGTH_SHORT).show();
return;
}
cursor.close();
ContentValues values = new ContentValues();
values.put("username", user.getUsername());
values.put("password", user.getPassword());
long newRowId = db.insert("users", null, values);
if (newRowId == -1) {
Log.e("DatabaseHelper", "Failed to insert new user.");
Toast.makeText(mContext, "Error inserting new user", Toast.LENGTH_SHORT).show();
} else {
Log.d("DatabaseHelper", "New user inserted with ID: " + newRowId);
Toast.makeText(mContext, "User created successfully!", Toast.LENGTH_SHORT).show();
}
db.close();
}
}
1