Saving value from cursor into a variable [duplicate] - java

This question already has an answer here:
sqlite get ROWID
(1 answer)
Closed 1 year ago.
I have an android studio app that uses sqlite to save user data such as username, password, etc. In the login page after the user enters his login credentials, the user clicks on a button that calls the following function from a DatabaseHelper java class to check if the info is correct:
public boolean checkLogin(String username, String password){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM user WHERE username=? AND password=? ",
new String[] {username, password});
if (cursor.getCount() > 0){
return true;
}
else {
return false;
}
}
I want to save the row ID that matches this user so I can use it in the future and I was thinking of saving the ID into a variable that I will then send to different activities using an intent. The issue is that I can't figure out how to save the ID from the query.

I'd suggest returning a int rather than boolean the long being the id or -1 if the user/password combination doesn't exist. So :-
public int checkLogin(String username, String password){
int rv = -1;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM user WHERE username=? AND password=? ",
new String[] {username, password});
if (cursor.moveToFirst()) {
rv = cursor.getInt(cursor.getColumnIndex("id"));
}
cursor.close();
return rv;
}
Instead of using something like :-
if (checkLogin("the_user","the_password")) {
logged in code ....
} else {
not logged in code ....
}
You could use something like :-
private int current_userid = -1; // probably declared as a class variable
....
if ((current_userid = db.checkLogin("the_user","the_password")) > 0 ) {
logged in OK code ....
} else {
not logged in code ....
}
I want to save the row ID that matches this user so I can use it in the future and I was thinking of saving the ID into a variable that I will then send to different activities using an intent.
Here's an example that does that and sends the id to another Activity (NextActivity) and then returns (finishes) from that activity after writing the username and password to the log.
First the Database Helper DBHelper :-
class DBHelper extends SQLiteOpenHelper {
SQLiteDatabase db;
public DBHelper(#Nullable Context context) {
super(context, "mydb", null, 1);
db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS user (" +
"id INTEGER PRIMARY KEY, " +
"username TEXT UNIQUE, " +
"password TEXT " +
")");
ContentValues cv = new ContentValues();
cv.put("username","fred");
cv.put("password","password_for_fred");
db.insert("user",null,cv);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) { }
public int checkLogin(String username, String password){
int rv = -1;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM user WHERE username=? AND password=? ",
new String[] {username, password});
if (cursor.moveToFirst()) {
rv = cursor.getInt(cursor.getColumnIndex("id"));
}
cursor.close();
return rv;
}
public Cursor getUserById(int userId) {
return db.query("user",null,"id=?",new String[]{String.valueOf(userId)},null,null,null);
}
}
Note that this uses a single class variable for the SQLiteDatabase, so only needs the 1 getWriteableDatabase. It also forces the database to open when constructing by including db = this.getWriteableDatabase(); in the constructor.
Note the added method getUserById(ing userId) method which returns a Cursor according to the userId.
Note that a demo user is added to the table when it is created.
MainActivity (a little overly complex as it demonstrates both a failed login attempt (1st) as well as a successful login attempt (as part of handling the failed attempt)) :-
public class MainActivity extends AppCompatActivity {
public static final String INTENT_EXTRA_CURRENT_USERID = "current_userid";
DBHelper db;
private int current_userid = -1;
private Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBHelper(this);
Log.d("LOGIN1","Attempting to Login"); // Will purposefully fail login
if ((current_userid = db.checkLogin("the_user","the_password")) > 0 ) {
Log.d("LOGIN2","Successfully Logged in to user with ID = " + String.valueOf(current_userid));
gotoNextActivity();
} else {
Toast.makeText(this,"Invalid Login, please try again",Toast.LENGTH_SHORT).show();
Log.d("LOGIN1","First attempt to login failed");
// Make 2nd attempt (will work as username and password are correct)
Log.d("LOGIN2","Attemtping to Login (2nd) ");
if((current_userid = db.checkLogin("fred","password_for_fred")) > 0 ) {
Log.d("LOGIN2","Successfully Logged in to user with ID = " + String.valueOf(current_userid));
gotoNextActivity();
}
}
}
private void gotoNextActivity() {
intent = new Intent(this,NextActivity.class);
intent.putExtra(INTENT_EXTRA_CURRENT_USERID,current_userid);
startActivity(intent);
}
}
Finally NextActivity :-
public class NextActivity extends AppCompatActivity {
private int current_userid;
private String current_username, current_password;
private DBHelper db;
Cursor csr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
db = new DBHelper(this);
current_userid = this.getIntent().getIntExtra(MainActivity.INTENT_EXTRA_CURRENT_USERID,-1);
csr = db.getUserById(current_userid);
if (csr.moveToFirst()) {
current_username = csr.getString(csr.getColumnIndex("username"));
current_password = csr.getString(csr.getColumnIndex("password"));
}
if (current_userid > 0) {
Log.d("NEXTACTIVTY","Valid user ID - Username = " + current_username + " password is " + current_password);
} else {
Log.d("NEXTACTIVITY","No Valid userid?");
}
// Finish the Activity and hence return to MainActivity
// Hence it is unlikely that the NextActivity will even be noticed.
finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (!csr.isClosed()) {
csr.close();
Log.d("NEXTACTIVITY","Closing Cursor in onDestroy method");
}
}
}
Result
When run the log includes :-
2021-07-17 12:19:37.201 D/LOGIN1: Attempting to Login
2021-07-17 12:19:37.211 D/LOGIN1: First attempt to login failed
2021-07-17 12:19:37.211 D/LOGIN2: Attemtping to Login (2nd)
2021-07-17 12:19:37.212 D/LOGIN2: Successfully Logged in to user with ID = 1
2021-07-17 12:19:37.392 D/NEXTACTIVTY: Valid user ID - Username = fred password is password_for_fred
2021-07-17 12:19:37.745 D/NEXTACTIVITY: Closing Cursor in onDestroy method

