is this code work for Update delete search android studio by Apweslk - android-database

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";
}
}

Related

Wrong password/email error authentication activity - with SQLite

What can be wrong with the Onclick() method? Or verifyFromSqlite()? Trying to login with data just provided to the registration form, why the output of pressing Login button is just an error that the password/email is wrong?
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
private final AppCompatActivity activity = LoginActivity.this;
private NestedScrollView nestedScrollView;
private TextInputLayout textInputLayoutEmail;
private TextInputLayout textInputLayoutPassword;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private AppCompatButton appCompatButtonLogin;
private AppCompatTextView textViewLinkRegister;
private InputValidation inputValidation;
private DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
initViews();
initListeners();
initObjects();
}
private void initViews(){
nestedScrollView = (NestedScrollView) findViewById(R.id.nestedScrollView);
textInputLayoutEmail= (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword= (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
textInputEditTextEmail=(TextInputEditText) findViewById(R.id.textInputEditTextEmail);
textInputEditTextPassword=(TextInputEditText) findViewById(R.id.textInputEditTextPassword);
appCompatButtonLogin = (AppCompatButton) findViewById(R.id.appCompatButtonLogin);
textViewLinkRegister= (AppCompatTextView) findViewById(R.id.textViewLinkRegister);
}
private void initListeners(){
appCompatButtonLogin.setOnClickListener(this);
textViewLinkRegister.setOnClickListener(this);
}
private void initObjects(){
databaseHelper = new DatabaseHelper(activity);
inputValidation = new InputValidation(activity);
}
#Override
public void onClick(View v){
switch (v.getId()){
case R.id.appCompatButtonLogin:
verifyFromSQLite();
break;
case R.id.textViewLinkRegister:
Intent intentRegister = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(intentRegister);
break;
}
}
private void verifyFromSQLite(){
if (!inputValidation.isInputEditTextFilled(textInputEditTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))){
return;
}
if (!inputValidation.isInputEditTextEmail(textInputEditTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))){
return;
}
if (!inputValidation.isInputEditTextFilled(textInputEditTextPassword, textInputLayoutPassword, getString(R.string.error_message_password))){
return;
}
if(databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim()
, textInputEditTextPassword.getText().toString().trim())){
Intent accountsIntent = new Intent(activity, UsersActivity.class);
accountsIntent.putExtra("EMAIL", textInputEditTextEmail.getText().toString().trim());
emptyInputEditText();
startActivity(accountsIntent);
} else {
Snackbar.make(nestedScrollView, getString(R.string.error_valid_email_password), Snackbar.LENGTH_LONG).show();
}
}
private void emptyInputEditText(){
textInputEditTextEmail.setText(null);
textInputEditTextPassword.setText(null);
}
}
This right here will do the wrong thing I believe.
if(databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim()
, textInputEditTextPassword.getText().toString().trim())){
Intent accountsIntent = new Intent(activity, UsersActivity.class);
accountsIntent.putExtra("EMAIL", textInputEditTextEmail.getText().toString().trim());
emptyInputEditText();
startActivity(accountsIntent);
} else {
Snackbar.make(nestedScrollView, getString(R.string.error_valid_email_password), Snackbar.LENGTH_LONG).show();
}
}
please let me know what I am doing wrong because I've tried all the other answers and it won't click to me :) Why would error message me after registration and trying to log in?
Assuming that the checkUser method is unchanged from your previous question i.e. it is :-
public boolean checkUser(String password, String email){
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db= this.getWritableDatabase();
String selection = COLUMN_USER_EMAIL + " = ? " + "AND "+ COLUMN_USER_PASSWORD+" =? ";
String[] selectionArgs = { email,password };
Cursor cursor = db.query(TABLE_USER,
columns,
selection,
selectionArgs,
null,
null,
null);
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if(cursorCount > 0){
return true;
}
return false;
}
Then you are passing the email as the password and the password as the email. Try changing :-
if(databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim()
, textInputEditTextPassword.getText().toString().trim())){
Intent accountsIntent = new Intent(activity, UsersActivity.class);
accountsIntent.putExtra("EMAIL", textInputEditTextEmail.getText().toString().trim());
emptyInputEditText();
startActivity(accountsIntent);
} else {
Snackbar.make(nestedScrollView, getString(R.string.error_valid_email_password), Snackbar.LENGTH_LONG).show();
}
}
to :-
if(databaseHelper.checkUser( textInputEditTextPassword.getText().toString().trim()
,textInputEditTextEmail.getText().toString().trim())){
Intent accountsIntent = new Intent(activity, UsersActivity.class);
accountsIntent.putExtra("EMAIL", textInputEditTextEmail.getText().toString().trim());
emptyInputEditText();
startActivity(accountsIntent);
} else {
Snackbar.make(nestedScrollView, getString(R.string.error_valid_email_password), Snackbar.LENGTH_LONG).show();
}
}

