Connecting my app to a SQLite database - how to? - java

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.

Related

multiple tables in android

I want to use two tables in my SQLite database but when I try to read the second table my app crashes.
I have a table for the items in a storage and another table for the employees of the storage.
Here is my database class:
public class Database extends SQLiteOpenHelper {
protected static final String DATABASE_NAME = "Storage";
protected static final String KEY_ID = "id";
protected static final String KEY_DESCRIPTION = "description";
protected static final String KEY_CATEGORY = "category";
protected static final String KEY_ORIGIN = "origin";
protected static final String KEY_DATE = "date";
protected static final String KEY_BRAND = "brand";
protected static final String TAB_NAME = "items";
protected static final String KEY_ID2 = "id2";
protected static final String KEY_SURNAME = "surname";
protected static final String KEY_NAME = "name";
protected static final String KEY_USERNAME = "username";
protected static final String KEY_PASSWORD = "password";
protected static final String TAB_NAME2 = "employees";
protected static final int VERSION = 1;
public Database(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TAB_NAME + " ("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_DESCRIPTION + " TEXT, "
+ KEY_CATEGORY + " TEXT, "
+ KEY_ORIGIN + " TEXT, "
+ KEY_DATE + " TEXT, "
+ KEY_BRAND + " TEXT)";
String CREATE_DIPENDENTI_TABLE = "CREATE TABLE " + TAB_NAME2 + " ("
+ KEY_ID2 + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_SURNAME + " TEXT, "
+ KEY_NAME + " TEXT, "
+ KEY_USERNAME + " TEXT, "
+ KEY_PASSWORD + " TEXT)";
db.execSQL(CREATE_ITEMS_TABLE);
db.execSQL(CREATE_DIPENDENTI_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TAB_NAME);
db.execSQL("DROP TABLE IF EXISTS " + TAB_NAME2);
this.onCreate(db);
}
public void Add(String des, String cat, String pro, String data, String brand) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_DESCRIPTION, des);
contentValues.put(KEY_CATEGORY, cat);
contentValues.put(KEY_ORIGIN, pro);
contentValues.put(KEY_DATE, data);
contentValues.put(KEY_BRAND, brand);
sqLiteDatabase.insert(TAB_NAME,null, contentValues);
sqLiteDatabase.close();
}
public void Add(String cog, String nom, String user, String pass) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_SURNAME, cog);
contentValues.put(KEY_NAME, nom);
contentValues.put(KEY_USERNAME, user);
contentValues.put(KEY_PASSWORD, pass);
sqLiteDatabase.insert(TAB_NAME2,null, contentValues);
sqLiteDatabase.close();
}
public Cursor getInfo() {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM " + TAB_NAME + ";";
return sqLiteDatabase.rawQuery(query, null);
}
public ArrayList getInfoDip() {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
ArrayList<String> al=new ArrayList<>();
Cursor cursor= sqLiteDatabase.rawQuery("SELECT * FROM " +TAB_NAME2, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
al.add(cursor.getString(cursor.getColumnIndex("surname")));
al.add(cursor.getString(cursor.getColumnIndex("name")));
al.add(cursor.getString(cursor.getColumnIndex("username")));
al.add(cursor.getString(cursor.getColumnIndex("password")));
cursor.moveToNext();
}
return al;
}
public void Modify(int cod,String des, String cat, String pro, String dat, String bran){
SQLiteDatabase db = this.getWritableDatabase();
if(!des.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET description = "+"'"+des+"' "+ "WHERE id = "+"'"+cod+"'");
if(!cat.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET categoria = "+"'"+cat+"' "+ "WHERE id = "+"'"+cod+"'");
if(!pro.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET origin = "+"'"+pro+"' "+ "WHERE id = "+"'"+cod+"'");
if(!dat.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET date = "+"'"+dat+"' "+ "WHERE id = "+"'"+cod+"'");
if(!bran.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET brand = "+"'"+bran+"' "+ "WHERE id = "+"'"+cod+"'");
}
public void Modify(int cod, String cog, String nom, String user, String pass){
SQLiteDatabase db = this.getWritableDatabase();
if(!cog.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET surname = "+"'"+cog+"' "+ "WHERE id2 = "+"'"+cod+"'");
if(!nom.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET name = "+"'"+nom+"' "+ "WHERE id2 = "+"'"+cod+"'");
if(!user.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET username = "+"'"+user+"' "+ "WHERE id2 = "+"'"+cod+"'");
if(!pass.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET password = "+"'"+pass+"' "+ "WHERE id2 = "+"'"+cod+"'");
}
public void Delete(int cod){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+TAB_NAME+" WHERE id= "+"'"+cod+"'");
}
public void DeleteDip(int cod){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+TAB_NAME2+" WHERE id2= "+"'"+cod+"'");
}
public Cursor Search(int cod){
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM " + TAB_NAME + " WHERE id = "+"'"+cod+"';";
return sqLiteDatabase.rawQuery(query, null);
}
public Cursor Search(String des){
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM " + TAB_NAME + " WHERE description = "+"'"+des+"';";
return sqLiteDatabase.rawQuery(query, null);
}
public void DeleteAll() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from " + TAB_NAME);
}
}
and here is the activity where I try to get the ArrayList with the data:
private Database db= new Database(this);
private ArrayList<String> al=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
db.Add("admin","admin","admin","admin");
al.addAll(db.getInfoDip());
But when I try to put the data in the ArrayList the app crashes. Can anyone help me out?
Well so far, how I learned that the best practice for formating queries is to use String.format function. Here your example:
String query = "SELECT * FROM " + TAB_NAME + ";";
Best practice:
String query = String.format("SELECT * FROM %s", TAB_NAME);
So let's get to the getInfoDip method, you should try this:
public List<ContentValues> getInfoDip() {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
String query = String.format("SELECT * FROM %s", TAB_NAME2);
Cursor res = db.rawQuery(query, null);
res.moveToFirst();
List<ContentValues> list = new ArrayList<>(res.getCount());
while (!res.isAfterLast()){
String surname = res.getString(res.getColumnIndex(KEY_SURNAME));
String name = res.getString(res.getColumnIndex(KEY_NAME));
String username = res.getString(res.getColumnIndex(KEY_USERNAME));
String password = res.getString(res.getColumnIndex(KEY_PASSWORD));
list.add(new ContentValues(surname, name, username, password));
res.moveToNext();
}
return list;
}
Here is my whole SQLite test program, check out maybe it helps you:
package com.example.vezba09;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class Database extends SQLiteOpenHelper {
private static final String DATABASE_FILE_NAME = "contact_database";
public Database(#Nullable Context context) {
super(context, DATABASE_FILE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = String.format(
"CREATE TABLE IF NOT EXISTS %s (%s INTEGER PRIMARY KEY AUTOINCREMENT, %s TEXT, %s TEXT, %s TEXT)",
ContactModel.TABLE_NAME,
ContactModel.COLUMN_CONTACT_ID,
ContactModel.COLUMN_CONTACT_NAME,
ContactModel.COLUMN_CONTACT_EMAIL,
ContactModel.COLUMN_CONTACT_PHONE
);
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
String query = String.format("DROP TABLE IF EXISTS %s", ContactModel.TABLE_NAME);
db.execSQL(query);
onCreate(db);
}
//Dodavanje kontakta
public void addContact(String name, String email, String phone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ContactModel.COLUMN_CONTACT_NAME, name);
cv.put(ContactModel.COLUMN_CONTACT_EMAIL, email);
cv.put(ContactModel.COLUMN_CONTACT_PHONE, phone);
db.insert(ContactModel.TABLE_NAME, null, cv);
}
//Izmena
public void editContact(int contactId, String name, String email, String phone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ContactModel.COLUMN_CONTACT_NAME, name);
cv.put(ContactModel.COLUMN_CONTACT_EMAIL, email);
cv.put(ContactModel.COLUMN_CONTACT_PHONE, phone);
db.update(ContactModel.TABLE_NAME,
cv,
ContactModel.COLUMN_CONTACT_ID + "=?",
new String[]{String.valueOf(contactId)});
}
public int deleteContact(int contactId) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(ContactModel.TABLE_NAME,
ContactModel.COLUMN_CONTACT_ID + "=?",
new String[]{String.valueOf(contactId)});
}
public ContactModel getContactById(int contactId) {
SQLiteDatabase db = this.getReadableDatabase();
String query = String.format("SELECT * FROM %s WHERE %s = ?",
ContactModel.TABLE_NAME,
ContactModel.COLUMN_CONTACT_ID);
Cursor res = db.rawQuery(query, new String[] {String.valueOf(contactId)});
if(res.moveToFirst()) {
String name = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_NAME));
String email = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_EMAIL));
String phone = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_PHONE));
return new ContactModel(contactId, name, email, phone);
}
else {
return null;
}
}
public List<ContactModel> getAllContacts() {
SQLiteDatabase db = this.getReadableDatabase();
String query = String.format("SELECT * FROM %s", ContactModel.TABLE_NAME);
Cursor res = db.rawQuery(query, null);
res.moveToFirst();
List<ContactModel> list = new ArrayList<>(res.getCount());
while(!res.isAfterLast()) {
int contactId = res.getInt(res.getColumnIndex(ContactModel.COLUMN_CONTACT_ID));
String name = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_NAME));
String email = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_EMAIL));
String phone = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_PHONE));
list.add(new ContactModel(contactId, name, email, phone));
res.moveToNext();
}
return list;
}
}
Try this and feel free to ask more questions :)
Best regards, Sanady

