Having trouble on username it says null - java

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

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

Get specific row of SQLite android

I am new to Android and I want it when the user logs in by the email and password. Bring the rest of the information like the first name and the date of birth to the user via email. Is there any way to do that?
"Is there a function I can add that can not bring all user information after logging in by email"
this is my database Code :
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "UserManager.db";
private static final String TABLE_USER = "user";
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_FIRST_NAME = "user_first_name";
private static final String COLUMN_USER_LAST_NAME = "user_last_name";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_PHONE_NUMBER = "user_phone_number";
private static final String COLUMN_USER_BARTH_DAY = "user_barth_day";
private static final String COLUMN_USER_PASSWORD = "user_password";
private static final String COLUMN_USER_GENDER = "user_gender";
private String CREATE_USER_TABLE = "CREATE TABLE "+TABLE_USER + "("+
COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"+
COLUMN_USER_FIRST_NAME + " TEXT,"+ COLUMN_USER_LAST_NAME + " TEXT,"+
COLUMN_USER_EMAIL + " TEXT PRIMARY KEY,"+COLUMN_USER_PHONE_NUMBER + " TEXT,"+
COLUMN_USER_BARTH_DAY+" TEXT,"+ COLUMN_USER_PASSWORD+" TEXT," +
COLUMN_USER_GENDER+" TEXT"+ ")";
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS "+ TABLE_USER ;
public DatabaseHelper(Context context) {
super(context , DATABASE_NAME, null , DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_USER_TABLE);
onCreate(db);
}
public void addUser(User user){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_FIRST_NAME , user.getFirstName());
values.put(COLUMN_USER_LAST_NAME , user.getLastName());
values.put(COLUMN_USER_EMAIL , user.getEmail());
values.put(COLUMN_USER_PHONE_NUMBER , user.getPhoneNumber());
values.put(COLUMN_USER_BARTH_DAY , user.getBarthDay());
values.put(COLUMN_USER_PASSWORD , user.getPassword());
values.put(COLUMN_USER_GENDER , user.getGender());
database.insert(TABLE_USER , null, values);
database.close();
}
public boolean checkUser (String email){
String [] columns = {
COLUMN_USER_ID
};
SQLiteDatabase database = this.getWritableDatabase();
String selection = COLUMN_USER_EMAIL + " = ?";
String[] selectionArgs = {email};
Cursor cursor = database.query(TABLE_USER,
columns,selection , selectionArgs,null,null,null);
int cursorCount = cursor.getCount();
cursor.close();
database.close();
if (cursorCount > 0){
return true;
}else {
return false;
}
}
public boolean checkUser (String email , String password){
String [] columns = {
COLUMN_USER_ID
};
SQLiteDatabase database = this.getWritableDatabase();
String selection = COLUMN_USER_EMAIL + " = ?" + " AND " + COLUMN_USER_PASSWORD + " = ?";
String[] selectionArgs = {email , password};
Cursor cursor = database.query(TABLE_USER,
columns,selection , selectionArgs,null,null,null);
int cursorCount = cursor.getCount();
cursor.close();
database.close();
if (cursorCount > 0){
return true;
}else {
return false;
}
}
}
For your first question, you can add below function and use it.
public User getSingleUserInfo(String email){
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_USER + " WHERE " + COLUMN_USER_EMAIL + "=" + email);
cursor.moveToFirst();
//setting related user info in User Object
User user = new User();
user.setUserId(cursor.getInt(cursor.getColumnIndexCOLUMN_USER_ID ));
user.setFirstName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_FIRST_NAME));
user.setLastName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_LAST_NAME ));
user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL ));
user.setPhoneNumber(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PHONE_NUMBER ));
user.setBirthday(cursor.getString(cursor.getColumnIndex(COLUMN_USER_BARTH_DAY ));
user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD));
user.setGender(cursor.getString(cursor.getColumnIndex(COLUMN_USER_GENDER ));
//close cursor & database
cursor.close();
database.close();
return user;
}
Note : Becareful about your User object's setter functions which may be vary from my example and data types. Use c.getInt() if it is int and c.getString() if String.
You can use particular email address with password to query in database to get all the details.
public String getUserName(String email, String password) {
Cursor cursor = null;
String firstName = "";
try {
cursor = SQLiteDatabaseInstance_.rawQuery("SELECT * FROM " + TABLE_USER + " WHERE "+ COLUMN_USER_EMAIL +"?", new String[] {email+ ""}+ " AND "+COLUMN_USER_PASSWORD+"?", new String[] {password+ ""});
if(cursor.getCount() > 0) {
cursor.moveToFirst();
firstName= cursor.getString(cursor.getColumnIndex(COLUMN_USER_FIRST_NAME));
}
return firstName;
}finally {
cursor.close();
}
}