JavaFX - How do I access the result(ObservableList) from a service?

How do I access the returned result from a service? The result is queried from the database and added to a ObservableList. I have a checkbox and wanted its value to depend on the result from the database.
How do I bind the checkbox so that its value(checked/unchecked) will depend on the rs.getString("studentForm137") field.
//cboxForm137.selectedProperty().bind(//I don't know the codes to bind checkbox);
Service
final Service<ObservableList<Student>> service = new Service<ObservableList<Student>>()
{
#Override
protected Task<ObservableList<Student>> createTask()
{
return new Task<ObservableList<Student>>()
{
#Override
protected ObservableList<Student> call() throws Exception
{
for (int i = 0; i < 250; i++)
{
updateProgress(i, 250);
Thread.sleep(2);
}
return student.display();
}
};
}
};
service.start();
Student Class
public class Student extends Person {
private SimpleStringProperty form137;
private SimpleStringProperty form138;
private SimpleStringProperty goodMoralCertificate;
private SimpleStringProperty birthCertificate;
private SimpleStringProperty highschoolDiploma;
public Student()
{
super();
}
public Student(String lastName, String firstName, String middleName,
String cpNumber, String address, String dateOfBirth,
String placeOfBirth, String emailAddress, String gender,
String fathersName, String mothersName,
String form137, String form138, String goodMoralCertificate,
String birthCertificate, String highschoolDiploma)
{
super(lastName, firstName, middleName,
cpNumber, address, dateOfBirth, placeOfBirth, emailAddress, gender,
fathersName, mothersName);
this.form137 = new SimpleStringProperty(form137);
this.form138 = new SimpleStringProperty(form138);
this.goodMoralCertificate = new SimpleStringProperty(goodMoralCertificate);
this.birthCertificate = new SimpleStringProperty(birthCertificate);
this.highschoolDiploma = new SimpleStringProperty(highschoolDiploma);
}
//form137
public String getForm137()
{
return form137.get();
}
public void setForm137(String form137)
{
this.form137.set(form137);
}
public StringProperty form137Property()
{
return form137;
}
//form138
public String getForm138()
{
return form138.get();
}
public void setForm138(String form138)
{
this.form138.set(form138);
}
public StringProperty form138Property()
{
return form138;
}
//goodMoralCertificate
public String getGoodMoralCertificate()
{
return goodMoralCertificate.get();
}
public void setGoodMoralCertificate(String goodMoralCertificate)
{
this.goodMoralCertificate.set(goodMoralCertificate);
}
public StringProperty goodMoralCertificateProperty()
{
return goodMoralCertificate;
}
//birthCertificate
public String getBirthCertificate()
{
return birthCertificate.get();
}
public void setBirthCertificate(String birthCertificate)
{
this.birthCertificate.set(birthCertificate);
}
public StringProperty birthCertificateProperty()
{
return birthCertificate;
}
//highschoolDiploma
public String getHighschoolDiploma()
{
return highschoolDiploma.get();
}
public void setHighschoolDiploma(String highschoolDiploma)
{
this.highschoolDiploma.set(highschoolDiploma);
}
public StringProperty highschoolDiplomaProperty()
{
return highschoolDiploma;
}
#Override
public ObservableList display()
{
Connection c = null;
PreparedStatement pst = null;
ResultSet rs = null;
ObservableList<Student> student = FXCollections.observableArrayList();
try
{
c = MySqlConnection.connect();
String SQL = "SELECT * " +
"FROM students ";
pst = c.prepareStatement(SQL);
rs = pst.executeQuery();
while(rs.next())
{
student.add(new Student(rs.getString("studentLastName"),
rs.getString("studentFirstName"),
rs.getString("studentMiddleName"),
rs.getString("studentCPNumber"),
rs.getString("studentAddress"),
rs.getString("studentDateOfBirth"),
rs.getString("studentPlaceOfBirth"),
rs.getString("studentEmailAddress"),
rs.getString("studentGender"),
rs.getString("studentFathersName"),
rs.getString("studentMothersName"),
rs.getString("studentForm137"),
rs.getString("studentForm138"),
rs.getString("studentGMC"),
rs.getString("studentNSO"),
rs.getString("studentHSDiploma")));
}
}
catch(Exception e)
{
System.out.println("Error on Building Data");
}
finally
{
try
{
PublicClass.closeConnection(c, pst, rs);
}
catch (SQLException ex)
{
Logger.getLogger(Student.class.getName()).log(Level.SEVERE, null, ex);
}
}
return student;
}
}