Basically you just need the
cursor.getInt([column position])
or
cursor.getString([column position])
to retrieve the data from the columns in the database. I made an example I hope this helps you. I'm not very familiar with programming language some cases so I can't argue more.
public class User {
private int id;
private String name;
private String password;
private boolean isLogged = false;
public User() {
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public boolean isLogged() {
return isLogged;
}
public void setLogged(boolean x) {
this.isLogged = x;
}
}
Method to retrieve the Id requested you could just create a String or something..
public User checkLogin(String username, String password) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM user WHERE username=? AND password=? ", new String[] {username, password});
if (cursor.moveToFirst() || cursor.getCount() > 0) {
User user = new User();
user.setId(cursor.getInt(0));//if you created a primary key should be the first column
user.setLogged(true);
cursor.close();// * Closes the Cursor, releasing all of its resources and making it completely invalid.
db.close(); // * Releases a reference to the object, closing the object if the last reference* was released.
return user;
} else {
return null;
}
}

Related

Unable to save data to SQLite database

I'm developing a fitness tracker android app and have set up a SQLite database with 2 tables successfully. One table is for saving data about cardio exercises and one table is for saving data about weight lifting exercises. I'm able to save information to the cardio table (saved_workout_cardio) however, I can't seem to save anything to the weight lifting table (saved_workout_weights). I started off by coding the functionality for saving to 'saved_workout_cardio' table and once I had successfully got that working, I just copy and pasted the code and edited it to fit what was needed for saving to 'saved_workout_weights' table, however unfortunately it's not working and I'm puzzled as to why.
Below is the code from my databasehelper java class where I create the database as well as 2 methods, 1 for saving data to each table:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "FitnessTracker.db";
public static final String TABLE_WEIGHTS = "saved_workout_weights";
public static final String COL_1 = "ID";
public static final String COL_2 = "DATE";
public static final String COL_3 = "EXERCISE";
public static final String COL_4 = "WEIGHT";
public static final String COL_5 = "REPS";
public static final String COL_6 = "SETS";
public static final String TABLE_CARDIO = "saved_workout_cardio";
public static final String COL_1a = "ID";
public static final String COL_2a = "DATE";
public static final String COL_3a = "TIME";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_WEIGHTS + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,DATE TEXT,EXERCISE TEXT,WEIGHT INTEGER,REPS INTEGER)");
db.execSQL("create table " + TABLE_CARDIO + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,DATE TEXT,TIME INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_WEIGHTS);
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_CARDIO);
onCreate(db);
}
public boolean saveData (String date, String time) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2a, date);
contentValues.put(COL_3a, time);
long result = db.insert(TABLE_CARDIO, null, contentValues);
if(result == -1)
return false;
else
return true;
}
public boolean saveData2 (String date, String exercise, String weight, String reps, String sets) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues2 = new ContentValues();
contentValues2.put(COL_2, date);
contentValues2.put(COL_3, exercise);
contentValues2.put(COL_4, weight);
contentValues2.put(COL_5, reps);
contentValues2.put(COL_6, sets);
long result = db.insert(TABLE_WEIGHTS, null, contentValues2);
if(result == -1)
return false;
else
return true;
}
}
Now here's the relevant code from my 'Cardio' java class where I'm calling the method for saving data to the cardio table (this method works and I'm able to save data to the cardio table successfully:
public void saveCardioData () {
btnSaveCardio.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.saveData(txtDate.getText().toString(),
txtTimer.getText().toString() );
if(isInserted = true)
Toast.makeText(Cardio.this, "Workout saved", Toast.LENGTH_LONG).show();
else
Toast.makeText(Cardio.this, "Error saving workout", Toast.LENGTH_LONG).show();
}
}
);
}
Now here's the 'weights' java class where I call the method for saving data to the weights table. As you can see I have set up a toast message to appear if data is successfully inserted. Whenever I click to save the workout in my app the toast message tells me that the workout has been successfully saved however, when I check the weights table in my database no values have been saved.
public void saveWeightsData () {
btnSaveWeights.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.saveData2(exerciseVal.getText().toString(),
weightVal.getText().toString(),
repVal.getText().toString(),
setVal.getText().toString(),
dateVal.getText().toString() );
if(isInserted = true)
Toast.makeText(WeightsMain.this, "Workout saved", Toast.LENGTH_LONG).show();
else
Toast.makeText(WeightsMain.this, "Error saving workout", Toast.LENGTH_LONG).show();
}
}
);
}
Really confused as to why I'm having this problem, so if anyone can tell me why it would be greatly appreciated! :)
EDIT: I'm using Android Device Monitor within Android studio to pull the database from the android emulator's storage to my pc. I then use SQLite Manager firefox addon to check the 2 tables.
There's no SETS column in your table but you're trying to insert data to it. That won't work.
After adding the SETS column to the CREATE TABLE, you can uninstall your app to force onCreate() to execute again.