Unfortunately Myapp has stopped after entering login details

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.

Searching for a row in the database doesn't work, String comparison error

I'm trying to make a register-login app in android studio and I've come across some problems in the registration part. This is my code in RegisterActivity:
public void addUser (View view) {
StringBuffer errors = new StringBuffer();
StringBuffer noerrors = new StringBuffer();
errors.append("");
noerrors.append("");
String firstname = FirstName.getText().toString();
String lastname = LastName.getText().toString();
String username = UserName.getText().toString();
String password = UserPassoword.getText().toString();
String retypepassword = RetypePassword.getText().toString();
String email = UserEmail.getText().toString();
if(!searchUsername(username)) {
errors.append("Username already exists\n");
UserName.clearComposingText();
}
if(!searchEmail(email)) {
errors.append("Email already in use\n");
UserEmail.clearComposingText();
}
if(password.equals(retypepassword)){
errors.append("Password retyped incorrectly");
UserPassoword.clearComposingText();
RetypePassword.clearComposingText();
}
userDbHelper = new UserDbHelper(context);
sqLiteDatabase = userDbHelper.getWritableDatabase();
if(errors.toString().equals(noerrors.toString())) {
userDbHelper.addInformation(firstname, lastname, username, password, email, sqLiteDatabase);
Toast.makeText(getBaseContext(), "Register successful!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(this, errors, Toast.LENGTH_LONG).show();
}
userDbHelper.close();
}
public boolean searchUsername(String username) {
userDbHelper = new UserDbHelper(getApplicationContext());
sqLiteDatabase = userDbHelper.getReadableDatabase();
Cursor cursor = userDbHelper.getUsername(username, sqLiteDatabase);
if(cursor.moveToFirst()) {
return true;
} else {
return false;
}
}
and this is my database helper
public class UserDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "USERINFO.DB";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE " + UserContract.NewUserInfo.TABLE_NAME + "(" + UserContract.NewUserInfo.FIRST_NAME + " TEXT," +
UserContract.NewUserInfo.LAST_NAME + " TEXT," + UserContract.NewUserInfo.USER_NAME + " TEXT," +
UserContract.NewUserInfo.USER_PASSWORD + " TEXT," + UserContract.NewUserInfo.USER_EMAIL + " TEXT);";
public UserDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
}
public void addInformation (String firstname, String lastname, String username, String password, String email, SQLiteDatabase db) {
ContentValues contentValues = new ContentValues();
contentValues.put(UserContract.NewUserInfo.FIRST_NAME, firstname);
contentValues.put(UserContract.NewUserInfo.LAST_NAME, lastname);
contentValues.put(UserContract.NewUserInfo.USER_NAME, username);
contentValues.put(UserContract.NewUserInfo.USER_PASSWORD, password);
contentValues.put(UserContract.NewUserInfo.USER_EMAIL, email);
db.insert(UserContract.NewUserInfo.TABLE_NAME, null, contentValues);
Log.e("DATABASE OPERATIONS", "One row inserted");
}
public Cursor getUsername (String username, SQLiteDatabase db) {
String[] projections = {UserContract.NewUserInfo.FIRST_NAME, UserContract.NewUserInfo.LAST_NAME,
UserContract.NewUserInfo.USER_PASSWORD, UserContract.NewUserInfo.USER_EMAIL};
String selection = UserContract.NewUserInfo.USER_NAME + " LIKE ?";
String[] selection_args = {username};
Cursor cursor = db.query(UserContract.NewUserInfo.TABLE_NAME, projections, selection, selection_args, null, null, null);
return cursor;
}
}
In my registration form, whenever I retype the password correctly, my stringbuffer shows "Password retyped incorrectly" and when I retype it incorrectly, this message doesn't appear.
In the database helper, the searchEmail method is the same as searchUsername, only with a few changes so that it seaches for the email. Whether I type a username/email that is or isn't in the database, "Username already exists" and "Email already in use" are appended.
I also don't get why .clearComposingText() doesn't work to clear my edittext fields.
I found the problem. The two methods, searchEmail and searchUsername, need to take the View object as a parameter.

Populate Android Listview from SQLite database

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

Categories