can not Creating tables in sqlite database on android

I can not create a table. It shows that the database is created and I can also insert a row, but the table is not created.
public class DatabaseOperations extends SQLiteOpenHelper {
public static final int Database_version = 2;
public static final String Tag = DatabaseOperations.class.getSimpleName();
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.USER_ID + " INTEGER PRIMARY KEY," +
TableData.TableInfo.USER_PASS +" TEXT "+ "," +
TableData.TableInfo.USER_EMAIL +" TEXT "+ ");";
public DatabaseOperations(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null,Database_version);
Log.d("Tag", "Database created");
}
#Override
public void onCreate(SQLiteDatabase sdb) {
sdb.execSQL(SQL_CREATE_ENTRIES);
Log.d("Tag", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void putInformation(DatabaseOperations drop, String name, String pass, String email) {
SQLiteDatabase SQ = drop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_ID, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
cv.put(TableData.TableInfo.USER_EMAIL, email);
long k = SQ.insert(TableData.TableInfo.TABLE_NAME, null, cv);
Log.d("Tag", "inert a row");
}
public Cursor getInformation(DatabaseOperations dop) {
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] coloumns = {TableData.TableInfo.USER_ID, TableData.TableInfo.USER_PASS, TableData.TableInfo.USER_EMAIL};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, coloumns, null, null, null, null, null);
return CR;
}
}
You're missing a , between USER_EMAIL and USER_PASS columns in the CREATE TABLE.
After adding it you can uninstall your app to recreate the database. When is SQLiteOpenHelper onCreate() / onUpgrade() run?
You miss comma in USER PASS type.Uninstall the application and install it again each time you add something new to sqlite database because the table structure has been changed.So you need to reinstall the new application .
The code should be like this
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.USER_ID + " INTEGER PRIMARY KEY," +
TableData.TableInfo.USER_PASS +" TEXT ,"+ "," +
TableData.TableInfo.USER_EMAIL +" TEXT "+ ")";

