I am trying to create a registration / authorization page for my application. In the database additionally create a table for users. At the activity with registration, after clicking the "Register" button I want to perform a check whether there is a user with such email in the database or not. And there is no, then the entered data should be recorded in a table. The check seems to be happening, but the result is always negative, it seems to me that the data is simply not recorded in the table. I can not understand why.
Database. Validation of the data entered - Exist
public class DB { //название и версия БД private static final String DB_NAME = "mydb"; private static final int DB_VERSION = 1; int remember_id = 1; //столбцы для таблицы событий и создание таблицы private static final String DB_TABLE_EVENTS = "mytab"; public static final String EVENTS_COLUMN_ID = "_id"; public static final String EVENTS_COLUMN_TITLE = "title"; public static final String EVENTS_COLUMN_DATE = "date"; public static final String EVENTS_COLUMN_TIME = "time"; public static final String EVENTS_COLUMN_ADDRESS = "address"; public static final String EVENTS_COLUMN_PHONE = "phone"; public static final String EVENTS_COLUMN_DESCRIPTION = "description"; private static final String CREATE_TABLE_EVENTS = "create table " + DB_TABLE_EVENTS + "(" + EVENTS_COLUMN_ID + " integer primary key autoincrement, " + EVENTS_COLUMN_TITLE + " text, " + EVENTS_COLUMN_DATE + " text, " + EVENTS_COLUMN_TIME + " text, " + EVENTS_COLUMN_ADDRESS + " text, " + EVENTS_COLUMN_PHONE + " text, " + EVENTS_COLUMN_DESCRIPTION + " text" + ");"; //столбцы для таблицы пользователей и создание таблицы private static final String DB_TABLE_USERS = "users_tab"; public static final String USERS_COLOMN_ID = "_id"; public static final String USERS_COLOMN_LOGIN = "login"; public static final String USERS_COLOMN_EMAIL = "email"; public static final String USERS_COLOMN_PASSWORD = "pass"; private static final String CREATE_TABLE_USERS = "create table " + DB_TABLE_USERS + "(" + USERS_COLOMN_ID + " integer primary key autoincrement, " + USERS_COLOMN_LOGIN + " text, " + USERS_COLOMN_EMAIL + " text, " + USERS_COLOMN_PASSWORD + " text" + ");"; //столбцы для таблицы списка и создание таблицы private static final String DB_TABLE_LIST = "list_tab"; public static final String LIST_COLOMN_ID = "_id"; public static final String USERLIST_COLOMN_ID = "_id_user"; public static final String EVENTLIST_COLOMN_ID = "_id_event"; private static final String CREATE_TABLE_LIST = "create table " + DB_TABLE_LIST + "(" + LIST_COLOMN_ID + " integer primary key autoincrement, " + USERLIST_COLOMN_ID + " integer not null ,foreign key ("+USERLIST_COLOMN_ID+") reference "+DB_TABLE_USERS+" ("+USERS_COLOMN_ID+"), " + EVENTLIST_COLOMN_ID + " integer not null ,foreign key ("+EVENTLIST_COLOMN_ID+") reference "+DB_TABLE_EVENTS+" ("+EVENTS_COLUMN_ID+")" + ");"; private final Context mCtx; private DBHelper mDBHelper; private SQLiteDatabase mDB; public DB(Context ctx) { mCtx = ctx; } // открыть подключение public void open() { mDBHelper = new DBHelper(mCtx, DB_NAME, null, DB_VERSION); mDB = mDBHelper.getWritableDatabase(); } // закрыть подключение public void close() { if (mDBHelper!=null) mDBHelper.close(); } // получить все данные из таблицы DB_TABLE_EVENTS public Cursor getAllData() { return mDB.query(DB_TABLE_EVENTS, null, null, null, null, null, "_id DESC"); } //получаем объект по id из таблицы DB_TABLE_EVENTS public Cursor getEventById(long id) { return mDB.query("mytab", null, "_id = " + id, null, null, null, "_id DESC"); } //проверяем существует ли пользователь public String Exist(String user) { String username=""; try { Cursor c = mDB.query(DB_TABLE_USERS, null, USERS_COLOMN_EMAIL + "=?", new String[]{String.valueOf(user)},null, null, null); if (c == null) { return username; } else { c.moveToFirst(); username = c.getString(c.getColumnIndex(USERS_COLOMN_EMAIL)); } } catch(Exception e){ e.printStackTrace(); } return username; } // добавить запись в DB_TABLE_EVENTS public void addRecEvent(String tit, String dat, String tim, String adr, String phn, String dsc) { ContentValues cv = new ContentValues(); cv.put(EVENTS_COLUMN_TITLE, tit); cv.put(EVENTS_COLUMN_DATE, dat); cv.put(EVENTS_COLUMN_TIME, tim); cv.put(EVENTS_COLUMN_ADDRESS, adr); cv.put(EVENTS_COLUMN_PHONE, phn); cv.put(EVENTS_COLUMN_DESCRIPTION, dsc); mDB.insert(DB_TABLE_EVENTS, null, cv); } // добавить запись в DB_TABLE_USERS public void addRecUsers(String login, String email, String pass) { ContentValues cv2 = new ContentValues(); cv2.put(USERS_COLOMN_EMAIL, email); cv2.put(USERS_COLOMN_LOGIN, login); cv2.put(USERS_COLOMN_PASSWORD, pass); mDB.insert(DB_TABLE_USERS, null, cv2); } // удалить запись из DB_TABLE_EVENTS public void delRec(long id) { mDB.delete(DB_TABLE_EVENTS, EVENTS_COLUMN_ID + "=" + id, null); } // класс по созданию и управлению БД private class DBHelper extends SQLiteOpenHelper { public DBHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } // создаем и заполняем БД @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_EVENTS); db.execSQL(CREATE_TABLE_USERS); ContentValues cv = new ContentValues(); for (int i = 1; i < 2; i++) { cv.put(EVENTS_COLUMN_TITLE, "Увлекательное событие"); cv.put(EVENTS_COLUMN_DATE, "Каждый день"); cv.put(EVENTS_COLUMN_TIME, "каждый час"); cv.put(EVENTS_COLUMN_ADDRESS, "где-то"); cv.put(EVENTS_COLUMN_PHONE, "спросите у нас."); cv.put(EVENTS_COLUMN_DESCRIPTION, "происходит что-то интересное. Не пропустите самые интересные события вашего города!"); db.insert(DB_TABLE_EVENTS, null, cv); } ContentValues cv2 = new ContentValues(); for (int i = 1; i < 2; i++) { cv2.put(USERS_COLOMN_LOGIN, "superuser"); cv2.put(USERS_COLOMN_EMAIL, "dasha"); cv2.put(USERS_COLOMN_PASSWORD, "12345"); db.insert(DB_TABLE_USERS, null, cv2); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } }
Activity where the registration takes place:
public class RegisterActivity extends Activity implements View.OnClickListener { EditText etRegEmail, etRegLogin, etRegPassword; Button btnRegister, btnLoginLink; TextView tvSiteLink; DB db; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register); etRegEmail = (EditText) findViewById(R.id.etRegEmail); etRegLogin = (EditText) findViewById(R.id.etRegLogin); etRegPassword = (EditText) findViewById(R.id.etRegPassword); btnRegister = (Button) findViewById(R.id.btnRegister23); btnLoginLink = (Button) findViewById(R.id.btnLoginLink); tvSiteLink = (TextView) findViewById(R.id.tvSiteLink); btnRegister.setOnClickListener(this); btnLoginLink.setOnClickListener(this); // открываем подключение к БД db = new DB(this); db.open(); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.btnRegister23: String email = (etRegEmail.getText().toString()); String login = (etRegLogin.getText().toString()); String pass = (etRegPassword.getText().toString()); String storedUser = db.Exist(email); if (email.equals(storedUser)) { Toast.makeText(this, "Вы уже зарегистрированы. Пожалуйста, авторизируйтесь.", Toast.LENGTH_SHORT).show(); } else db.addRecUsers(email, login, pass); break; case R.id.btnLoginLink: startActivity(new Intent(this, LoginActivity.class)); break; } } }
addRecUsers(String login, String email, String pass), and calldb.addRecUsers(email, login, pass);login and email places changed. - Yura Ivanov