Singleton Instance returns null

In my application, I use the users password as the encryption key for encryption media. I am encrypting media using PBEWithMD5AndDES and this works fine with a password stored in shared preferences. Now to achieve a level of security I am removing the password from shared preferences and using a singleton that is only kept alive during the app session (as the app logs out automatically requiring entry of the password). Below is my singleton:
public class Credentials {
private static Credentials dataObject = null;
private Credentials() {
// left blank intentionally
}
public static Credentials getInstance() {
if (dataObject == null)
dataObject = new Credentials();
return dataObject;
}
private char[] user_password;
public char[] getUser_password() {
return user_password;
}
public void setUser_password(char[] user_password) {
this.user_password = user_password;
}
}
The password is zeroed out from memory if the app logs out, or is log out by the user or gets destroyed. However at times I am getting a null pointer when trying to retrieve the password.
char[] pswd = Credentials.getInstance().getUser_password();
What could be causing this? is there any other method I can use except a singleton?
Alternatively, you can store the password using built-in Sqlite db, though I'd still recommend you save it encrypted for max protection. You can do this in 4 steps:
2) Create an entity object to store the password:
public class Password {
int password_id; // will be auto-increamted
String password;
public Password(int password_id, String password) {
this.password_id = password_id;
this.password = password;
}
// getter/setters ...
}
2) Create an Sqlite utility object:
public class SQLiteDBAdapter {
protected static final String DATABASE_NAME = "mydb";
protected static final int DATABASE_VERSION = 1;
protected Context context;
protected static DatabaseHelper mDbHelper;
public static final String TABLE_PASSWORD = "tbl_password";
// columns
public static final String PASSWORD_ID = "_id";
public static final String PASSWORD = "password";
// create table string
private static final String CREATE_TABLE_PASSWORD =
"CREATE TABLE if not exists " + TABLE_PASSWORD + " ( " +
PASSWORD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
PASSWORD + " TEXT NOT NULL);";
public SQLiteDBAdapter(Context context) {
context = context.getApplicationContext();
}
public SQLiteDatabase openDb() {
if (mDbHelper == null) {
mDbHelper = new DatabaseHelper(mContext);
}
return mDbHelper.getWritableDatabase();
}
protected static class DatabaseHelper extends SQLiteOpenHelper {
// -------------------------------------------------------------------------------------------
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// -------------------------------------------------------------------------------------------
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_PASSWORD);
}
// -------------------------------------------------------------------------------------------
#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 routes");
onCreate(db);
}
}
}
3) Extend an Sqlite object to manipulate the table (CRUD operations):
public class PasswordDbAdapter extends SQLiteDBAdapter {
private SQLiteDatabase db;
// these are column corresponding indices
public static final int INDEX_PASSWORD_ID = 0; // an auto-increment
public static final int INDEX_PASSWORD = 1;
public PasswordDbAdapter(Context context) {
super(context);
}
public void addPassword(String password) {
db = openDb();
ContentValues values = new ContentValues();
values.put(PASSWORD, password);
db.insert(TABLE_PASSWORD, null, values);
}
public void updatePassword(String password) {
db = openDb();
ContentValues values = new ContentValues();
values.put(PASSWORD, password);
db.update(TABLE_PASSWORD, values, null);
}
public void deletePassword() {
db = openDb();
db.delete(TABLE_PASSWORD, null, null);
}
public boolean isEmpty() {
db = openDb();
boolean empty = true;
Cursor cur = db.rawQuery("SELECT COUNT(*) FROM " + TABLE_PASSWORD, null);
if (cur != null && cur.moveToFirst()) {
empty = (cur.getInt (0) == 0);
}
cur.close();
return empty;
}
public Password fetchPassword() { // ok because there's only one password record
db = openDb();
Cursor cursor = db.query(TABLE_PASSWORD, new String[]{PASSWORD_ID, PASSWORD},
null, null, null, null, null, null);
if (cursor != null &&
cursor.moveToFirst()) {
return new Password(
cursor.getString(INDEX_PASSWORD_ID),
cursor.getInt(INDEX_PASSWORD));
}
return null;
}
}
4) Finally, save/update/retrieve the password as desired:
public class MainActivity extends AppCompatActivity {
private PasswordDbAdapter passwordDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// initialize the password db
passwordDB = new PasswordDbAdapter(this);
// check if password record exists
if (passwordDB.isEmpty() {
// save a new copy
passwordDB.addPassword("the_password"); // more secure if it is saved encrypted
} else {
// update it
passwordDB.updatePassword("the_password");
}
}
...
public String fetchPassword() {
return passwordDB.fetchPassword(); // or first decrypt it, then return it
}
}

