I have created 2 tables in a db. 1 is working fine. TABLE_NAME2 is giving error while inserting data in it saying Column Email is not found.
DatabaseHelper.java:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME2 + "("
+ USER_NAME + "TEXT,"
+ USER_EMAIL + "TEXT,"
+ USER_MOBILE + "TEXT, "
+ USER_PASS + "TEXT)");
db.execSQL("CREATE Table " + TABLE_NAME1 + "("// + COL1 + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COL2 + " TEXT,"
+ COL3 + " TEXT,"
+ COL4 + " TEXT,"
+ COL5 + " TEXT,"
+ COL6 + " TEXT,"
+ COL7 + " TEXT)");
}
public boolean insertSignupDataDB(String name, String email, String mobile, String pass){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(USER_NAME, name);
contentValues.put(USER_EMAIL, email);
contentValues.put(USER_MOBILE, mobile);
contentValues.put(USER_PASS, pass);
long result = db.insert(TABLE_NAME2, null, contentValues);
if (result==-1){
return false;
}
else
return true;
}
Log:
(1) table signup has no column named EMAIL
06-08 21:00:51.306 15019-15019/com.mgm.manish.trekcompanion E/SQLiteDatabase: Error inserting EMAIL=abc NAME=abc PASSWORD=abc MOBILE=abc
android.database.sqlite.SQLiteException: table signup has no column named EMAIL (code 1): , while compiling: INSERT INTO signup(EMAIL,NAME,PASSWORD,MOBILE) VALUES (?,?,?,?)
Please solve this
From this page I am sending data to DatabaseHelper Class to insert data.
It shows the toast "successful signup", but is showing error in Logs, and also it is not navigating to LoginActivity class. it is navigating to MainActivity.
Even else part is not working. when i put different passwords it gives error app stopped.
if(etSignPass.getText().toString().equals(etSignConPass.getText().toString())){
boolean queryResult = dbHelper.insertSignupDataDB(etSignName.getText().toString(),
etSignEmail.getText().toString(), etSignMobile.getText().toString(), etSignPass.getText().toString());
if(queryResult=true){
Toast.makeText(SignUp.this, "Successfully Signed up", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
navigateUpTo(new Intent(SignUp.this,LoginActivity.class));
}
}
else{
Toast.makeText(SignUp.this, "Error", Toast.LENGTH_SHORT).show();
}
}
else{
etSignConPass.setBackgroundColor(Color.RED);
onClicSignUp();
}
}
This is complete code of DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "abc.db";
public static final String TABLE_NAME1 = "table1";
public static final String COL2 = "col1";
public static final String COL3 = "Date";
public static final String COL4 = "Cost";
public static final String COL5 = "loc1";
public static final String COL6 = "loc2";
public static final String COL7 = "Description";
public static final String TABLE_NAME2 = "signup";
public static final String USER_NAME = "NAME";
public static final String USER_EMAIL = "EMAIL";
public static final String USER_MOBILE = "MOBILE";
public static final String USER_PASS = "PASSWORD";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME2 + "("
+ USER_NAME + "TEXT,"
+ USER_EMAIL + "TEXT,"
+ USER_MOBILE + "TEXT, "
+ USER_PASS + "TEXT)");
db.execSQL("CREATE Table " + TABLE_NAME1 + "("// + COL1 + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COL2 + " TEXT,"
+ COL3 + " TEXT,"
+ COL4 + " TEXT,"
+ COL5 + " TEXT,"
+ COL6 + " TEXT,"
+ COL7 + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME1);
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME2);
onCreate(db);
}
public boolean insertHomeDataDB(String locName, String date, String cost, String startLoc, String endLoc, String description){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, locName);
contentValues.put(COL3, date);
contentValues.put(COL4, cost);
contentValues.put(COL5, startLoc);
contentValues.put(COL6, endLoc);
contentValues.put(COL7, description);
//contentValues.put(COL8, userId);
long result = db.insert(TABLE_NAME1, null, contentValues);
if (result==-1){
return false;
}
else
return true;
}
public boolean insertSignupDataDB(String name, String email, String mobile, String pass){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(USER_NAME, name);
contentValues.put(USER_EMAIL, email);
contentValues.put(USER_MOBILE, mobile);
contentValues.put(USER_PASS, pass);
long result = db.insert(TABLE_NAME2, null, contentValues);
if (result==-1){
return false;
}
else
return true;
}
public Cursor getAllHomeData(SQLiteDatabase db){
Cursor res;
String[] projection = {COL2,COL3,COL4};
res = db.query(TABLE_NAME1,projection,null,null,null,null,null);
return res;
}
public Cursor getAllProfileData(SQLiteDatabase db){
Cursor res;
String[] projection={USER_NAME,USER_EMAIL,USER_MOBILE,USER_PASS};
res = db.query(TABLE_NAME2, projection,null,null,null,null,null);
return res;
}
}
Related
I am creating a login app, where a user has an username and a password. I want to save sign up data in my database, but when I want to get access to the elements from database, no one seems to be saved ( it has no user saved in db). I suppose the error comes from db implementation. Any idea?
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String TABLE_NAME = "user_table";
public static final String COL1 = "ID";
public static final String COL2 = "user_username";
public static final String COL3 = "user_password";
public DataBaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + "( " + COL2 + " TEXT," +
COL3 + "TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void add(String name, String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, name);
contentValues.put(COL3, password);
db.insert(TABLE_NAME, null, contentValues);
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT *FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
LOGIN Activity:
public void loginSeach(View view) {
EditText password_editText = (EditText) findViewById(R.id.editText_password);
EditText username_editText = (EditText) findViewById(R.id.editText_username);
String currUserName = username_editText.getText().toString();
String currPassWord = password_editText.getText().toString();
DataBaseHelper db = new DataBaseHelper(this);
Cursor data = db.getData();
int Number = 0;
while (data.moveToNext()) {
Number ++;
String userName = data.getString(1);
String passWord = data.getString(2);
}
Toast.makeText(this, Integer.toString(Number), Toast.LENGTH_SHORT).show();
}
Sign up activity:
public void createAccount(View view) {
EditText usernameEditText = (EditText) findViewById(R.id.editText_createUsername);
EditText passwordEditText = (EditText) findViewById(R.id.editText_createPassword);
String userName = usernameEditText.getText().toString();
String passWord = passwordEditText.getText().toString();
dataBaseHelper.add(userName, passWord);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
This statement in onCreate():
String createTable = "CREATE TABLE " + TABLE_NAME + "(" + COL2 + " TEXT," + COL3 + "TEXT)";
created a table without an ID column.
Uninstall the app from the emulator/device, change your code to this:
String createTable = "CREATE TABLE " + TABLE_NAME + "(" + COL1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 + " TEXT," + COL3 + " TEXT)";
and rerun the app.
I have a local database in my app for storing user profiles from input fields. I have created the database using SQLiteOpenHelper class but after running my app, this error appears. I have been through the DatabaseHelper class but can't find what's wrong with it. I hope someone points out my mistake. Thanks.
my db class file here:
public class DBHelper {
private static final String DATABASE_NAME = "UsersDemo.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "profileInfo";
private static final String COL_ID = "databaseId";
public static final String COL_USER_ID = "userId";
public static final String COL_FULL_NAME = "fullName";
public static final String COL_GENDER = "gender";
public static final String COL_DOB = "DOB";
public static final String COL_MOBILE_NUM = "mobileNum";
public static final String COL_OCCUPATION = "occupation";
public static final String COL_ORGANIZATION = "organization";
//private static final String COL_PROFILE_PHOTO = "profilePhoto";
private Context mCtx;
private DatabaseManager databaseManager;
private SQLiteDatabase db;
public DBHelper(Context context){
this.mCtx = context;
databaseManager = new DatabaseManager(mCtx);
}
public DBHelper open() throws SQLException{
db = databaseManager.getWritableDatabase();
return this;
}
public void close(){
databaseManager.close();
}
public boolean saveInputField(TingTingUser user){
SQLiteDatabase userDb = databaseManager.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_FULL_NAME, user.getDisplayName());
values.put(COL_USER_ID, user.getUserId());
values.put(COL_GENDER, user.getGender());
values.put(COL_DOB, user.getDob());
values.put(COL_MOBILE_NUM, user.getMobileNumber());
values.put(COL_ORGANIZATION, user.getOrganization());
values.put(COL_OCCUPATION, user.getOccupation());
long result = userDb.insert(TABLE_NAME, null, values);
userDb.close();
if (result == -1){
return false;
} else {
return true;
}
}
public TingTingUser getCurrentUser(int id){
SQLiteDatabase currDB = databaseManager.getWritableDatabase();
Cursor cursor = currDB.query(true, TABLE_NAME, new String[]{COL_ID, COL_USER_ID, COL_FULL_NAME, COL_GENDER, COL_DOB, COL_MOBILE_NUM, COL_OCCUPATION, COL_ORGANIZATION}, COL_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null && cursor.moveToFirst()){
TingTingUser user = new TingTingUser(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7));
return user;
}
return null;
}
public void saveCameraImage(byte[] imageBytes){
SQLiteDatabase camDb = databaseManager.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put(COL_PROFILE_PHOTO, imageBytes);
camDb.insert(TABLE_NAME, null, contentValues);
}
public void saveGalleryImage(byte[] imageBytes){
ContentValues contentValues = new ContentValues();
//contentValues.put(COL_PROFILE_PHOTO, imageBytes);
db.insert(TABLE_NAME, null, contentValues);
}
public class DatabaseManager extends SQLiteOpenHelper {
public DatabaseManager(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String db_create = "Create Table " + TABLE_NAME + " ("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_USER_ID + " TEXT, "
+ COL_FULL_NAME + " TEXT, "
+ COL_GENDER + " TEXT, "
+ COL_DOB + " TEXT, "
+ COL_MOBILE_NUM + " TEXT, "
+ COL_OCCUPATION + " TEXT, "
+ COL_ORGANIZATION + " TEXT, ";
//+ COL_PROFILE_PHOTO + " BLOB NOT NULL );";
sqLiteDatabase.execSQL(db_create);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(sqLiteDatabase);
}
}
}
The error occurs in my MainActivity when I call saveInputField() method of DBHelper, shown below:
JsonObjectRequest otpObjectRequest = new JsonObjectRequest(Request.Method.POST, Constants.TING_VERIFY_OTP_ENDPOINT, verifyOTPObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("OTPDialogFragment", "OTP Verification Response is: \t" + response.toString());
Log.d("OTPDialogFragment", "OTP Verified Successfully");
try {
JSONObject verifyObject = new JSONObject(response.toString());
JSONObject userObject = verifyObject.getJSONObject("user");
userId = userObject.getString("_id");
Log.d(TAG, "Retrieved user id is:\t" + userId);
TingTingUser user = new TingTingUser();
user.setDisplayName(fullName);
user.setMobileNumber(num);
user.setGender(genderVal);
user.setDob(dob);
user.setOccupation("default");
user.setOrganization("default");
user.setUserId(userId);
if (!TextUtils.isEmpty(fullName) && !TextUtils.isEmpty(genderVal) && !TextUtils.isEmpty(dob) && !TextUtils.isEmpty(userId)){
if (dbHelper.saveInputField(user) == true){ // error occurs here
Toast.makeText(getContext(), "Saved User", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Save Failed", Toast.LENGTH_SHORT).show(); // Toast shows cos save failed, dont know why
}
}
Sorry guys, my mainactivity is too long, only showed what is necessary.
Error message in logcat:
android.database.sqlite.SQLiteException: near ",": syntax error (code 1): , while compiling: Create Table profileInfo (databaseId INTEGER PRIMARY KEY AUTOINCREMENT, userId TEXT, fullName TEXT, gender TEXT, DOB TEXT, mobileNum TEXT, occupation TEXT, organization TEXT,
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com.billionusers.tingting.db.DBHelper$DatabaseManager.onCreate(DBHelper.java:131)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.billionusers.tingting.db.DBHelper.saveInputField(DBHelper.java:53)
at com.billionusers.tingting.activities.SignUpActivity$OTPDialogFragment$6.onResponse(SignUpActivity.java:466)
at com.billionusers.tingting.activities.SignUpActivity$OTPDialogFragment$6.onResponse(SignUpActivity.java:443)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
From the logcat
near ",": syntax error (code 1): , while compiling: Create Table profileInfo (databaseId INTEGER PRIMARY KEY AUTOINCREMENT, userId TEXT, fullName TEXT, gender TEXT, DOB TEXT, mobileNum TEXT, occupation TEXT, organization TEXT,
and DBHelper.onCreate
String db_create = "Create Table " + TABLE_NAME + " ("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_USER_ID + " TEXT, "
+ COL_FULL_NAME + " TEXT, "
+ COL_GENDER + " TEXT, "
+ COL_DOB + " TEXT, "
+ COL_MOBILE_NUM + " TEXT, "
+ COL_OCCUPATION + " TEXT, "
+ COL_ORGANIZATION + " TEXT, ";
//+ COL_PROFILE_PHOTO + " BLOB NOT NULL );";
sqLiteDatabase.execSQL(db_create);
Your create statement is invalid because you have put into comments the last line so it terminates in + COL_ORGANIZATION + " TEXT, "; which is not correct. The ending should be:
+ COL_ORGANIZATION + " TEXT ); ";
Can anyone see what is wrong with this code please, this is the error given:
Caused by: android.database.sqlite.SQLiteException: near ")": syntax error (code 1): , while compiling: CREATE TABLE scores(_id INTEGER PRIMARY KEY AUTOINCREMENT , scoreName TEXT , );
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "scores.db";
public static final String TABLE_SCORES = "scores";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_SCORENAME = "scoreName";
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_SCORES + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT " +
COLUMN_SCORENAME + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_SCORES);
onCreate(db);
}
public void addScore(Scores score) {
ContentValues values = new ContentValues();
values.put(COLUMN_SCORENAME, score.get_scoreName());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_SCORES, null, values);
db.close();
}
public void deleteScore(String scoreName) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_SCORES + "WHERE " + COLUMN_SCORENAME + "=\"" + scoreName + "\";");
}
public String databaseToString() {
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_SCORES + "WHERE 1";
//Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
//move to first row in your results
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("scoreName")) != null) {
dbString += c.getString(c.getColumnIndex("scoreName"));
dbString += "\n";
}
}
db.close();
return dbString;
}
}
Seems problem in Query for creating table (comma is missing after AUTOINCREMENT). Try this
db.execSQL("CREATE TABLE " + TABLE_SCORES + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_SCORENAME + " TEXT" + ");");
I try to create a table in my database. I am using this framework: http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
I have edited the code for a bit. In the code below, a table login is created(correct me if im wrong). But I cant see any table named login in the database.
Here is the complete code:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "android_api";
// Login table name
private static final String TABLE_LOGIN = "login";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
private static final String KEY_TOTAL_USAGE = "total_usage";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT,"
+ KEY_TOTAL_USAGE + " TEXT);";
db.execSQL(CREATE_LOGIN_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name, String email, String uid, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_UID, uid); // Email
values.put(KEY_CREATED_AT, created_at); // Created At
// values.put(KEY_TOTAL_USAGE, total_usage); // Total_usage
// Inserting Row
db.insert(TABLE_LOGIN, null, values);
db.close(); // Closing database connection
}
/**
* Storing user details in database
* */
public void updateUser(String email, String total_usage) {
String selectQuery = "UPDATE login SET total_usage = 132 WHERE email = 'sampleMail'";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(selectQuery);
// Cursor cursor = db.rawQuery(selectQuery, null);
// System.out.print("Count"+cursor.getCount());
/*
SQLiteDatabase db = this.getWritableDatabase();
db.rawQuery("UPDATE login SET total_usage = 132 WHERE email = 'sampleMail'", null);
db.rawQuery("UPDATE login SET total_usage = 132 WHERE email = 'sampleMail'", null);
db.setTransactionSuccessful();
db.close(); */
// db.rawQuery("UPDATE "+ TABLE_LOGIN + " SET "+ KEY_TOTAL_USAGE +" = " + total_usage + " WHERE " + KEY_EMAIL + " = '" + email + "'", null);
// db.rawQuery("UPDATE "+ TABLE_LOGIN + " SET "+ KEY_TOTAL_USAGE +" = " + total_usage + " WHERE " + KEY_EMAIL + " = '" + email + "'", null);
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(3));
user.put("created_at", cursor.getString(4));
}
cursor.close();
db.close();
// return user
return user;
}
/**
* Getting user login status
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
/**
* Re crate database
* Delete all tables and create them again
* */
public void resetTables(){
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_LOGIN, null, null);
db.close();
}
}
This code(see below) from above creates the table login, right?
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT,"
+ KEY_TOTAL_USAGE + " TEXT);";
db.execSQL(CREATE_LOGIN_TABLE);
}
So my question is: why there is no table called login? Or am I misinterpreting something?
If I am doing something wrong, could someone help me solving it?
The application runs correctly(without crashes etc), there is no output at the logcat
Thanks in advance
I wrote a simple database helper class to make access to the DB from multiple activities more clean.
Here's the class:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "name";
private static final String TABLE_SCORES = "scores";
private static final String KEY_ID = "id";
private static final String KEY_SCORE = "score";
private static final String KEY_DATE = "date";
SQLiteDatabase database;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
database = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase database) {
String CREATE_SCORES_TABLE = "CREATE TABLE " + TABLE_SCORES + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_SCORE + " INTEGER,"
+ KEY_DATE + " TEXT" + ")";
database.execSQL(CREATE_SCORES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
database.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORES);
onCreate(database);
}
void addScore(int score){
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy", Locale.US);
String currentDateandTime = dateFormat.format(new Date());
ContentValues values = new ContentValues();
values.put(KEY_SCORE, score);
values.put(KEY_DATE, currentDateandTime);
database.insert(TABLE_SCORES, null, values);
//database.close();
}
void delete(){
database.delete(TABLE_SCORES, null, null);
}
public List<Score> getAllScores(){
List<Score> scoresList = new ArrayList<Score>();
String selectQuery = "SELECT * FROM " + TABLE_SCORES + " ORDER BY " + KEY_SCORE +" DESC LIMIT 10";
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
do{
Score score = new Score();
score.setId(Integer.parseInt(cursor.getString(0)));
score.setScore(Integer.parseInt(cursor.getString(1)));
score.setDate(cursor.getString(2));
scoresList.add(score);
} while (cursor.moveToNext());
}
return scoresList;
}
public int getHighscore() {
String selectQuery = "SELECT " + KEY_SCORE + " FROM " + TABLE_SCORES + " ORDER BY " + KEY_SCORE +" DESC LIMIT 1";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
return cursor.getInt(0);
}
else return 0;
}
public int getLastScoreID(){
String selectQuery = "SELECT " + KEY_ID + " FROM " + TABLE_SCORES + " ORDER BY " + KEY_ID + " DESC LIMIT 1";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
return cursor.getInt(0);
}
else return -1;
}
public int getLastScoreValue(){
String selectQuery = "SELECT " + KEY_SCORE + " FROM " + TABLE_SCORES + " ORDER BY " + KEY_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
return cursor.getInt(0);
}
else return -1;
}
}
Here's the question:
where should I put database.close()? There's no such thing like destructor in Java (I really don't want to finalize() this one...).
Best regards.
Override the close() method of the SQLiteOpenHelper class
#Override
public synchronized void close() {
database.close();
super.close();
}