Related
I've been stuck on this problem for a while now, and I can't seem to figure out what's wrong. I'm trying to create a database table, insert values into the table, and check to see if the email already exists. At first, it was at least telling me that the values were being inserted, now, the app only stops.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "People.db";
public static final String TABLE_NAME = "user";
public static final String COL1 = "email";
public static final String COL2 = "password";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" +
COL1 + "TEXT PRIMARYKEY," +
COL2 + "TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
/*Inserting into database*/
public boolean add(String email, String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
to database
contentValues.put(COL1, email);
contentValues.put(COL2, password);
long ins = db.insert(TABLE_NAME, null, contentValues);
if (ins == -1) return false;
else return true;
}
/*checking if email exist*/
public Boolean chkemail(String email) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * from TABLE_NAME where email = ?",
new String[]{email});
if (cursor.getCount() > 0) return false;
else return true;
}
}
This is the SignUp activity that inserts and checks the information.
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.powell.randomeats.MainActivity;
import com.powell.randomeats.R;
public class SignUp extends AppCompatActivity {
DatabaseHelper db;
EditText email, pass, pass1;
Button sign;
boolean optionsSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
db = new DatabaseHelper(this);
email = (EditText) findViewById(R.id.Email);
pass = (EditText) findViewById(R.id.Password);
pass1 = (EditText) findViewById(R.id.Confirm);
sign = (Button) findViewById(R.id.Signup);
sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1 = email.getText().toString();
String s2 = pass.getText().toString();
String s3 = pass1.getText().toString();
if (s1.equals("") || s2.equals("") || s3.equals("")) {
Toast.makeText(getApplicationContext(), "Fields are empty",
Toast.LENGTH_SHORT).show();
} else {
if (s2.equals(s3)) {
Boolean chkemail = db.chkemail(s1);
if (chkemail == true) {
Boolean insert = db.add(s1, s2);
if (insert == true) {
Toast.makeText(getApplicationContext(),
"Registered Succesfully",
Toast.LENGTH_SHORT).show();
Log();
if (optionsSwitch == true) {
openLog();
}
}
} else {
Toast.makeText(getApplicationContext(), "Email
Already exists,", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Passwords do
not match", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void Log() {
optionsSwitch = true;
}
public void openLog() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
Your issue(s)
I believe that the table is being created. However, not with the expected column names.
That is due to spaces being admitted the create statement resolves to :-
CREATE TABLE user (emailTEXT PRIMARYKEY, passwordTEXT);
As such the table will have columns emailTEXT rather than email and passwordText rather than password.
This will cause issues when attempt to use columns email and password as those columns do not exist.
Additional PRIMARYKEY is not a valid keyword so changing the create statement to
CREATE TABLE user (email TEXT PRIMARYKEY, password TEXT);
Will create the table with the correct columns BUT the email column would not reject duplicate values.
So you'd need to add a space between PRIMARY and KEY thus the create should be :-
CREATE TABLE user (email TEXT PRIMARY KEY, password TEXT);
Suggested Fix
Your code could be changed to :-
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" +
COL1 + " TEXT PRIMARY KEY," +
COL2 + " TEXT)");
}
Note that onCreate will not be invoked unless the database is deleted or it is forced to be invoked, so you could do one of the following :-
Delete the App's data (deletes the database).
uninstall the App (deletes the database).
Increase the database version (4th parameter of the call to the super e.g. use super(context, DATABASE_NAME, null, 2); (1 changed to 2)) (causes the onUpgrade method to be invoked and thus the table is dropped and then onCreate is invoked.).
Change this line:
Cursor cursor = db.rawQuery("SELECT * from TABLE_NAME where email = ?", new String[]{email});
to
Cursor cursor = db.rawQuery("SELECT * from " + TABLE_NAME + " where email = ?", new String[]{email});
so that the name of the table in the sql statement is users and not TABLE_NAME.
create database and other things in dbhelper class
public class DBHandler extends SQLiteOpenHelper{
private static final String TAG =DBHandler.class.getSimpleName();
private static final int VERSION =1;
private static final String DATABASE_NAME = "userDb.db";
private String CREATE_TABLE ="CREATE TABLE " + Users.TABLE_NAME + "("
+ Users._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + Users.USER_NAME + " TEXT,"
+ Users.USER_DOB + " TEXT," + Users.USER_GENDER + " TEXT," + Users.USER_PASSWORD + " TEXT " + ")";
private String DROP_TABLE ="DROP TABLE IF EXISTS " +Users.TABLE_NAME;
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);
}
insert data to database sqlite
//adding users
public boolean addInfo(Users addUser){
boolean result = true;
try {
SQLiteDatabase db =this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Users.USER_NAME,addUser.getUserName());
values.put(Users.USER_DOB,addUser.getDob());
values.put(Users.USER_GENDER,addUser.getGender());
values.put(Users.USER_PASSWORD,addUser.getPassword());
result =db.insert(Users.TABLE_NAME,null,values)>0;
}
catch (Exception ex){
result=false;
ex.getMessage();
}
return result;
}
update method of database.is this possible to do
//updateInfor()
public boolean updateInfor(Users updateUser){
boolean result = true;
try{
SQLiteDatabase db =this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Users.USER_NAME,updateUser.getUserName());
values.put(Users.USER_DOB,updateUser.getDob());
values.put(Users.USER_GENDER,updateUser.getGender());
values.put(Users.USER_PASSWORD,updateUser.getPassword());
//update using user id
String[] hello ={String.valueOf(updateUser.getUserName())};
result =db.update(Users.TABLE_NAME,values,Users.USER_NAME+ "=? ",hello) >0;
}
catch (Exception ex){
result =false;
}
return result;
}
retrieving all data from database`
//retrieve data from database
public List<Users>readAllInfor(){
String[] columns ={Users.USER_NAME,Users.USER_DOB,Users.USER_GENDER,Users.USER_PASSWORD};
List<Users> usersList = new ArrayList<Users>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Users.TABLE_NAME,columns,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
Users user = new Users();
user.setUserId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Users._ID))));
user.setUserName(cursor.getString(cursor.getColumnIndex(Users.USER_NAME)));
user.setDob(cursor.getString(cursor.getColumnIndex(Users.USER_DOB)));
user.setGender(cursor.getString(cursor.getColumnIndex(Users.USER_GENDER)));
user.setPassword(cursor.getString(cursor.getColumnIndex(Users.USER_PASSWORD)));
usersList.add(user);
}while (cursor.moveToNext());
}
cursor.close();
db.close();
return usersList;
}
retrieving data from database using its own id
//overloading method to retrive by id
public Cursor readAllInfor(String user){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "+UserProfile.Users.table_name+" WHERE "+UserProfile.Users.Column_UserName+" = '"+user+"'",null);
return cursor;
}
delete user from database
public boolean deleteUser(Users user){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Users.TABLE_NAME,Users._ID + "=?",
new String[]{String.valueOf(user.getUserId())});
db.close();
return true;
}
login part checking user using user name and password
public Users checkUser(String email,String password){
Users users =null;
try {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + Users.TABLE_NAME + " WHERE userName = ? AND userPassword = ?" ,new String[]{email,password} );
if (cursor.moveToFirst()){
users = new Users();
users.setUserId(cursor.getInt(0));
users.setUserName(cursor.getString(1));
users.setDob(cursor.getString(2));
users.setGender(cursor.getString(3));
users.setPassword(cursor.getString(4));
}
}catch (Exception e){
users=null;
}
return users;
}
implimantaion of all methods in db helper
public class ProfileManangment extends AppCompatActivity implements View.OnClickListener{
private final AppCompatActivity activity = ProfileManangment.this;
private RadioGroup groupGender;
private RadioButton radioButton;
private EditText username,password,dob;
private Button update;
private Users users;
private DBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_manangment);
iniViews();
iniObjects();
iniListners();
}
private void iniViews() {
username =findViewById(R.id.regUsername);
password =findViewById(R.id.regPassword);
dob =findViewById(R.id.regDob);
update=findViewById(R.id.btnUpadateReg);
groupGender = findViewById(R.id.radioGroupGender);
}
private void iniObjects() {
users =new Users();
dbHandler =new DBHandler(activity);
}
private void iniListners() {
update.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnUpadateReg : addtoDataBase();
break;
}
}
//get values of readio button
public void radioButtonValue(View v){
int radioId = groupGender.getCheckedRadioButtonId();
radioButton =findViewById(radioId);
}
private void addtoDataBase() {
users.setUserName(username.getText().toString().trim());
users.setDob(dob.getText().toString().trim());
int radioId = groupGender.getCheckedRadioButtonId();
radioButton =findViewById(radioId);
users.setGender(radioButton.getText().toString().trim());
users.setPassword(password.getText().toString().trim());
boolean result =dbHandler.addInfo(users);
if(result){
Toast.makeText(ProfileManangment.this,"SUCCESSFULLY REGISTERED",Toast.LENGTH_LONG).show();
Intent intentEditProfile = new Intent(ProfileManangment.this,EditProfile.class);
startActivity(intentEditProfile);
}
else
Toast.makeText(ProfileManangment.this,"AN ERROR OCCURRED",Toast.LENGTH_LONG).show();
}
}
search is the most important thing .please tell me any body how to use the search .my code is following
/**
* StringBuffer was used in aid of using the AlertDialog.Builder to display all the stuff
* on the screen
*/
public void search(View view) {
User user = db.readAllInfor(ET_username.getText().toString());
if(user == null) {
showStuff("Error", "No Data Found!");
return;
}
StringBuffer buffer = new StringBuffer();
buffer.append("User ID: " + user.getId() + "\n");
buffer.append("Username: " + user.getUsername() + "\n");
buffer.append("Date Of Birth: " + user.getDateOfBirth() + "\n");
buffer.append("Password: " + user.getPassword() + "\n");
buffer.append("Gender: " + user.getGender() + "\n\n");
showStuff("Data", buffer.toString());
}
/**
* This was done in the aid of displaying the stuff on the screen
*/
public void showStuff(String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
user class that create getters and setters and table columns
class Users implements BaseColumns{
public static final String TABLE_NAME = "user";
public static final String USER_NAME = "userName";
public static final String USER_PASSWORD = "userPassword";
public static final String USER_DOB = "dob";
public static final String USER_GENDER = "userGender";
private int userId;
private String userName;
private String Password;
private String dob;
private String gender;
public Users(){}
//User profile
public final class UserProfile {
private UserProfile(){}
public static class UserPro implements BaseColumns{
public static final String TABLE_NAME = "UserInfo";
public static final String COLUMN_NAME_USERNAME = "userName";
public static final String COLUMN_NAME_DOB = "dateOfBirth";
public static final String COLUMN_NAME_GENDER = "Gender";
}
}
//DBHelper
public class DBHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "UserInfo.db";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase){
String SQL_CREATE_ENTRIES =
"CREATE TABLE " + UserProfile.UserPro.TABLE_NAME + " (" +
UserProfile.UserPro._ID + " INTEGER PRIMARY KEY," +
UserProfile.UserPro.COLUMN_NAME_USERNAME + " TEXT," +
UserProfile.UserPro.COLUMN_NAME_DOB + " TEXT," +
UserProfile.UserPro.COLUMN_NAME_GENDER + " TEXT)";
sqLiteDatabase.execSQL(SQL_CREATE_ENTRIES);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public void addInfo(String username, String password){
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(UserProfile.UserPro.COLUMN_NAME_USERNAME, username);
sqLiteDatabase.insert(UserProfile.UserPro.TABLE_NAME, null, values);
}
public Boolean updateInfo(String username, String newpassword, String newdob, String newgender){
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(UserProfile.UserPro.COLUMN_NAME_USERNAME, username);
values.put(UserProfile.UserPro.COLUMN_NAME_GENDER, newgender);
values.put(UserProfile.UserPro.COLUMN_NAME_DOB, newdob);
String selection = UserProfile.UserPro.COLUMN_NAME_USERNAME + " LIKE ?";
String[] selectionArgs = {username};
int count = sqLiteDatabase.update(
UserProfile.UserPro.TABLE_NAME,
values,
selection,
selectionArgs
);
if(count>=1)
return true;
else
return false;
}
public List readAllInfo(){
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String[] projection = {
BaseColumns._ID,
UserProfile.UserPro.COLUMN_NAME_USERNAME,
UserProfile.UserPro.COLUMN_NAME_DOB,
UserProfile.UserPro.COLUMN_NAME_GENDER
};
String sortOrder = UserProfile.UserPro.COLUMN_NAME_USERNAME + " ASC";
Cursor cursor = sqLiteDatabase.query(
UserProfile.UserPro.TABLE_NAME,
projection,
null,
null,
null,
null,
sortOrder
);
List users = new ArrayList<>();
List dobs = new ArrayList<>();
List genders = new ArrayList<>();
while (cursor.moveToNext()){
String username = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.UserPro.COLUMN_NAME_USERNAME));
String dob = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.UserPro.COLUMN_NAME_DOB));
String gender = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.UserPro.COLUMN_NAME_GENDER));
users.add(username);
dobs.add(dob);
genders.add(gender);
}
cursor.close();
return users;
}
public Cursor readAllInfo(String username){
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
String selection = UserProfile.UserPro.COLUMN_NAME_USERNAME + " = ?";
String[] selectionArgs = {username};
Cursor data = sqLiteDatabase.rawQuery("SELECT * FROM " + UserProfile.UserPro.TABLE_NAME + " WHERE " + UserProfile.UserPro.COLUMN_NAME_USERNAME + " = ?", selectionArgs);
return data;
}
public int deleteInfo(String username){
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
String selection = UserProfile.UserPro.COLUMN_NAME_USERNAME + " LIKE ?";
String[] selectionArgs = {username};
int deletedRows = sqLiteDatabase.delete(UserProfile.UserPro.TABLE_NAME, selection, selectionArgs);
return deletedRows;
}
}
//Home activity
public class HomeActivity extends AppCompatActivity {
private final AppCompatActivity activity = HomeActivity.this;
private EditText userName;
private EditText password;
private RadioButton genderMale;
private RadioButton genderFemale;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
userName = findViewById(R.id.UserNameEditText);
password = findViewById(R.id.PasswordEditText);
}
public void onClickRegister(View view){
DBHelper dbHelper = new DBHelper(activity);
dbHelper.addInfo(userName.getText().toString().trim(), password.getText().toString().trim());
Toast.makeText(HomeActivity.this, "User Added", Toast.LENGTH_LONG).show();
Intent intent = new Intent(HomeActivity.this, ProfileManagementActivity.class);
startActivity(intent);
}
}
//Edit Profile
public class EditProfileActivity extends AppCompatActivity {
private final AppCompatActivity activity = EditProfileActivity.this;
private Button deleteButton;
private EditText userName;
private EditText password;
private EditText dob;
private RadioButton genderMale;
private RadioButton genderFemale;
private String gender;
private DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
deleteButton = findViewById(R.id.DeleteButton);
userName = findViewById(R.id.UserNameEditText);
password = findViewById(R.id.PasswordEditText);
dob = findViewById(R.id.DOBEditText);
genderMale = findViewById(R.id.MaleRadioButton);
genderFemale = findViewById(R.id.FemaleRadioButton);
genderMale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onRadioButtonClicked(genderMale);
}
});
genderFemale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onRadioButtonClicked(genderFemale);
}
});
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int rows = dbHelper.deleteInfo(userName.getText().toString().trim());
if(rows>0)
Toast.makeText(EditProfileActivity.this, "Entry Deleted", Toast.LENGTH_LONG).show();
else
Toast.makeText(EditProfileActivity.this, "Delete Failed", Toast.LENGTH_LONG).show();
}
});
dbHelper = new DBHelper(activity);
}
public void ReadAllInfo(View view){
Cursor data = dbHelper.readAllInfo(userName.getText().toString());
if(data.getCount() == 0){
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while (data.moveToNext()){
buffer.append("ID : " + data.getString(0) + "\n");
buffer.append("Username : " + data.getString(1) + "\n");
buffer.append("Date of Birth : " + data.getString(2) + "\n");
buffer.append("Gender : " + data.getString(3) + "\n");
}
showMessage("User Details", buffer.toString());
}
public void showMessage(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void onClickEdit(View view){
boolean success = dbHelper.updateInfo(userName.getText().toString(), password.getText().toString(), dob.getText().toString(), gender);
Toast.makeText(EditProfileActivity.this, "Info Update Success: " + success, Toast.LENGTH_LONG).show();
}
public void onRadioButtonClicked(View view){
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()){
case R.id.MaleRadioButton:
if (checked)
gender = "Male";
break;
case R.id.FemaleRadioButton:
if (checked)
gender = "Female";
break;
}
}
}
//profile Manager
public class ProfileManagementActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_management);
}
public void onClickUpdateProfile(View view){
Intent intent = new Intent(ProfileManagementActivity.this, EditProfileActivity.class);
startActivity(intent);
}
}
//DBHelper class
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "UserInformation.db";
public DBHelper(Context context){
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String SQL_CREATE_ENTRIES = "CREATE TABLE "
+ UserProfile.Users.TABLE_NAME + " ("
+ UserProfile.Users._ID + "INTEGER PRIMARY KEY AUTOINCREMENT,"
+ UserProfile.Users.COLUMN_NAME_USERNAME + "TEXT,"
+ UserProfile.Users.COLUMN_NAME_PASSWORD + "TEXT,"
+ UserProfile.Users.COLUMN_NAME_DATEOFBIRTH + "TEXT,"
+ UserProfile.Users.COLUMN_NAME_GENDER + "TEXT)";
db.execSQL(SQL_CREATE_ENTRIES);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("drop table if exists " + UserProfile.Users.TABLE_NAME);
}
public boolean addInfo(String username, String password, String dob, String gender){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(UserProfile.Users.COLUMN_NAME_USERNAME, username);
values.put(UserProfile.Users.COLUMN_NAME_PASSWORD, password);
values.put(UserProfile.Users.COLUMN_NAME_DATEOFBIRTH, dob);
values.put(UserProfile.Users.COLUMN_NAME_GENDER, gender);
int i = (int) db.insert(UserProfile.Users.TABLE_NAME, null, values);
if(i > 0)
return true;
else
return false;
}
public boolean updateInfor(String username, String password, String dob, String gender){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(UserProfile.Users.COLUMN_NAME_USERNAME, username);
values.put(UserProfile.Users.COLUMN_NAME_PASSWORD, password);
values.put(UserProfile.Users.COLUMN_NAME_DATEOFBIRTH, dob);
values.put(UserProfile.Users.COLUMN_NAME_GENDER, gender);
String selection = UserProfile.Users.COLUMN_NAME_USERNAME + " LIKE ?";
String[] selectionArgs = { username };
int i = db.update(
UserProfile.Users.TABLE_NAME,
values,
selection,
selectionArgs
);
if(i > 0)
return true;
else
return false;
}
public Cursor readAllInfor(){
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("select * from " + UserProfile.Users.TABLE_NAME + "",null);
return cursor;
}
public Cursor readAllInfor(String username){
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("select * from " + UserProfile.Users.TABLE_NAME + "where " + UserProfile.Users.COLUMN_NAME_USERNAME+"=\""+username+"\"", null);
return cursor;
}
public boolean deleteInfo(String username){
SQLiteDatabase db = getWritableDatabase();
String selection = UserProfile.Users.COLUMN_NAME_USERNAME + " LIKE ?";
String[] selectionArgs = { username };
int i = db.delete(
UserProfile.Users.TABLE_NAME,
selection,
selectionArgs
);
if(i > 0)
return true;
else
return false;
}
}
//Edit Profile class
public class EditProfileActivity extends AppCompatActivity {
private EditText username, password, dob;
private RadioGroup gender;
private RadioButton male, female;
private Button edit, delete, search;
DBHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
username = (EditText) findViewById(R.id.epusernameedittext);
dob = (EditText) findViewById(R.id.epdateofbirthedittext);
password = (EditText) findViewById(R.id.eppasswordedittext);
gender = (RadioGroup) findViewById(R.id.epagender);
male = (RadioButton) findViewById(R.id.epmale);
female = (RadioButton) findViewById(R.id.epfemale);
edit = (Button) findViewById(R.id.epedit);
delete = (Button) findViewById(R.id.epdelete);
search = (Button) findViewById(R.id.epsearch);
final String radiobuttonid = String.valueOf(gender.getCheckedRadioButtonId());
db = new DBHelper(this);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor cursor = db.readAllInfor(username.getText().toString());
int i = cursor.getCount();
if(i <= 0){
Toast.makeText(EditProfileActivity.this, "User not found", Toast.LENGTH_LONG).show();
}
while (cursor.moveToNext()){
dob.setText(cursor.getString(2));
if(cursor.getString(3).toString().matches("Male")){
male.setChecked(true);
}
else{
female.setChecked(true);
}
password.setText(cursor.getString(4));
}
}
});
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean isInserted = db.updateInfor(
username.getText().toString(),
dob.getText().toString(),
password.getText().toString(),
radiobuttonid
);
if(isInserted == true)
Toast.makeText(EditProfileActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(EditProfileActivity.this, "DAta not Added", Toast.LENGTH_LONG).show();
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean isInserted = db.deleteInfo(
username.getText().toString()
);
if(isInserted == true)
Toast.makeText(EditProfileActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(EditProfileActivity.this, "DAta not Added", Toast.LENGTH_LONG).show();
}
});
db.close();
}
}
//Home Activity
public class HomeActivity extends AppCompatActivity {
private final AppCompatActivity activity = HomeActivity.this;
private EditText username, password;
private RadioButton male, female;
Button login, register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
username = (EditText) findViewById(R.id.usernameedittext);
password = (EditText) findViewById(R.id.passwordedittext);
register = (Button) findViewById(R.id.register);
login = (Button) findViewById(R.id.login);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
registerClick();
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginClick();
}
});
}
private void loginClick() {
Intent intent = new Intent(HomeActivity.this, EditProfileActivity.class);
startActivity(intent);
}
private void registerClick() {
Intent intent = new Intent(HomeActivity.this, ProfileManagementActivity.class);
startActivity(intent);
}
}
//profile management
public class ProfileManagementActivity extends AppCompatActivity {
private EditText username, password, dob;
private Button register;
private RadioGroup gender;
DBHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_management);
username = (EditText) findViewById(R.id.prusernameedittext);
dob = (EditText) findViewById(R.id.prdateofbirthedittext);
password = (EditText) findViewById(R.id.prpasswordedittext);
register = (Button) findViewById(R.id.prupdate);
gender = (RadioGroup) findViewById(R.id.pragender);
final String radiobuttonid = String.valueOf(gender.getCheckedRadioButtonId());
db = new DBHelper(this);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean isInserted = db.addInfo(
username.getText().toString(),
password.getText().toString(),
dob.getText().toString(),
radiobuttonid
);
if(isInserted == true)
Toast.makeText(ProfileManagementActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(ProfileManagementActivity.this, "DAta not Added", Toast.LENGTH_LONG).show();
}
});
db.close();
}
}
//user profile
public final class UserProfile {
private UserProfile(){}
public static class Users implements BaseColumns{
public static final String TABLE_NAME = "Users";
public static final String COLUMN_NAME_USERNAME = "username";
public static final String COLUMN_NAME_PASSWORD = "password";
public static final String COLUMN_NAME_DATEOFBIRTH = "date_of_birth";
public static final String COLUMN_NAME_GENDER = "gender";
}
}
I am builing an MVC 5 web app and I am using entity framework 6 and I have MS SQL Server 2008 R2 as my database. I use connection pooling to ensure that I get a connection as fast as possible for db operations. My connection string in my Web.config is as follows
<add name="MyConnectionPoolConnectionString" connectionString="Data Source=MyHOST;Initial Catalog=TEST_DB;User Id=sa;Password=password1; Min Pool Size=10;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
I notice that obtaining a connection from the connection pool is very fast i.e. some tens to hundreds of milliseconds
However, what I have also noticed is that closing the connection (which in a connection pool means the connection is returned to the pool) takes a rather long time (i.e. on the average between 2000ms and 5000ms (2 - 5 secs)).
Here is an excerpt from my profiling log
Time taken to open connection
2015-02-18 21:06:55,497 Opened connection at 18/02/2015 21:06:55 92.65 ms
Time taken to close / return connection
Closed connection at 18/02/2015 21:07:01 2543.06 ms
Notice that opening the connection takes 92ms and closing the connection takes 2500ms.
BTW, these stats are provided my the EF framework itself i.e. by setting the Log property of the Database prop on the EF context i.e.
MyTestAppDbContext.Database.Log = Logger.Debug;
What I dont understand is why it is so fast to get a connection from the connection pool but it takes so long for EF to return the connection back to the pool (i.e. close the connection) and more importantly how to speed up the release/closing of the connection
This is quite important for me because the web app needs to be quite responsive and as I have to create the EF Dbcontext for every request, if EF adds an extra 2 - 5 secs overhead to just close / release a connection, it reduces the responsiveness of the app.
MyTestAppDbContext.cs
public partial class MyTestAppDbContext : DbContext
{
public ILogger Logger { get; set; }
static MyTestAppDbContext()
{
System.Data.Entity.Database.SetInitializer<MyTestAppDbContext>(null);
}
public MyTestAppDbContext(ILogger logger)
: base("Name=MyConnectionPoolConnectionString")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
Logger = logger;
this.Database.Log = Logger.Debug;
}
public override int SaveChanges()
{
Exception entityFrameworkExceptions = null;
String exMsg = "";
int result = 0;
try
{
if (this.ChangeTracker.HasChanges())
{
// Get all Added/Deleted/Modified entities (not Unmodified or Detached)
foreach (var ent in this.ChangeTracker.Entries().Where(p => p.State == EntityState.Added || p.State == EntityState.Deleted || p.State == EntityState.Modified))
{
// For each changed record, log the activity performed
Logger.Debug("Detected Changes");
}
result = base.SaveChanges();
}
}
catch (DbEntityValidationException dbEx)
{
entityFrameworkExceptions = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
//System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
exMsg += String.Format("\nProperty: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
Logger.Debug(String.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage));
}
}
}
catch (DbUpdateException dbEx)
{
entityFrameworkExceptions = dbEx;
Logger.Debug(String.Format("Exception Message: {0}", dbEx.Message));
Logger.Debug(String.Format("InnerException: {0}", dbEx.InnerException));
Logger.Debug(String.Format("StackTrace: {0}", dbEx.StackTrace));
Logger.Debug(String.Format("Call Stack: {0}", CommonUtils.GetCallStackAsString()));
}
catch (Exception ex)
{
entityFrameworkExceptions = ex;
Logger.Debug(String.Format("Exception Message: {0}", ex.Message));
Logger.Debug(String.Format("InnerException: {0}", ex.InnerException));
Logger.Debug(String.Format("StackTrace: {0}", ex.StackTrace));
Logger.Debug(String.Format("Call Stack: {0}", CommonUtils.GetCallStackAsString()));
}
if (entityFrameworkExceptions != null)
{
exMsg = exMsg + "\n" + entityFrameworkExceptions.Message + #"\n" + entityFrameworkExceptions.StackTrace + #"\n" + entityFrameworkExceptions.InnerException;
entityFrameworkExceptions = new HttpException(500, #"Exception applying changes in PaceDBContext (i.e. Entity Framework)\n" + exMsg+"\n"+CommonUtils.GetCallStackAsString());
throw entityFrameworkExceptions;
}
return result;
}
}
IUnitOfWork.cs
public interface IUnitOfWork /*: IDisposable*/
{
MyTestAppDbContext MyTestAppDbContext { get; set; }
Exception Save();
}
UnitOfWork.cs
public class UnitOfWork : IUnitOfWork, IDisposable
{
private bool disposed = false;
public MyTestAppDbContext MyTestAppDbContext {get; set;}
public ILogger Logger { get; set; }
public Exception Save()
{
Exception entityFrameworkExceptions = null;
String exMsg = "";//, callStackAsString = "";
try
{
System.Diagnostics.Trace.TraceInformation("Saving Db Changes in UnitOfWork");
MyTestAppDbContext.SaveChanges();
System.Diagnostics.Trace.TraceInformation("Finished saving Db Changes in UnitOfWork");
}
catch (DbEntityValidationException dbEx)
{
entityFrameworkExceptions = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
exMsg += String.Format("\nProperty: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
Logger.Debug(String.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage));
}
}
}
catch (DbUpdateException dbEx)
{
entityFrameworkExceptions = dbEx;
this.LogException(dbEx);
}
catch (Exception ex)
{
entityFrameworkExceptions = ex;
this.LogException(ex);
}
if (entityFrameworkExceptions != null)
{
exMsg = "\n" + entityFrameworkExceptions.Message + #"\n" + entityFrameworkExceptions.StackTrace + #"\n" + entityFrameworkExceptions.InnerException+"\n"+CommonUtils.GetCallStackAsString();
entityFrameworkExceptions = new HttpException(500, #"Exception applying changes in PaceDBContext (i.e. Entity Framework)\n" + exMsg);
throw entityFrameworkExceptions;
}
return entityFrameworkExceptions;
}
protected virtual void Dispose(bool disposing)
{
this.Save();
if (!this.disposed)
{
if (disposing)
{
MyTestAppDbContext.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void LogException(Exception ex){
Logger.Debug(String.Format("Exception Message: {0}", ex.Message));
Logger.Debug(String.Format("InnerException: {0}", ex.InnerException));
Logger.Debug(String.Format("StackTrace: {0}", ex.StackTrace));
}
}
UserRepository.cs
public class UserRepository : IUserRepository
{
public IUnitOfWork UnitOfWork { get; private set; }
public UserRepository(IUnitOfWork unitOfWork)
{
this.UnitOfWork = unitOfWork;
}
public Users GetUserByUserId(string userId)
{
if (!String.IsNullOrEmpty(userId)){
var user = from u in UnitOfWork.MyTestAppDbContext.Users
where u.UserId.Trim().Equals(userId.Trim())
select u;
return user.SingleOrDefault();
}
return null;
}
public string GetUserFullName(string userId)
{
string fullname = null;
if (!String.IsNullOrEmpty(userId))
{
var user = (from u in UnitOfWork.MyTestAppDbContext.Users
where u.UserId.Trim().Equals(userId.Trim())
select u).SingleOrDefault();
if (user != null)
{
if (!String.IsNullOrEmpty(user.FirstName))
fullname += user.FirstName + " ";
if (!String.IsNullOrEmpty(user.LastName))
fullname += user.LastName;
}
}
return fullname;
}
public long GetUserGroupId(string userId)
{
if (!String.IsNullOrEmpty(userId))
{
var user = (from u in UnitOfWork.MyTestAppDbContext.Users
where u.UserId.Trim().Equals(userId.Trim())
select u).SingleOrDefault();
if (user != null)
return user.UserGroupId;
}
return -1;
}
}
Thanks
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have created a database table where I have id, username, password and email as columns. My xml has 3 elements, Username, password edittexts and a signin button.
Method validateLogin in DatabaseActivity.java does the validation.
Error
The method getWritableDatabase() is undefined for the type DbHelper
in line ----- SQLiteDatabase db = mydb.getWritableDatabase();----
This is my DatabaseActivity.java file
package com.login.recscores;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
#SuppressLint("Registered")
public class DatabaseActivity extends Activity implements OnClickListener {
Button mLogin;
Button mNewUser;
Button mShowAll;
EditText mUsername;
EditText mPassword;
DbHelper mydb = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mNewUser = (Button)findViewById(R.id.sign_in_button);
mNewUser.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.sign_in_button:
mUsername = (EditText)findViewById(R.id.email);
mPassword = (EditText)findViewById(R.id.password);
String uname = mUsername.getText().toString();
String pass = mPassword.getText().toString();
if(uname.equals("") || uname == null){
Toast.makeText(getApplicationContext(), "email Empty", Toast.LENGTH_SHORT).show();
}else if(pass.equals("") || pass == null){
Toast.makeText(getApplicationContext(), "Password Empty", Toast.LENGTH_SHORT).show();
}else{
boolean validLogin = validateLogin(uname, pass, DatabaseActivity.this);
if(validLogin){
System.out.println("In Valid");
Intent i = new Intent(DatabaseActivity.this, UserHome.class);
startActivity(i);
finish();
}
}
break;
}
}
// #SuppressWarnings("deprecation")
public boolean validateLogin(String uname, String pass, Context context) {
mydb = new DbHelper(this);
SQLiteDatabase db = mydb.getWritableDatabase();
//SELECT
String[] columns = {"_id"};
//WHERE clause
String selection = "username=? AND password=?";
//WHERE clause arguments
String[] selectionArgs = {uname,pass};
Cursor cursor = null;
try{
//SELECT _id FROM login WHERE username=uname AND password=pass
cursor = db.query(DbHelper.RECSCORES_TABLE_NAME, columns, selection, selectionArgs, null, null, null);
// startManagingCursor(cursor);
}catch(Exception e){
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if(numberOfRows <= 0){
Toast.makeText(getApplicationContext(), "Wha Failed..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
public void onDestroy(){
super.onDestroy();
mydb.close();
}
}
The DbHelper.java is
package com.login.recscores;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DbHelper {
private static final String DATABASE_NAME = "recscores.db";
public static final String KEY_ROWID = "_id";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_EMAIL = "email";
private static final String TAG = "DbHelper";
private static final int DATABASE_VERSION = 1;
public static final String RECSCORES_TABLE_NAME = "users";
private static final String RECSCORES_TABLE_CREATE =
"CREATE TABLE " + RECSCORES_TABLE_NAME + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+
"username VARCHAR NOT NULL, password VARCHAR NOT NULL, email VARCHAR NOT NULL);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DbHelper(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(RECSCORES_TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS titles");
onCreate(db);
}
}
//---opens the database---
public DbHelper open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a title into the database---
public long insertTitle(String Id, String username, String password, String email)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ROWID, Id);
initialValues.put(KEY_USERNAME, username);
initialValues.put(KEY_PASSWORD, password);
initialValues.put(KEY_EMAIL, email);
return db.insert(RECSCORES_TABLE_NAME, null, initialValues);
}
//---deletes a particular title---
public boolean deleteTitle(long rowId)
{
return db.delete(RECSCORES_TABLE_NAME, KEY_ROWID +
"=" + rowId, null) > 0;
}
//---retrieves all the titles---
public Cursor getAllTitles()
{
return db.query(RECSCORES_TABLE_NAME, new String[] {
KEY_ROWID,
KEY_USERNAME,
KEY_PASSWORD,
KEY_EMAIL},
null,null,null,null,null);
}
//---retrieves a particular title---
public Cursor getTitle(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, RECSCORES_TABLE_NAME, new String[] {
KEY_ROWID,
KEY_USERNAME,
KEY_PASSWORD,
KEY_EMAIL
},
KEY_ROWID + "=" + rowId,
null,null,null,null,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//---updates a title---
public boolean updateTitle(long rowId, String isbn,
String title, String publisher)
{
ContentValues args = new ContentValues();
args.put(KEY_USERNAME, isbn);
args.put(KEY_PASSWORD, title);
args.put(KEY_EMAIL, publisher);
return db.update(RECSCORES_TABLE_NAME, args,
KEY_ROWID + "=" + rowId, null) > 0;
}
}
getWritableDatabase is a method on DatabaseHelper, not DbHelper. For example:
In your DbHelper.java, you use get getWritableDatabase as follows:
db = DBHelper.getWritableDatabase();
where you are declaring:
private DatabaseHelper DBHelper;
So you are calling getWritableDatabase on an instance of DatabaseHelper
However on the problem line you have this:
mydb = new DbHelper(this);
SQLiteDatabase db = mydb.getWritableDatabase();
This is attempting to call getWritableDatabase on an instance of DbHelper, which you haven't declared.
Note that you're use of a DBHelper variable within your declaration of a class called DbHelper is confusing in the extreme, and likely is the cause of the misunderstanding.
i am having this problem with the android database. I adopted the DBAdapter file the NotepadAdv3 example from the google android page.
DBAdapter.java
public class DBAdapter {
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "PasswordDb";
private static final String DATABASE_TABLE = "myuserdata";
private static final String DATABASE_USERKEY = "myuserkey";
private static final int DATABASE_VERSION = 2;
public static final String KEY_USERKEY = "userkey";
public static final String KEY_TITLE = "title";
public static final String KEY_DATA = "data";
public static final String KEY_ROWID = "_id";
private final Context mContext;
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DB_CREATE_KEY =
"create table " + DATABASE_USERKEY
+ " ("
+ "userkey text not null"
+");";
private static final String DB_CREATE_DATA =
"create table " + DATABASE_TABLE
+ " ("
+ "_id integer primary key autoincrement, "
+ "title text not null"
+ "data text"
+");";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DB_CREATE_KEY);
db.execSQL(DB_CREATE_DATA);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS myuserkey");
db.execSQL("DROP TABLE IF EXISTS myuserdata");
onCreate(db);
}
}
public DBAdapter(Context ctx)
{
this.mContext = ctx;
}
public DBAdapter Open() throws SQLException{
try {
mDbHelper = new DatabaseHelper(mContext);
}
catch(Exception e){
Log.e(TAG, e.toString());
}
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close(){
mDbHelper.close();
}
public Long storeKey(String userKey){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_USERKEY, userKey);
try {
mDb.delete(DATABASE_USERKEY, "1=1", null);
}
catch(Exception e)
{
Log.e(TAG, e.toString());
}
return mDb.insert(DATABASE_USERKEY, null, initialValues);
}
public String retrieveKey() {
final Cursor c;
try {
c = mDb.query(DATABASE_USERKEY, new String[] {
KEY_USERKEY},
null,
null,
null,
null,
null);
}catch(Exception e){
Log.e(TAG, e.toString());
return "";
}
if(c.moveToFirst()){
return c.getString(0);
}
else{
Log.d(TAG, "UserKey Empty");
}
return "";
}
//not including any function related to "myuserdata" table
}
Class1.java
{
mUserKey = mDbHelper.retrieveKey();
mDbHelper.storeKey(Key);
}
the error that i am receiving is from Log.e(TAG, e.toString()) in the methods retrieveKey() and storeKey()
"no such table: myuserkey: , while compiling: SELECT userkey FROM myuserkey"
Did you pop the DB version so onUpgrade fires? You're at version 2 in the example above but if you changed the schema since version 2 then you need to pop the version again.
i think you are not mention your provider tag in AndroidManifest.xml .Check it.
u have to mention the tag like
<provider android:name=".name of providerclass"
android:authorities="authority path" />