How to update an existing SQLite db table data with new android app update?

I recently launched an app on the android app store that contained a SQLite database.
I am now attempting to release an update of the app, and want to add more data into the existing database, however have come a bit unstuck. I have read answers on SO that outline making changes to the database itself, however I want my tables and columns to stay the same, only add new data in.
The data that i want to add to the database is pulled from CSV files in the Raw file, and originally loaded into the database when the user registers for the app.
I have a feeling I am going to need to implement the onUpgrade method, however should I be adding the new data from the CSV files in at that point as well? Is it a matter of simple updating the database version and using the onUpgrade to load the new data?
I am fairly new to SQLite DB, so any help would be hugely appreciated.
CourseDBHelper Code
public class CourseDBHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "CourseDB";
// Create two table names
private static final String TABLE_COURSES = "courses";
// Universities Table Columns names
private static final String COURSE_NAME = "Course_name";
private static final String UNI_NAME = "Uni_name";
private static final String COURSE_DURATION = "Duration";
private static final String COURSE_STUDY_MODE = "Study_mode";
private static final String COURSE_QUALIFICATION = "Qualification";
private static final String COURSE_ENTRY_STANDARDS = "Entry_standards";
private static final String COURSE_GRADUATE_PROSPECTS = "Graduate_prospects";
private static final String COURSE_STUDENT_SATISFACTION = "Student_satisfaction";
private String CREATE_COURSES_TABLE = "CREATE TABLE courses" +
"(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"Course_name TEXT NOT NULL," +
"Uni_name TEXT NOT NULL," +
"Duration TEXT NOT NULL," +
"Study_mode TEXT NOT NULL," +
"Qualification TEXT NOT NULL," +
"Entry_standards TEXT NOT NULL," +
"Graduate_prospects TEXT NOT NULL," +
"Student_satisfaction TEXT NOT NULL" +
");";
private static final String[] COLUMNS = {
COURSE_NAME,
UNI_NAME,
COURSE_DURATION,
COURSE_STUDY_MODE,
COURSE_QUALIFICATION,
COURSE_ENTRY_STANDARDS,
COURSE_GRADUATE_PROSPECTS,
COURSE_STUDENT_SATISFACTION
};
public CourseDBHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// TODO: REMOVED NOT NULL FROM EVERY COLUMN FOR TEST PURPOSES, WILL NEED TO BE READDED
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(CREATE_COURSES_TABLE);
}
public void deleteAll()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete("courses", null, null);
db.execSQL("delete from " + "courses");
db.close();
}
// Getting one course by course name and uni name
public Course getCourse(String courseName, String uniName) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_COURSES, COLUMNS, " Course_name = ? AND Uni_name = ?",
new String[]{courseName, uniName},
null,
null,
null,
null);
if (cursor != null)
cursor.moveToFirst();
Course course = new Course();
/*
System.out.println(cursor.getString(0));
System.out.println(cursor.getString(1));
System.out.println(cursor.getString(2));
System.out.println(cursor.getString(3));
System.out.println(cursor.getString(4));
System.out.println(cursor.getString(5));
System.out.println(cursor.getString(6));
*/
course.setCourseName(cursor.getString(0));
course.setUniversity(cursor.getString(1));
course.setCourseDuration(cursor.getString(2));
course.setStudyMode(cursor.getString(3));
course.setQualification(cursor.getString(4));
course.setEntryStandards(cursor.getString(5));
course.setGradProspects(cursor.getString(6));
course.setStudentSatisfaction(cursor.getString(7));
return course;
}
public void addCourse(Course course)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COURSE_NAME, course.getCourseName());
values.put(UNI_NAME, course.getUniversity());
values.put(COURSE_DURATION, course.getCourseDuration());
values.put(COURSE_STUDY_MODE, course.getStudyMode());
values.put(COURSE_QUALIFICATION, course.getQualification());
values.put(COURSE_ENTRY_STANDARDS, course.getEntryStandards());
values.put(COURSE_GRADUATE_PROSPECTS, course.getGradProspects());
values.put(COURSE_STUDENT_SATISFACTION, course.getStudentSatisfaction());
db.insert(TABLE_COURSES,
null, //nullColumnHack
values);
db.close();
}
public ArrayList<Course> getAllCourses()
{
ArrayList<Course> courses = new ArrayList<>();
// 1. build the query
String query = "SELECT * FROM " + TABLE_COURSES;
// 2. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
// 3. go over each row, build course and add it to list
Course course;
if(cursor.moveToFirst()){
cursor.moveToNext();
do{
course = new Course();
course.setCourseName(cursor.getString(1));
course.setUniversity(cursor.getString(2));
course.setCourseDuration(cursor.getString(3));
course.setStudyMode(cursor.getString(4));
course.setQualification(cursor.getString(5));
course.setEntryStandards(cursor.getString(6));
course.setGradProspects(cursor.getString(7));
course.setStudentSatisfaction(cursor.getString(8));
// Add course to courses list
courses.add(course);
} while(cursor.moveToNext());
}
// return courses
return courses;
}
public int getDBCount()
{
SQLiteDatabase db = this.getWritableDatabase();
String count = "SELECT count(*) FROM courses";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
return icount;
}
public void deleteCourse(Course course) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. delete
db.delete("courses", //table name
"Course_name = ? AND Uni_name = ?", // selections
new String[] { course.getCourseName(), course.getUniversity() }); //selections args
// 3. close
db.close();
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
Method that loads data from CSV file to SQlite DB
public void populateCourseDatabase(int id) {
// NOW POPULATE THE COURSE DATABASE FILE
inputStream = getResources().openRawResource(R.raw.coursesone);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String word;
String cvsSplitBy = ",";
try{
while((word = reader.readLine()) != null){
Log.d(TAG, "constructing Course object from: " + word);
String[] segment = word.split(cvsSplitBy);
Course course = new Course();
course.setCourseName(segment[0]);
course.setUniversity(segment[1]);
course.setCourseDuration(segment[2]);
course.setStudyMode(segment[3]);
course.setQualification(segment[4]);
course.setEntryStandards(segment[5]);
course.setGradProspects(segment[6]);
course.setStudentSatisfaction(segment[7]);
myCourseDBHelper.addCourse(course);
progressBar.setProgress(count);
count = count + 1;
System.out.println("Sucessfully added: " + course.toString());
}
}
catch(IOException e1){
e1.printStackTrace();
System.out.println("SOMETHING WENT WRONG");
}
}
SQLiteOpenHelper onCreate() and onUpgrade() callbacks are invoked when the database is actually opened, for example by a call to getWritableDatabase().onCreate() is only run when the database file did not exist and was just created. onUpgrade() is only called when the database file exists but the stored version number is lower than requested in constructor.Increment the database version so that onUpgrade() is invoked.
Example pseudo code below
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch(oldVersion) {
case 1:
//upgrade logic from version 1 to 2
case 2:
//upgrade logic from version 2 to 3
case 3:
//upgrade logic from version 3 to 4
break;
default:
throw new IllegalStateException(
"onUpgrade() with unknown oldVersion " + oldVersion);
}
}