Android: Throwing error while inserting data in table

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

SQLiteLog﹕no such column

I am trying to execute a basic login form in android. This is the trimmed version of the code. Basically, if the user enters an invalid login details it should trigger an alert. However, I'm getting an error when ever I click on the Login Button.
Below posted is my code.
Alert_Dialouge alert = new Alert_Dialouge();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
context = this;
final DataBaseHelper hl = new DataBaseHelper(context);
AlertDialog alertDialog = new AlertDialog.Builder(
Main_activity.this).create();
Button b1 = (Button) findViewById(R.id.login);
v1 = (TextView) findViewById(R.id.TEXT_STATUS_ID);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
c = c + 1;
EditText user = (EditText) findViewById(R.id.username);
EditText pwd = (EditText) findViewById(R.id.password);
String username = user.getText().toString();
String password = pwd.getText().toString();
db = hl.getReadableDatabase();
db.beginTransaction();
String select = "SELECT * from " + " " + hl.TABLE_NAME+ " "+
"where Username = admin and Password = admin;" ;
Cursor c = db.rawQuery(select, null);
if ((username.equals("") && password.equals("")) ||
password.equals("") || username.equals("")||c.getCount()==0) {
alert.showAlertDialog(Main_activity.this, "Please enter your credentials", false);
Intent intent = new Intent(getApplicationContext(), Main_activity.class);
startActivity(intent);
finish();
} else if(c.getCount()>0) {
c.moveToFirst();
System.out.println("hiiii");
}
c.close();
}
});
}
}
Below posted is my Database Helper class
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="db1";
public static final int DATABASE_VERSION=8;
public static final String COLUMN_ID = "_id";
public static final String TABLE_NAME ="malware_users1";
public static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " +"
"+ TABLE_NAME +"( _id INTEGER PRIMARY KEY AUTOINCREMENT,Username
VARCHAR(255),Password VARCHAR(255))";
public static final String DELETE_TABLE= "DROP TABLE IF EXISTS " +
TABLE_NAME;
public DataBaseHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DELETE_TABLE);
oncreate(db);
}
public void insertData(String Username,String Password)
{
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
ContentValues values;
try
{
values = new ContentValues();
values.put("Username",Username);
values.put("Password",Password);
long i =db.insert(TABLE_NAME,null,values);
Log.i("Insert",i+"");
db.setTransactionSuccessful();
}
catch (SQLiteException e)
{
e.printStackTrace();
}
finally {
db.endTransaction();
db.close();
}
}
}
Below posted is the stackTrace:
no such column: admin (code 1): , while compiling: SELECT * from
malware_users1 where Username = admin and Password = admin;
at
android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
Method) at
android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
much better would be to use the selectionArgs argument
String select = "SELECT * from " + " " + hl.TABLE_NAME+ " "+
"where Username = ? and Password = ? ";
Cursor c = db.rawQuery(select, new String[] {"admin", "admin});
Here you can find the documentation
Please check the query which I had changed
String select = "SELECT * from " + " " + hl.TABLE_NAME+ " "+
"where Username = 'admin' and Password = 'admin'" ;
Please check it and let me know its solved the issue or not ?
in your b1 clicklistener the problem is with your select query
change this
String select = "SELECT * from " + " " + hl.TABLE_NAME+ " "+
"where Username = admin and Password = admin;" ;
to
String username="admin";
String password="admin";
String select = "SELECT * from " + hl.TABLE_NAME+
" where Username ='"+username+"' and Password ='"+password+"'" ;

Table not created using sqlite in android application

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

Categories