Login validation from database error Android [closed]

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.

data/data/com.package/databases folder isn't showed

I made an android dictionary application. I have created a database named "kamusJawa.sqlite" and copied it to the assets folder. I tried the code in this link Own Database in Assets Folder on Android Eclipse Project
This is my database manager class:
package com.kamusJI;
public class DBHelper extends SQLiteOpenHelper{
private static String DBPATH = "/data/data/com.kamusJI/databases/";
private static String DBNAME = "kamusJawa.sqlite";
private SQLiteDatabase DBSQ;
private final Context KJICtx;
public DBHelper(Context context) throws IOException {
super(context, DBNAME, null, 1);
this.KJICtx = context;
// TODO Auto-generated constructor stub
boolean dbexist = cekDB();
if (dbexist) {
//System.out.println("Database exists");
openDB();
} else {
System.out.println("Database doesn't exist");
createDB();
}
}
public void createDB() throws IOException{
boolean dbExist = cekDB();
if(!dbExist){
this.getReadableDatabase();
try{
salinDB();
}catch (IOException e){
throw new Error("Gagal menyalin database");
}
}
}
boolean cekDB() {
//SQLiteDatabase cekDatabase = null;
boolean cekdb = false;
try{
String path = DBPATH + DBNAME;
File dbfile = new File(path);
//cekDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
cekdb = dbfile.exists();
}catch(SQLException e){
System.out.println("Database tidak ada");
}
return cekdb;
//return cekDatabase !=null ? true : false;
}
private void salinDB() throws IOException{
AssetManager AM = KJICtx.getAssets();
File DbFile = new File(DBPATH+DBNAME);
InputStream in = KJICtx.getAssets().open(DBNAME);
//OutputStream out = new FileOutputStream(DbFile);
OutputStream out = new FileOutputStream("/data/data/com.kamusJI/databases/kamusJawa.sqlite");
DbFile.createNewFile();
byte[] b = new byte[1024];
int i, r;
String[] Files = AM.list("");
Arrays.sort(Files);
i= 1;
String fdb = String.format("kamusJawa.db.00%d", i);
while(Arrays.binarySearch(Files, fdb)>=0){
//InputStream in = AM.open(fdb);
while(( r = in.read(b))>0)
out.write(b,0,r);
in.close();
i++;
fdb = String.format("kamusJawa.db.00%d", i);
}
out.flush();
out.close();
}
public void openDB() throws SQLException{
String path = DBPATH+DBNAME;
DBSQ = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}
public synchronized void close(){
if(DBSQ !=null)
DBSQ.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
and this is my main class:
package com.kamusJI;
public class KJI extends ListActivity {
private KJI this_class = this;
String[] Menu = {"Basa Jawa", "Bahasa Indonesia", "Tambah Data"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this, R.layout.row, R.id.Cari, Menu));
ListView lv = getListView();
lv.setTextFilterEnabled(false);
/* Defines On Item Click callback method */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent action = null;
switch(position) {
case 0:
case 1:
action = new Intent(getApplicationContext(), Cari.class);
action.putExtra("MODE", position);
break;
case 2:
action = new Intent(getApplicationContext(), Tambah.class);
action.putExtra("MODE", position);
break;
case 3:
finish();
return;
}
startActivity(action);
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
public void InitDatabase() {
AsyncTask<String, Void, String> InitDB = new AsyncTask<String, Void, String>() {
Dialog progress = null;
String msg;
DBHelper dbhelper;
#Override
protected void onPreExecute() {
try {
dbhelper = new DBHelper(this_class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!dbhelper.cekDB())
progress = ProgressDialog.show(this_class, "", "Installing Database.\nPlease wait.");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
dbhelper.createDB();
msg = "Database successfully installed.";
} catch (IOException ioe) {
msg = "Database installation failed.";
}
return msg;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (progress!=null) {
progress.dismiss();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
}
};
InitDB.execute(new String());
}
}
When I run my application, then I go to file explorer, I can't find the data/data/com.kamusJI/databases. How it can be like that?
change your database name extension to .db
You need special permissions like root access to read the path:
/data/data/com.package/databases

Android: database reading problem throws exception

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" />

Resources