How to find uniqueness of data field (eg. Email) every time it is inserted in the database?

I'm developing an android app, in which users enter their name, surname, email and password for registration purpose. This entry process works perfectly fine, now I want to check every time, when a user enters his/her email, that the entered email is exists already in my database or not.
for this I tried the following method in my DBHelper class:
public String Exist(String user) {
String username="";
SQLiteDatabase db = this.getReadableDatabase();
try {
Cursor c = db.query(TABLE_NAME, null, "COL_4" + "=?", new String[]{String.valueOf(user)},null, null, null);
if (c == null) {
return username;
}
else {
c.moveToFirst();
username = c.getString(c.getColumnIndex("COL_4"));
}
}
catch(Exception e){
}
return username;
}
here TABLE_NAME is the name of my table, COL_4 is the column which contains emails of the users and I'm passing the entered string (email) entered by user as parameter of this method.
I'm calling this method from my main activity class as following:
String myUser = email.getText().toString();
String storedUser = myDb.Exist(myUser);
//If Username exist
if (myUser.equals(storedUser)) {
Toast.makeText(getApplicationContext(), "Username already exist!", Toast.LENGTH_SHORT).show();
return;
}
here I'm storing entered email in myUser variable.
The problem is that even the email is entered same as previously entered, it allows to insert the data in database. That means every time the exception occurs and "" is returned. What is error in Exists method?
Okay, I found answer by myself!
I used following code in DBHelper Class:
public boolean Exists(String user){
Cursor res = getAllData();
int flag=0;
while (res.moveToNext()){
String email =res.getString(3);
if(email.equals(user)){
flag++;
}
}
if(flag==0){
return false;
}
else {
return true;
}
}
and following code in my main activity:
//If Username exist
if (myDb.Exists(email.getText().toString())) {
showMessage("Error :(","This username is already exists.");
return;
}
You Can get that in the query itself
*SELECT * FROM TABLE_NAME WHERE Col = 'user email id';*
If you pass the Table name and column name correctly, it will return the cursor. Below I have put a method which will return true if the email id exists in the table.
public boolean isEmailExists(String emailAddress) {
SQLiteDatabase db =null; DatabaseHelper.getInstance(context).getReadableDatabase();
Cursor cursor = null;
String selectQuery = "SELECT * FROM Table_name WHERE COLUMN_NAME ='emailAddress';";
cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.getCount() > 0) {
return true;
}
return false;
}
As I mentioned earlier appropriate Table name and column name has been given correctly.

