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+"'" ;
Related
please help me with this problem. My app keeps crashing because of this. What I want to do is to display the user's information from the SQLite database after they login in a text view on the profile activity. Please help me with my project. I'm still new to android studio.
this is the syntax error in my logcat
android.database.sqlite.SQLiteException: near "null": syntax error (code 1 SQLITE_ERROR): , while compiling: Select * from USER_TABLE where null=?null =?null =?
This is my Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
public static String C_EMAIL,C_PREFERENCES,C_PASSWORD;;
public DatabaseHelper(#Nullable Context context) {
super(context, constants.DB_NAME, null, constants.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(constants.CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + constants.TABLE_NAME);
onCreate(db);
}
public boolean insertInfo(String email, String preference,String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(constants.C_EMAIL, email);
values.put(constants.C_PREFERENCES, preference);
values.put(constants.C_PASSWORD , password);
long id = db.insert(constants.TABLE_NAME, null, values);
if (id == -1) {
return false;
}else {
return true;
}
}
public boolean userExists (String email){
String [] columns = {C_EMAIL};
SQLiteDatabase db = getReadableDatabase();
String selection = C_EMAIL + "=?";
String selectionArgs []= { email };
Cursor cursor = db.query(TABLE_NAME,columns,selection,selectionArgs,null,null,null);
int count = cursor.getCount();
cursor.close();
db.close();
if (count > 0)
return true;
else
return false;
}
public Cursor getData(String email, String Password){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(" Select * from "+ TABLE_NAME + " where "+ C_EMAIL + "=?" + C_PASSWORD + " =?", new String[]{email,Password});
return res;
}
}
This is my login.java
loginacc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor rs = dbHelper.getData(loginemail.getText().toString(),loginpassword.getText().toString());
if(rs.moveToFirst()){
String email = rs.getString(rs.getColumnIndex(DatabaseHelper.C_EMAIL));
String preference = rs.getString(rs.getColumnIndex(DatabaseHelper.C_PREFERENCES));
String password = rs.getString(rs.getColumnIndex(DatabaseHelper.C_PASSWORD));
Toast.makeText(login.this,"Login Successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(login.this,profile.class);
intent.putExtra("email", email);
intent.putExtra("preference", preference);
intent.putExtra("password", password);
startActivity(intent);
if(rs != null && rs.isClosed()){
rs.close();
}
}
else{
Toast.makeText(login.this,"Invalid Login", Toast.LENGTH_SHORT).show();
}
}
});
}
This is my profile.java
public class profile extends AppCompatActivity {
DatabaseHelper dbHelper;
TextView pemail,ppreferences, ppassword;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
dbHelper = new DatabaseHelper(this);
pemail = findViewById(R.id.pemail);
ppreferences = findViewById(R.id.ppreferences);
ppassword = findViewById(R.id.ppassword);
pemail.setText(getIntent().getStringExtra("email"));
ppreferences.setText(getIntent().getStringExtra("preferences"));
ppassword.setText((getIntent().getStringExtra("password")));
Thanks for your help!
You are declaring 3 static variables here:
public static String C_EMAIL,C_PREFERENCES,C_PASSWORD;
without assigning any value to them so they are all null.
When you use them inside getData():
" Select * from "+ TABLE_NAME + " where "+ C_EMAIL + "=?" + C_PASSWORD + " =?"
the result is:
Select * from USER_TABLE where null=?null =?null =?
(it's not clear from your code where the 3d null =? comes from)
What you want is (I guess) to use these variables for the column names of the table.
So change the declarations to:
public static String C_EMAIL = "email"; // change to the actual column name
public static String C_PASSWORD = "password"; // change to the actual column name
public static String C_PREFERENCES = "preferences"; // change to the actual column name
Also add the AND operator in the sql statement:
"Select * from "+ TABLE_NAME + " where "+ C_EMAIL + "= ? AND " + C_PASSWORD + " = ?"
Edit
Inside the method insertInfo() you use constants.C_EMAIL, constants.C_PREFERENCES and constants.C_PASSWORD which it seems are the names of your columns.
If so, then use them also in the sql statement and drop the static variables:
"Select * from "+ TABLE_NAME + " where "+ constants.C_EMAIL + "= ? AND " + constants.C_PASSWORD + " = ?"
i got toast null null, it supposed to toast: "Welcome Angelo(username) Dionisio(userSurname)" after logging in but it says "Welcome null null"
after checking the user existance, it supposed to get the name from the database and display to the toast and switch activities...
what is my error?
and i want to store the username, id, usersurname to the shared prefs after displaying the toast in the future..
myLoginActivity.java
public class Login extends AppCompatActivity implements View.OnClickListener {
private EditText editTextEmailPhone;
private EditText editTextPassword;
private Button Login;
private ProgressDialog progressDialog;
Parent_DatabaseHelper mydb;
SQLiteDatabase sqLiteDatabase;
ParentModel parentModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextEmailPhone = findViewById(R.id.input_username);
editTextPassword = findViewById(R.id.input_password);
findViewById(R.id.btn_login).setOnClickListener(Login.this);
progressDialog = new ProgressDialog(this);
mydb = new Parent_DatabaseHelper(this);
sqLiteDatabase = mydb.getReadableDatabase();
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_login: {
userLogin();
break;
}
}
}
private void userLogin() {
String email = editTextEmailPhone.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if (email.isEmpty()) {
editTextEmailPhone.setError("Email or Phone Number is required");
editTextEmailPhone.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password is required");
editTextPassword.requestFocus();
return;
}
if (password.length()<6 ){
editTextPassword.setError("Minimum of length of password should be 6");
editTextPassword.requestFocus();
return;
}
else{
progressDialog.setMessage("Please Wait...");
progressDialog.show();
boolean exists = mydb.userExistance(email, password);
if(exists){
progressDialog.dismiss();
SharedPrefs.saveSharedSetting(this, "NoAccount", "false");
Intent intent = new Intent(Login.this, Parent_Home.class);
ArrayList<ParentModel> arrayList = new ArrayList<>();
parentModel = new ParentModel();
String s_parentID;
String s_parentName;
String s_parentSurname;
s_parentID = parentModel.getID();
s_parentName = parentModel.getName();
s_parentSurname = parentModel.getSurname();
Toast.makeText(this, "Welcome " + s_parentName + s_parentSurname, Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
else {
Toast.makeText(getApplicationContext(), "Login error", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
return;
}
}
}
public void Login_AdminParent(View view) {
startActivity(new Intent(this, Login_AdminTeacher.class));
}
}
DatabaseHelper.java (incase you need it)
package edu.angelo.parentsportal;
public class Parent_DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Parents_Portal.db";
public static final String TABLE_NAME = "Parents_Table";
public static final String COL_0 = "ID";
public static final String COL_1 = "NAME";
public static final String COL_2 = "SURNAME";
public static final String COL_3 = "EMAIL_ADDRESS";
public static final String COL_4 = "PHONE_NUMBER";
public static final String COL_5 = "PASSWORD";
public Parent_DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, EMAIL_ADDRESS TEXT, PHONE_NUMBER TEXT, PASSWORD TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String surname, String email_address, String phone_number, String password){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,name);
contentValues.put(COL_2,surname);
contentValues.put(COL_3,email_address);
contentValues.put(COL_4,phone_number);
contentValues.put(COL_5,password);
long result = db.insert(TABLE_NAME, null , contentValues);
if (result == -1) {
return false;
}
else {
return true;
}
}
public ArrayList<ParentModel> getAllParentsData(){
ArrayList<ParentModel> list = new ArrayList<>();
String sql = "select * from " + TABLE_NAME;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
ParentModel parentModel = new ParentModel();
parentModel.setID(cursor.getString(0));
parentModel.setName(cursor.getString(1));
parentModel.setSurname(cursor.getString(2));
parentModel.setEmail(cursor.getString(3));
parentModel.setPhone_number(cursor.getString(4));
parentModel.setPassword(cursor.getString(5));
list.add(parentModel);
}
while (cursor.moveToNext());
}
return list;
}
public void updateData(int id, String name , String surname , String email , String phone_number , String password){
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, name);
contentValues.put(COL_2, surname);
contentValues.put(COL_3, email);
contentValues.put(COL_4, phone_number);
contentValues.put(COL_5, password);
SQLiteDatabase mydb = this.getWritableDatabase();
mydb.update(TABLE_NAME, contentValues, COL_0 + "=" + id, null);
mydb.close();
}
public void deleteParent(int id){
SQLiteDatabase mydb = this.getWritableDatabase();
mydb.delete(TABLE_NAME, COL_0 + "=" + id, null);
mydb.close();
}
public boolean userExistance(String emailOrPhone, String pwd) {
String sql = "select * from " + TABLE_NAME + " where (" + COL_3 + " = '" + emailOrPhone + "' OR " + COL_4 + " = '" + emailOrPhone + "') AND " + COL_5 + " = " + pwd;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
ArrayList<ParentModel> list = new ArrayList<>();
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
ParentModel parentModel = new ParentModel();
parentModel.setID(cursor.getString(0));
parentModel.setName(cursor.getString(1));
parentModel.setSurname(cursor.getString(2));
parentModel.setEmail(cursor.getString(3));
parentModel.setPhone_number(cursor.getString(4));
parentModel.setPassword(cursor.getString(5));
list.add(parentModel);
}
while (cursor.moveToNext());
}
return true;
}
else{
return false;
}
}
}
This code here creates ParentModel instance but does not set its members.
parentModel = new ParentModel();
String s_parentID;
String s_parentName;
String s_parentSurname;
s_parentID = parentModel.getID();
s_parentName = parentModel.getName();
s_parentSurname = parentModel.getSurname();
So s_parentName and s_parentSurname are null.
To fix your problem you should create ParentModel instance before calling userExistance and pass it to userExistance. For example:
. . .
parentModel = new ParentModel();
boolean exists = mydb.userExistance(email, password, parentModel);
. . .
And change userExistance. Add ParentModel parameter and remove parentModel = new ParentModel();
like this:
public boolean userExistance(String emailOrPhone, String pwd, ParentModel parentModel)
{
String sql = "select * from " + TABLE_NAME + " where (" + COL_3 + " = '" + emailOrPhone + "' OR " + COL_4 + " = '" + emailOrPhone + "') AND " + COL_5 + " = " + pwd;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
ArrayList<ParentModel> list = new ArrayList<>();
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
parentModel.setID(cursor.getString(0));
parentModel.setName(cursor.getString(1));
parentModel.setSurname(cursor.getString(2));
parentModel.setEmail(cursor.getString(3));
parentModel.setPhone_number(cursor.getString(4));
parentModel.setPassword(cursor.getString(5));
list.add(parentModel);
}
while (cursor.moveToNext());
}
return true;
}
return false;
}
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 am developing an application and after I enter the login details the app crashes.I think the error is due to the problem of database linking and fetching and tried few solutions posted online, but nothing worked.
What can i do to solve this?
06-21 13:21:04.590 1913-1913/in.co.arrow E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.co.arrow, PID: 1913
java.lang.IllegalStateException: Couldn't read row 0, col 4 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at in.co.arrow.sql.SqliteHelper.Authenticate(SqliteHelper.java:140)
at in.co.arrow.LoginActivity$1.onClick(LoginActivity.java:55)
at android.view.View.performClick(View.java:6367)
at android.view.View$PerformClick.run(View.java:25032)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6753)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:482)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
here are my SqliteHelper and LoginActivity classes
package in.co.arrow;
public class LoginActivity extends AppCompatActivity {
EditText editTextEmail;
EditText editTextPassword;
TextInputLayout textInputLayoutEmail;
TextInputLayout textInputLayoutPassword;
Button buttonLogin;
SqliteHelper sqliteHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sqliteHelper = new SqliteHelper(this);
initCreateAccountTextView();
initViews();
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validate()) {
String Email = editTextEmail.getText().toString();
String Password = editTextPassword.getText().toString();
User currentUser = sqliteHelper.Authenticate(new User(null,null,null,null,null,Email,Password,null,null,null,null,null,null));
if (currentUser != null) {
Snackbar.make(buttonLogin, "Successfully Logged in!", Snackbar.LENGTH_LONG).show();
/* Intent intent=new Intent(LoginActivity.this,HomeScreenActivity.class);
startActivity(intent);
finish(); */
} else {
Snackbar.make(buttonLogin, "Failed to log in , please try again", Snackbar.LENGTH_LONG).show();
}
}
}
});
}
private void initCreateAccountTextView() {
TextView textViewCreateAccount = (TextView) findViewById(R.id.textViewCreateAccount);
textViewCreateAccount.setText(fromHtml("<font color='#ffffff'>I don't have account yet. </font><font color='#0c0099'>create one</font>"));
textViewCreateAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
private void initViews() {
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
buttonLogin = (Button) findViewById(R.id.buttonLogin);
}
#SuppressWarnings("deprecation")
public static Spanned fromHtml(String html) {
Spanned result;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
result = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
} else {
result = Html.fromHtml(html);
}
return result;
}
public boolean validate() {
boolean valid = false;
String Email = editTextEmail.getText().toString();
String Password = editTextPassword.getText().toString();
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
valid = false;
textInputLayoutEmail.setError("Please enter valid email!");
} else {
valid = true;
textInputLayoutEmail.setError(null);
}
if (Password.isEmpty()) {
valid = false;
textInputLayoutPassword.setError("Please enter valid password!");
} else {
if (Password.length() > 5) {
valid = true;
textInputLayoutPassword.setError(null);
} else {
valid = false;
textInputLayoutPassword.setError("Password is to short!");
}
}
return valid;
}
}
SqliteHelper.java
package in.co.arrow.sql;
public class SqliteHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "arrow";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_USERS = "users";
public static final String KEY_ID = "id";
public static final String KEY_USER_NAME = "username";
public static final String KEY_FIRST_NAME="firstname";
public static final String KEY_LAST_NAME="lastname";
public static final String KEY_MOBILE_NO="mobileno";
public static final String KEY_EMAIL = "email";
public static final String KEY_PASSWORD = "password";
public static final String KEY_FATHERS_NAME="fathersname";
public static final String KEY_GENDER="gender";
public static final String KEY_INST_NAME="instname";
public static final String KEY_DOB="dob";
public static final String KEY_BRANCH="branch";
public static final String KEY_YOP="yop";
public static final String SQL_TABLE_USERS = " CREATE TABLE " + TABLE_USERS
+ " ( "
+ KEY_ID + " INTEGER PRIMARY KEY, "
+ KEY_USER_NAME + " TEXT, "
+ KEY_FIRST_NAME + " TEXT,"
+ KEY_LAST_NAME + " TEXT,"
+ KEY_MOBILE_NO + " TEXT,"
+ KEY_EMAIL + " TEXT, "
+ KEY_PASSWORD + " TEXT, "
+ KEY_FATHERS_NAME + " TEXT,"
+ KEY_GENDER + " TEXT,"
+ KEY_INST_NAME + " TEXT,"
+ KEY_DOB + " TEXT,"
+ KEY_BRANCH + " TEXT,"
+ KEY_YOP + " TEXT "
+ " ) ";
public SqliteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_TABLE_USERS);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " + TABLE_USERS);
}
public void addUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_USER_NAME, user.userName);
values.put(KEY_FIRST_NAME, user.firstname);
values.put(KEY_LAST_NAME, user.lastname);
values.put(KEY_GENDER, user.gender);
values.put(KEY_FATHERS_NAME, user.fathersname);
values.put(KEY_MOBILE_NO, user.mobileno);
values.put(KEY_EMAIL, user.email);
values.put(KEY_PASSWORD, user.password);
values.put(KEY_DOB, user.dob);
values.put(KEY_INST_NAME,user.instname);
values.put(KEY_BRANCH, user.branch);
values.put(KEY_YOP, user.yop);
long todo_id = db.insert(TABLE_USERS, null, values);
}
public User Authenticate(User user) {
SQLiteDatabase db = this.getReadableDatabase();
#SuppressLint("Recycle") Cursor cursor = db.query(TABLE_USERS,
new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD},
KEY_EMAIL + "=?",
new String[]{user.email},
null, null, null);
if (cursor != null && cursor.moveToFirst()&& cursor.getCount()>0) {
User user1;
user1 = new User(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3),cursor.getString(4), cursor.getString(5), cursor.getString(6),cursor.getString(7),cursor.getString(8),cursor.getString(9),cursor.getString(10),cursor.getString(11),cursor.getString(12));
if (user.password.equalsIgnoreCase(user1.password)) {
return user1;
}
}
return null;
}
public boolean isEmailExists(String email) {
SQLiteDatabase db = this.getReadableDatabase();
#SuppressLint("Recycle") Cursor cursor = db.query(TABLE_USERS,// Selecting Table
new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD},
KEY_EMAIL + "=?",
new String[]{email},
null, null, null);
if (cursor != null && cursor.moveToFirst()&& cursor.getCount()>0) {
return true;
}
return false;
}
}
Your cursor has only 4 columns:
new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD}
but you are trying to read 13 columns out of it. It fails on the first non-existing one at index 4.
You can add all the columns you're reading to your projection.
Your isssue is that you have only specified 4 columns to be extracted into the cursor, yet you are trying to get data from 13 columns.
You could change :-
Cursor cursor = db.query(TABLE_USERS,
new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD},
KEY_EMAIL + "=?",
new String[]{user.email},
null, null, null);
to either :-
Cursor cursor = db.query(TABLE_USERS,
null, // <<<< gets all columns from the table
KEY_EMAIL + "=?",
new String[]{user.email},
null, null, null);
or :-
Cursor cursor = db.query(TABLE_USERS,
new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD, KEY_FIRST_NAME, KEY_LAST_NAME, KEY_GENDER, KEY_FATHERS_NAME, KEY_MOBILE_NO, KEY_DOB, KEY_INST_NAME, KEY_BRANCH, KEY_YOP},
KEY_EMAIL + "=?",
new String[]{user.email},
null, null, null);
The above two assuming that you want data from all columns.
or you could reduce the number of columns from which you retrieve data but that would depend upon what constructors are available for a User object.
I've been trying to populate an Android Listview from a SQLite database using the code below. I have successfully done this from an array inside the same class. But in this case I'm attempting to populate it from a String array I have returned from another class. I'm new to this so am possibly doing this completely wrong. If anyone could look at the code and advise to what I'm doing wrong that'd be brilliant.
Any help would be really appreciated with this as I'm under serious pressure to get it finished, Thanks!
LoginActivity Class
public class LoginActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final EditText txtUserName = (EditText)findViewById(R.id.txtUsername);
final EditText txtPassword = (EditText)findViewById(R.id.txtPassword);
Button btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
try{
if(username.length() > 0 && password.length() >0)
{
DBUserAdapter dbUser = new DBUserAdapter(LoginActivity.this);
dbUser.open();
int UID = dbUser.Login(username, password);
if(UID != -1)
{
// TEST
//int UID = dbUser.getUserID(username, password);
//getSitesByClientname(UID);
// END TEST
// MY TEST CODE TO CHANGE ACTIVITY TO CLIENT SITES
Intent myIntent = new Intent(LoginActivity.this, ClientSites.class);
//Intent myIntent = new Intent(getApplicationContext(), ClientSites.class);
myIntent.putExtra("userID", UID);
startActivity(myIntent);
//finish();
// END MY TEST CODE
//Cursor UserID = dbUser.getUserID();
Toast.makeText(LoginActivity.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(LoginActivity.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
}
dbUser.close();
}
}catch(Exception e)
{
Toast.makeText(LoginActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}
Method from DBHelper Class to return String Array
public String[] getSitesByClientname(String id) {
String[] args={id};
//return db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
// loop through all rows and adding to array
int count;
count = myCursor.getCount();
final String[] results = new String[count];
results[0] = new String();
int i = 0;
try{
if (myCursor.moveToFirst()) {
do {
results[i] = myCursor.getString(myCursor.getColumnIndex("client_sitename"));
} while (myCursor.moveToNext());
}
}finally{
myCursor.close();
}
db.close();
// return results array
return results;
ClientSites Class
public class ClientSites extends ListActivity {
public final static String ID_EXTRA="com.example.loginfromlocal._ID";
private DBUserAdapter dbHelper = null;
//private Cursor ourCursor = null;
private ArrayAdapter<String> adapter=null;
//#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
//int uID = i.getIntExtra("userID", 0);
//ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
dbHelper.createDatabase();
//dbHelper.openDataBase();
dbHelper.open();
String[] results = dbHelper.getSitesByClientname(uID);
//setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results));
//adapter = new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results);
setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.layout.client_sites, results));
//ListView myListView = (ListView)findViewById(R.id.myListView);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null);
//CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
//adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
//myListView.setAdapter(adapter);
//myListView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "XXERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
}
Any help with this would be great, Thanks!
Create own project with few activities. Start working with sqlite database
Create new application. Create login activity and DB helper. Trying to upload dada from DB. Reseach and development
Here is an example how to work with SQLite DB.
public class DBHelper extends SQLiteOpenHelper {
private static DBHelper instance;
private static final String DATABASE_NAME = "UserClientBase";
private static final int DATABASE_VERSION = 1;
public static interface USER extends BaseColumns {
String TABLE_NAME = "userTable";
String NAME = "userName";
String PASSWORD = "userPassword";
}
public static interface CLIENT extends BaseColumns {
String TABLE_NAME = "clientTable";
String NAME = "clientName";
String USER_ID = "userId";
}
private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS ";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS ";
private static final String UNIQUE = "UNIQUE ON CONFLICT ABORT";
private static final String CREATE_TABLE_USER = CREATE_TABLE + USER.TABLE_NAME + " (" + USER._ID
+ " INTEGER PRIMARY KEY, " + USER.NAME + " TEXT " + UNIQUE + ", " + USER.PASSWORD + " TEXT);";
private static final String CREATE_TABLE_CLIENT = CREATE_TABLE + CLIENT.TABLE_NAME + " (" + CLIENT._ID
+ " INTEGER PRIMARY KEY, " + CLIENT.NAME + " TEXT UNIQUE, " + CLIENT.USER_ID + " INTEGER);";
private DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DBHelper getInstance(Context context) {
if (instance == null) {
instance = new DBHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USER);
db.execSQL(CREATE_TABLE_CLIENT);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE + USER.TABLE_NAME);
db.execSQL(DROP_TABLE + CLIENT.TABLE_NAME);
onCreate(db);
}
public long createUser(String newUserName, String newUserPassword) {
ContentValues values = new ContentValues();
values.put(USER.NAME, newUserName);
values.put(USER.PASSWORD, newUserPassword);
return getWritableDatabase().insert(USER.TABLE_NAME, null, values);
}
public long createClient(long userId, String newClientName) {
ContentValues values = new ContentValues();
values.put(CLIENT.USER_ID, userId);
values.put(CLIENT.NAME, newClientName);
return getWritableDatabase().insert(CLIENT.TABLE_NAME, null, values);
}
public boolean isCorrectLoginPassword(String login, String password) {
Cursor userListCursor = getReadableDatabase().rawQuery(
"SELECT * FROM " + USER.TABLE_NAME + " WHERE " + USER.NAME + " =? AND " + USER.PASSWORD
+ " =?", new String[] { login, password });
if ((userListCursor != null) && (userListCursor.getCount() > 0)) {
return true;
} else {
return false;
}
}
public Cursor getUserClientList(String userName) {
Cursor userClientList = getReadableDatabase().rawQuery(
"SELECT * FROM " + CLIENT.TABLE_NAME + " INNER JOIN " + USER.TABLE_NAME
+ " ON " + CLIENT.USER_ID + " = " + USER.TABLE_NAME + "." + USER._ID + " WHERE "
+ USER.NAME + " =?", new String[] { userName });
return userClientList;
}
}
Example of login button click listener.
String login = loginEdt.getText().toString();
String password = passwordEdt.getText().toString();
boolean loginSuccess = databaseHelper.isCorrectLoginPassword(login, password);
if(loginSuccess) {
Intent clientListIntent = new Intent(LoginActivity.this, ClientListActivity.class);
clientListIntent.putExtra(ClientListActivity.EXTRAS_LOGIN, login);
startActivity(clientListIntent);
} else {
Toast.makeText(LoginActivity.this, "Incorrect login/password", Toast.LENGTH_SHORT).show();
}
And example of listview with data from sql:
clientLv= (ListView)findViewById(R.id.listClient);
login = getIntent().getExtras().getString(EXTRAS_LOGIN);
dbHelper = DBHelper.getInstance(this);
Cursor clientList = dbHelper.getUserClientList(login);
adapter = new SimpleCursorAdapter(this, R.layout.row_client, clientList, new String[]{DBHelper.CLIENT.NAME}, new int[]{R.id.txtClientName} , SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
clientLv.setAdapter(adapter);