My android app stop I donĀ“t know how get a value of SQLite

I'm new programmer, I need just one value ("IdUser") of SQLite and parse to String variable, but I don't have any idea to catch it and return that value. My app stopped because of this.
Activity.java
public void onClick(View arg0) {
String LOGIN2 ="Users";
String eti = loginDataBaseAdapter.CheckEtiqueta(LOGIN2);
Toast.makeText(getApplicationContext(), eti, Toast.LENGTH_LONG).show();
}
UsersDatabaseHelper.java
public String CheckEtiqueta(String LOGIN2) {
Cursor c = db.rawQuery("SELECT * FROM "+LOGIN2+" WHERE IdUser = 20 ORDER BY IdUser LIMIT1", null);
while (c.moveToNext()) {
//Sample operation with the Database
if (c.getString(c.getColumnIndex("IdUser"))!=null) {
LOGIN2=c.getString(c.getColumnIndex("IdUser"));
return LOGIN2;
}
}
return LOGIN2;
}
Thanks
First of all please correct your SQL query. and why you are returning the same variable that function received. You also havn't opened your database.
To open database.
public void openDatabase()
{
database = dbHelper.getWritableDatabase();
}
And To close :
public void closeDatabase()
{
if (database != null && database.isOpen())
database.close();
}
Add openDatabase() call before Cursor statement and Don't forget to closeDatabase() once you done with it.
EDIT :
Ideal Code :
public User getUserByID(int userID)
{
openDatabase();
Cursor userByID= database.rawQuery("select * from UsersTable where UserID = " + userID, null);
User user = new User();
userByID.moveToFirst();
user.setName(userByID.getString(userByID.getColumnIndex("UserName")));
userByID.close();
closeDatabase();
return User;
}

Categories