I am new to android studio and trying to work on simple login form which is my lab assignment.
When I click on login button it says username or password wrong even if it is true.
SqlHelper.java
package com.example.mogli.henabenparekhrajthakkar_comp304_lab4;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Mogli on 11/30/2017.
*/
public class SqlHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "hospital.db";
//nurse table name & columns
private static final String NURSE_TABLE_NAME = "nurses";
private static final String NURSE_COLUMN_ID = "nurseId";
private static final String NURSE_COLUMN_FIRST_NAME = "nurseFirstName";
private static final String NURSE_COLUMN_LAST_NAME = "nurseLastName";
private static final String NURSE_COLUMN_DEPARTMENT = "nurseDepartment";
private static final String NURSE_COLUMN_PASSWORD = "nursePassword";
//doctor table name & columns
private static final String DOCTOR_TABLE_NAME = "doctors";
private static final String DOCTOR_COLUMN_ID = "doctorId";
private static final String DOCTOR_COLUMN_FIRST_NAME = "doctorFirstName";
private static final String DOCTOR_COLUMN_LAST_NAME = "doctorLastName";
private static final String DOCTOR_COLUMN_DEPARTMENT = "doctorDepartment";
private static final String DOCTOR_COLUMN_PASSWORD = "doctorPassword";
private static final String NURSE_TABLE_CREATE = "create table if not exists nurses( nurseId text primary key not null, "
+ "nurseFirstName text not null, nurseLastName text not null, nurseDepartment text not null, nursePassword text not null );";
private static final String DOCTOR_TABLE_CREATE = "create table if not exists doctors( doctorId text primary key not null, "
+ "doctorFirstName text not null, doctorLastName text not null, doctorDepartment text not null, doctorPassword text not null );";
//insert query
/*private String insertIntoNurse = "INSERT INTO nurses (nurseId, nurseFirstName, nurseLastName, nurseDepartment, nursePassword)"
+"VALUES ('john123', 'john', 'doe', 'd1', '123john' ), ('jonahdoe', 'jonah', 'doe', 'd2', '123jonah'), ('hannah123', 'hannah', 'montana', 'd3', 'hm123');";*/
public SqlHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
try {
sqLiteDatabase.execSQL(NURSE_TABLE_CREATE);
sqLiteDatabase.execSQL(DOCTOR_TABLE_CREATE);
}
catch(Exception e)
{
Log.d("myMsg", "Error creating table");
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String nurse_query = "DROP TABLE IF EXISTS " + NURSE_TABLE_NAME;
String doctor_query = "DROP TABLE IF EXISTS " + DOCTOR_TABLE_NAME;
sqLiteDatabase.execSQL(nurse_query);
sqLiteDatabase.execSQL(doctor_query);
onCreate(sqLiteDatabase);
}
public boolean checkUser(String email, String password) {
// array of columns to fetch
String[] columns = {
NURSE_COLUMN_ID
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = NURSE_COLUMN_ID + " = ?" + " AND " + NURSE_COLUMN_PASSWORD + " = ?";
// selection arguments
String[] selectionArgs = {email, password};
// query user table with conditions
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE user_email = 'jack#androidtutorialshub.com' AND user_password = 'qwerty';
*/
Cursor cursor = db.query(NURSE_TABLE_NAME, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
public String searchPass(String NURSE_COLUMN_ID)
{
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query = "select nurseId, nursePassword from "+ NURSE_TABLE_NAME;
Cursor cursor =sqLiteDatabase.rawQuery(query, null);
String a, b;
b = "";
if(cursor.moveToFirst())
{
do
{
a = cursor.getString(0);
b = cursor.getString(1);
if(a.equals(NURSE_COLUMN_ID))
{
b = cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return b;
}
public void addNurses(Nurse nurse)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NURSE_COLUMN_ID, nurse.getNurseId());
values.put(NURSE_COLUMN_FIRST_NAME, nurse.getNurseFirstName());
values.put(NURSE_COLUMN_LAST_NAME, nurse.getNurseLastName());
values.put(NURSE_COLUMN_DEPARTMENT, nurse.getNurseDepartment());
values.put(NURSE_COLUMN_PASSWORD, nurse.getNursePassword());
db.insert(NURSE_TABLE_NAME,null,values);
db.close();
}
public List<Nurse> getAllNurses() {
List<Nurse> nurseList = new ArrayList<Nurse>();
// Select All Query
String selectQuery = "SELECT * FROM " + NURSE_TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Nurse nurse = new Nurse();
nurse.setNurseId(cursor.getString(0));
nurse.setNurseFirstName(cursor.getString(1));
nurse.setNurseLastName(cursor.getString(2));
nurse.setNurseDepartment(cursor.getString(3));
nurse.setNursePassword(cursor.getString(4));
// Adding contact to list
nurseList.add(nurse);
} while (cursor.moveToNext());
}
// return contact list
return nurseList;
}
}
In the log file the database is created and data is inserted. but the login code is giving false in the log console even if the username and password is correct.
Related
Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
// Table Name
public static final String TABLE_NAME = "Contacts";
// Table columns
public static final String ID = "ID";
public static final String Contact_Name = "Contact_Name";
public static final String Phone_Number = "Phone_Number";
public static final String Favourites = "Favourites";
// Database Information
static final String DB_NAME = "MessagePlus_Contacts";
// database version
static final int DB_VERSION = 1;
// Creating table query
private static final String CREATE_TABLE = "Create Table " + TABLE_NAME + "(" + ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Contact_Name + " TEXT NOT NULL, " + Phone_Number + " INT NOT NULL, " + Favourites + " Boolean NOT NULL);";
private static final String Show_Table = "Select * From " + TABLE_NAME;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void showData(SQLiteDatabase db){db.execSQL(Show_Table);}
public void insertData(String contactName, String phoneNumber,String favourites) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.Contact_Name, contactName);
values.put(DatabaseHelper.Phone_Number, phoneNumber);
values.put(DatabaseHelper.Favourites, favourites);
db.insert(DatabaseHelper.TABLE_NAME, null, values);
// close db connection
db.close();
}
public int addToFavourites(String favourites) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.Favourites, favourites);
// updating row
return db.update(DatabaseHelper.TABLE_NAME, values, DatabaseHelper.Phone_Number + " = ?", new String[]{favourites});
}
public int getCount() {
String countQuery = "SELECT * FROM " + DatabaseHelper.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
Modal
public class FavouritesHelper {
public String Name;
public String PhoneNumber;
public boolean Favourites;
public FavouritesHelper() {
}
public FavouritesHelper(String Name, String PhoneNumber, Boolean Favourites) {
this.Name = Name;
this.PhoneNumber = PhoneNumber;
this.Favourites = Favourites;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public void setPhoneNumber(String PhoneNumber) {
this.PhoneNumber = PhoneNumber;
}
public boolean getFavourites() {
return Favourites;
}
public void setFavourites(boolean Favourites) {
this.Favourites = Favourites;
}
}
This is my database helper and I'm trying to fetch the table in logcat but I don't know how to do that. I know the code is Select * from <tablename> but how do i implement that. I want to see all the data in my table.
Soltion:
Please follow the following steps:
First Step:
Make the below method in DatabaseHelper class:
public List<FavouritesHelper> getAllData() {
List<FavouritesHelper> data = new ArrayList<>();
// Select All Query
String selectQuery = "SELECT * FROM " + FavouritesHelper.TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
FavouritesHelper alldata = new FavouritesHelper();
alldata.setName(cursor.getString(cursor.getColumnIndex(FavouritesHelper.Name)));
alldata.setPhoneNumber(cursor.getString(cursor.getColumnIndex(FavouritesHelper.PhoneNumber)));
alldata.setFavourites(cursor.getBoolean(cursor.getColumnIndex(FavouritesHelper.Favourites)));
data.add(alldata);
} while (cursor.moveToNext());
}
// close db connection
db.close();
// return notes list
return data;
}
Second Step:
In your activity:
declare a global object: List<FavouritesHelper> AllData inside your class.
Third Step:
then, add this AllData = new List<FavouritesHelper>(); in your onCreate()
Fourth Step:
write this in your activity after inserting data: AllData = database.getAllData();
Fifth Step:
Print it in log using below statement:
for(FavouritesHelper helper : AllData) {
Log.e("values : ", helper.getName() + ", " + helper.getPhoneNumber() + ", " + helper.getFavourites());
}
That's it.
Try it out. Hope it Helps.
As #pskink suggested you can use dumpCursor like this
create this method inside your DatabaseHelper class
public void dumpCursorInLogCat() {
//here first getting the readable database
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(Show_Table, null);
//here is how you can Dump cursor
DatabaseUtils.dumpCursor(cursor);
cursor.close();
}
and call this method in your activity whenever you want to show data in logcat
call it inside your activity like
new DatabaseHelper(your_activity_name.this).dumpCursorInLogCat();
hi i want to put cursor content in textview .
im using sqlite data base when get the id of the current user and display them in a textview i tried to search but i found nothing
here is the code
package com.example.i.projet;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.EditText;
public class AfficherActivity extends AppCompatActivity {
BaseDeDonee bdd;
EditText nom , prenom , email,numt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_afficher);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
bdd = new BaseDeDonee(this);
int k =bdd.tempID();// to get id of corrent user
String id = Integer.toString(k) ;
Cursor res = bdd.afficherinfoP(id);// function return cursor
nom =(EditText) findViewById(R.id.nom);
prenom=(EditText) findViewById(R.id.prenom);
email=(EditText) findViewById(R.id.email);
numt=(EditText) findViewById(R.id.numtele);
if(res.getCount()<=0){
// show message empty
}else{
res.moveToFirst();
nom.setText(res.getString(res.getColumnIndex("nom")));
prenom.setText(res.getString(res.getColumnIndex("prenom")));
numt.setText(res.getInt(res.getColumnIndex("numero_tel")));
email.setText( res.getString(res.getColumnIndex("profile")));
}
}
}
and the data base
public class BaseDeDonee extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Platforme.db";
public static final String TABLE_PERSONNE = "UsersTable";
public static final String COL_1 = "ID";
public static final String COL_2 = "nom";
public static final String COL_3 = "prenom";
public static final String COL_4 = "numero_tel";
public static final String COL_5 = "profile";
public static final String COL_s = "password";
public static final String COL_k = "etat";
public static final String TABLE_COMPTE = "CompteTable";
public static final String COL_6 = "numero_compte";
public static final String COL_7 = "cle_compte";
public static final String COL_8 = "solde_courante";
public static final String COL_9 = "type_compte";
public static final String TABLE_OPPERATIONS = "OpperationsTable";
public static final String COL_10 = "num_opp";
public static final String COL_11 = "type_opp";
public static final String COL_12 = "date_opp";
public static final String COL_13 = "montant_opp";
public static final String COL_14 = "solde_courante";
//+etat de l'opp pour avoir est que personel ou du busness
public static final String TABLE_PRODUITS = "ProductsTable";
public static final String COL_15 = "nom_prod";
public static final String COL_16 = "type_prod";
public static final String COL_17 = "PrixUnit_prod";
public static final String COL_18 = "quantite_prod";
public static final String COL_19 = "PrixTotal_prod";
public static final String TABLE_FACTURES = "FacturesTable";
public static final String COL_20 = "num_fact";
public static final String COL_21 = "type_fact";
public static final String COL_22 = "Montant_fact";
public static final String COL_23 = "date_fact";
public static final String TABLE_IDENTIFICATION = "IdentificationTable";
public static final String COL_24 = "profile";
public static final String COL_25 = "password";
public static final String TABLE_DECAISSEMENT = "DecaissementTable";
public static final String COL_26 = "num_opp";
public static final String COL_27 = "type_compte";
public static final String COL_28 = "piecejustificatif";
public static final String TABLE_Temp = "tempTable";
public static final String COL_29 = "ID";
public BaseDeDonee(Context context ) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_PERSONNE +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,nom TEXT,prenom TEXT,numero_tel INTEGER,profile TEXT,password Text,etat Text)");
db.execSQL("create table " + TABLE_COMPTE +" (numero_compte INTEGER PRIMARY KEY,cle_compte INTEGER,solde_courante DOUBLE,type_compte TEXT,ID INTEGER REFERENCES TABLE_PERSONNE)");
db.execSQL("create table " + TABLE_PRODUITS +" (nom_prod TEXT PRIMARY KEY,type_prod TEXT,PrixUnit_prod DOUBLE,quantite_prod INTEGER,PrixTotal_prod DOUBLE,num_opp INTEGER REFERENCES TABLE_OPPERATIONS)");
db.execSQL("create table " + TABLE_FACTURES +" (num_fact INTEGER PRIMARY KEY AUTOINCREMENT,type_fact TEXT,Montant_fact DOUBLE,date_fact DATE,num_opp INTEGER REFERENCES TABLE_OPPERATIONS,ID INTEGER REFERENCES TABLE_PERSONNE)");
db.execSQL("create table " + TABLE_OPPERATIONS +" (num_opp INTEGER PRIMARY KEY AUTOINCREMENT,type_opp TEXT,montant_opp DOUBLE,date_opp DATE,ID INTEGER REFERENCES TABLE_PERSONNE ,solde_courante DOUBLE REFERENCES TABLE_COMPTE)");
db.execSQL("create table " + TABLE_IDENTIFICATION +" (profile TEXT REFERENCES TABLE_PERSONNE PRIMARY KEY ,password TEXT REFERENCES TABLE_PERSONNE)");
db.execSQL("create table " + TABLE_DECAISSEMENT + " (piecejustificatif TEXT PRIMARY KEY,num_opp INTEGER REFERENCES TABLE_OPPERATIONS,type_compte TEXT REFERENCES TABLE_COMPTE)");
db.execSQL("create table " + TABLE_Temp + " (ID INTEGER PRIMARY KEY )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PERSONNE + TABLE_COMPTE + TABLE_PRODUITS + TABLE_FACTURES + TABLE_OPPERATIONS + TABLE_IDENTIFICATION + TABLE_DECAISSEMENT + TABLE_Temp);
onCreate(db);
}
public boolean insertData(String nom ,String prenom ,String tel,String profile,String password ,String etat){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
Cursor res = db.query(TABLE_PERSONNE,new String[]{"*"},"profile =?",new String[]{profile},null,null,null);
contentValues.put(COL_2,nom);
contentValues.put(COL_3,prenom);
contentValues.put(COL_4,tel);
contentValues.put(COL_5,profile);
contentValues.put(COL_s,password);
contentValues.put(COL_k,etat);
if(res!=null && res.moveToFirst()){
return false;
}else{
long result= db.insert(TABLE_PERSONNE, null, contentValues);
if (result==-1){
return false;
}else return true; }
}
public boolean insertl(String profile ,String password ){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues ContentVlues = new ContentValues();
ContentVlues.put(COL_24,profile);
ContentVlues.put(COL_25,password);
long result =db.insert(TABLE_IDENTIFICATION,null,ContentVlues);
if (result==-1)
return false;
else return true ;
}
public boolean insertfacture(String type ,String Montantfact, String date){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues ContentVlues = new ContentValues();
ContentVlues.put(COL_21,type);
ContentVlues.put(COL_22,Montantfact);
ContentVlues.put(COL_23,date);
long result =db.insert(TABLE_FACTURES,null,ContentVlues);
if (result==-1)
return false;
else return true ;
}
public boolean insertCompte(String numero_compte ,String cle_compte, String solde_courante,String type_compte ){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues ContentVlues = new ContentValues();
ContentVlues.put(COL_6,numero_compte);
ContentVlues.put(COL_7,cle_compte);
ContentVlues.put(COL_8,solde_courante);
ContentVlues.put(COL_9,type_compte);
long result =db.insert(TABLE_COMPTE,null,ContentVlues);
if (result==-1)
return false;
else return true ;
}
public boolean insertProduit(String nom_prod ,String type_prod, String PrixUnit_prod,String quantite_prod,String PrixTotal_prod){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues ContentVlues = new ContentValues();
ContentVlues.put(COL_15,nom_prod);
ContentVlues.put(COL_16,type_prod);
ContentVlues.put(COL_17,PrixUnit_prod);
ContentVlues.put(COL_18,quantite_prod);
ContentVlues.put(COL_19,PrixTotal_prod);
long result =db.insert(TABLE_PRODUITS,null,ContentVlues);
if (result==-1)
return false;
else return true ;
}
public boolean inseloginid(int id ){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_Temp,null);
ContentValues ContentVlues = new ContentValues();
ContentVlues.put(COL_29,id);
if(res.getCount()<=0){
long result =db.insert(TABLE_Temp,null,ContentVlues);
if (result==-1)
return false;
else return true ;
}else return true;
}
public Cursor afficherinfoP (String id ){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.query(TABLE_PERSONNE,null,"ID = ? ", new String[]{id},null,null,null);
return res;
}
public Boolean finde(String lemail, String lpass) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.query(TABLE_IDENTIFICATION, null, "profile=? AND password=?",new String[]{lemail,lpass},null,null,null);
if(res.getCount()<=0){
res.close();
return false;
}else {
res.close();
return true;
}
}
public int findID (String lemail){
SQLiteDatabase db = this.getWritableDatabase();
int k ;
Cursor res = db.query(TABLE_PERSONNE, null, "profile=?", new String[]{lemail}, null, null, null);
if(res!=null && res.moveToFirst()){
//cursor contains data
int ind =res.getColumnIndex("id");
k = res.getInt(ind);
}else k=0;
return k;
}
public int tempID (){
SQLiteDatabase db = this.getWritableDatabase();
int k =-1;
Cursor res = db.rawQuery("select * from " + TABLE_Temp, null);
if (res!=null && res.moveToFirst()){
k = res.getInt(res.getColumnIndex("ID"));
}
return k ;
}
public double rapportJ(String date,int id ){
Double k= Double.valueOf(0);
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("Select * from"+TABLE_FACTURES+"where date_fact="+date+"and id="+id,null);
while (res.moveToNext()){
k=k+ res.getDouble(2);
}
Cursor ress=db.rawQuery("Select * from"+TABLE_OPPERATIONS+"where date_opp="+date+"and id="+id,null);
while (ress.moveToNext()){
k=k+ ress.getDouble(2);
}
return k;
}
}
stack trace
So I found the following issues following your logic:
public boolean inseloginid(int id ){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_Temp,null);
ContentValues ContentVlues = new ContentValues();
ContentVlues.put(COL_29,id);
if(res.getCount()>0){ // I changed this condition from <= to >
db.delete(TABLE_Temp,null,null); // added this line
long result =db.insert(TABLE_Temp,null,ContentVlues);
if (result==-1)
return false;
else return true ;
}else return true;
}
The reason is that it will not insert the current login if there is a previous value stored. After the correction, if there is a value stored, it'll clear the table and enter the login ID. In the main activity call bdd.inseloginid(loggedID); before int k = bdd.tempID();. That inserts the ID into temp then you pull it with int k = bdd.tempID();. That'll pull the correct data from the database when you call bdd.afficherinfoP(id);.
When it comes to displaying them with the EditText views:
numt.setText(res.getInt(res.getColumnIndex("numero_tel")));
returns a string because "numero_tel" is an integer in your table declaration, so turn it into a string:
numt.setText(Integer.toString(res.getInt(res.getColumnIndex("numero_tel"))));
There may be easier ways to do this but I tried to keep your logic intact. It's also worth mentioning that you have to clear TABLE_temp because in bdd.tempID(); your logic always goes to the top value. If you clear the table then the top value will be the logged in ID.
I have created a database in DB.java following various tutorials.
They have methods to get data and insert into the database using SQLite.
My questions are
1) How do I get DB.java to instantiate, as you see i have insertStudent("hello", "male", 4, "password", "computing", "module"); just for a bit of test data, I want to know what I would do with this in order for it to insert, I know I haven't called DB.java anywhere for it to do that, but I am unsure which way to go about it.
2) Once it has created the database, I want it to display the data from the database on the main activity. I decided to make the getData method static, then I called it in my main activity by using DB.getData(db); however it's stating db cannot be resolved to a variable. So i've messed up somewhere.
Any guidance is appreciated.
Below is my DB.java
package com.example.project;
import com.example.project.tableStudents.tableColumns;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DB extends SQLiteOpenHelper {
public static final int db_version = 1;
public static final String Table = "Students";
public static final String Student_ID = "Student_ID";
public static final String Student_Name = "Student_Name";
public static final String Student_Password = "Student_Password";
public static final String Student_Gender = "gender";
public static final String Student_Age = "age";
public static final String Student_Course = "course";
public static final String Student_Modules = "modules";
public DB(Context context) {
super(context, tableColumns.Database, null, db_version);
// Insert Students
insertStudent("hello", "male", 4, "password", "computing", "module");
}
#Override
public void onCreate(SQLiteDatabase db) {
//Create Table
db.execSQL("CREATE TABLE " + Table + "(" +
Student_ID + " INTEGER PRIMARY KEY, " +
Student_Name + " TEXT, " +
Student_Password + " TEXT, " +
Student_Gender + " TEXT, " +
Student_Age + " INTEGER, " +
Student_Course + " TEXT, " +
Student_Modules + "TEXT)"
);
Log.d("DB", "DB Created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Table);
onCreate(db);
}
public static Cursor getData(DB db)
{
SQLiteDatabase SQ = db.getReadableDatabase();
String[] columns ={tableColumns.Student_ID, tableColumns.Student_Password};
Cursor cursor = SQ.query(tableColumns.Table, columns, null, null, null, null, null);
return cursor;
}
public boolean insertStudent(String name, String gender, int age, String password, String course, String modules) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Student_Name, name);
contentValues.put(Student_Password, password);
contentValues.put(Student_Gender, gender);
contentValues.put(Student_Age, age);
contentValues.put(Student_Course, course);
contentValues.put(Student_Modules, modules);
db.insert(Table, null, contentValues);
//Log for admin insert
//Log.d("DB", "Inserted Successfully");
return true;
}
}
And my tableStudents.java for controlling the students table
package com.example.project;
import android.provider.BaseColumns;
public class tableStudents {
//Constructor
public tableStudents()
{
}
public static abstract class tableColumns implements BaseColumns
{
public static final String Student_ID= "Student_ID";
public static final String Student_Password = "Student_Password";
public static final String Student_Gender = "gender";
public static final String Student_Age = "age";
public static final String Student_Course = "course";
public static final String Student_Modules = "modules";
public static final String Database = "databasename";
public static final String Table = "tablename";
}
}
1) To instantiate and insert data -
In your main activity
DB db = new DB(this);
db.insertStudent(name, gender, age, password, course, modules);
2) For convenience, consider
Student.java
public class Student{
public String name, gender, password, course, modules;
public int age;
Student(){ //constructor
}
Student(String name, String gender, int age, String password, String course, String modules){ //constructor
this.name = name;
this.gender = gender;
this.age = age;
this.password = password;
this.course = course;
this.modules = modules;
}
}
Now modify your getData function in DB.java to this -
public List<Student> getData() {
List<Student> studentList = new ArrayList<Student>();
// Select All Query
String selectQuery = "SELECT * FROM " + Table;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Student student = new Student();
student.name = cursor.getString(0);
student.gender = cursor.getString(1);
student.age = Integer.parseInt(cursor.getString(2));
student.password = cursor.getString(3);
student.course = cursor.getString(4);
student.modules = cursor.getString(5);
studentList.add(student);
} while (cursor.moveToNext());
}
// return contact list
return studentList;
}
I'm coding for the first time in Android (Java) an application using a sqlite database.
Two activities must save some informations so I use in both a MySQLiteHelper to access the database.
I read here that building SQLiteOpenHelper as static data member could be a good practice so I did this.
The static factory method ensures that there exists only one DatabaseHelper instance at any time.
I create in each activity a SQLiteOpenHelper that uses the method getWritableDatabase() but I don't know where to use the close() method.
Should I put this method after every modification or once at the end of the activity ?
Thank you =)
You need to create a class where you put all your common methods, constants, variables, etc.
And then you would have to move the "getWritableDatabase()" in this class and pls. I would advice that you always remember to close your db calls. with the "close()".
But the actually solution am using here : is as follows :
In my app I have different db adapters and this is just an example :
package com.app.android;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
public static final String TAG = "DBAdapter";
//public static final String DATABASE_NAME = "my_db";
//public static final String DATABASE_TABLE = "contacts";
//public static final int DATABASE_VERSION = 1;
public static final String START_TBL_CREATION = "create table "+Appiah.DATABASE_TABLE+" (_id integer primary key autoincrement, ";
public static final String [] TABLE_COLUMNS_TO_BE_CREATED = new String []{
KEY_NAME+" text not null, ",
KEY_EMAIL+" text not null"
};
public static final String END_TBL_CREATION = ");";
private static final String DATABASE_CREATE = START_TBL_CREATION
+ TABLE_COLUMNS_TO_BE_CREATED[0]
+ TABLE_COLUMNS_TO_BE_CREATED[1]
+ END_TBL_CREATION;
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter (Context ctx){
this.context = ctx;
DBHelper = new DatabaseHelper(context);//there would be an error initially but just keep going...
}
private static class DatabaseHelper extends SQLiteOpenHelper{//after importing for "SQLiteOpenHelper", Add unimplemented methods
DatabaseHelper(Context context){
super (context, Appiah.DATABASE_NAME, null, Appiah.DATABASE_VERSION);//pls. note : "Appiah" is the class in which all the common methods, variables, etc. are sitting.
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(DATABASE_CREATE);
}catch(SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version "+ oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
//opens the database
public DBAdapter open() throws SQLiteException{
db = DBHelper.getWritableDatabase();
return this;
}
//closes the database
public void close(){
DBHelper.close();
}
//insert a contact into the database
public long insertContact(String name, String email){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_EMAIL, email);
return db.insert(Appiah.DATABASE_TABLE, null, initialValues);
}
//deletes a particular contact
public boolean deleteContact(long rowId){
String whereClause = KEY_ROWID + "=" + rowId;
String[] whereArgs = null;
return db.delete(Appiah.DATABASE_TABLE, whereClause, whereArgs) > 0;
}
//retrieves all the contacts
public Cursor getAllContacts(){
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_EMAIL};
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
return db.query(Appiah.DATABASE_TABLE, columns, selection, selectionArgs, groupBy, having, orderBy);
}
//retrieve a particular contact with ID as input
public Cursor getContact_with_ID(long rowId) throws SQLException {
boolean distinct = true;
String table = Appiah.DATABASE_TABLE;
String [] columns = new String []{KEY_ROWID, KEY_NAME, KEY_EMAIL};
String selection = KEY_ROWID + "=" + rowId;
String [] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
Cursor mCursor = db.query(distinct, table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if(mCursor != null){
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor getContact_with_nameEntered(String name_str) throws SQLException {
boolean distinct = true;
String table = Appiah.DATABASE_TABLE;
String [] columns = new String []{KEY_ROWID, KEY_NAME, KEY_EMAIL};
String selection = KEY_NAME + "=" + name_str;//check again and do "%" thing to expand scope and increase chances of a name getting found or populated
String [] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
Cursor mCursor = db.query(distinct, table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if(mCursor != null){
mCursor.moveToFirst();
}
return mCursor;
}
//update a contact
public boolean updateContact(long rowId, String name, String email){
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_EMAIL, email);
String table = Appiah.DATABASE_TABLE;
ContentValues values = args;
String whereClause = KEY_ROWID + "=" + rowId;
String []whereArgs = null;
return db.update(table, values, whereClause, whereArgs) > 0;
}
/*
TO USE ANY OF THE ABOVE METHODS :
1. type this before in your "onCreate()" : DBAdapter db = new DBAdapter(this);
2. in the special case of getting all contacts to display : do the ff :
db.open();
Cursor c = db.getAllContacts();
if(c.moveToFirst()){
do{
textView.setText("ID : " + c.getString(0) + "\nName : " + c.getString(1) + "\nEmail Address : " + c.getString(2) );
}while(c.moveToNext());//the "while" added ensures that, the looping process occurs
}
db.close();
*/
}
I hope this helps. It can get deeper but I do hope this helps. All the best.
In my application I want save data in database.
Here is my code of SQLiteHelper
public class UserSqliteHelper extends SQLiteOpenHelper {
private final String LOGCAT = "JBF/SQLite";
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "jbfjsonEntityDB";
private static final String TABLE_NAME = "jbfjsonEntity";
private static final String KEY_JSON = "json";
private static final String KEY_URL_PATH = "url_path";
private static final String KEY_TIME = "added_on";
public UserSqliteHelper(Context context) {
super(context, "dictionarysqlitehelper.db", null, 1);
Log.d(LOGCAT, "Created");
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_JSON + " TEXT, "
+ KEY_TIME + " TIMESTAMP NOT NULL DEFAULT current_timestamp, "
+ KEY_URL_PATH + " TEXT )";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS " + TABLE_NAME ;
db.execSQL(query); onCreate(db);
}
public void addJsonEntity(JsonEntity jsonEntity) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_JSON, jsonEntity.getJson());
values.put(KEY_URL_PATH, jsonEntity.getUrl_path());
// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close();
}
public JSONObject getJsonByUrl(String url) {
String json = "";
SQLiteDatabase db = this.getReadableDatabase();
try {
// Cursor c = db.query(TABLE_NAME, null, KEY_URL_PATH + "=?", new String[]{url}, null, null, null);
String selectQuery = "SELECT * FROM " + TABLE_NAME + " where " + KEY_URL_PATH + "='"+url+"'";
Cursor c = db.rawQuery(selectQuery, null);
if (c == null) {
return null;
} else {
c.moveToFirst();
json =c.getString(c.getColumnIndex(KEY_JSON));
if (json != null) {
return new JSONObject(json);
} else {
return null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
When I call from my activity this
UserSqliteHelper sqliteHelper = new UserSqliteHelper(SplashActivity.this);
sqliteHelper.getWritableDatabase();
sqliteHelper.addJsonEntity(new JsonEntity(STRING_CONFIGS_URL,response.toString()));
System.out.println("json ==== "+sqliteHelper.getJsonByUrl(GET_USER_INFO_URL));
I always got this error
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
Could anyone tell me what I did wrong in here. Why I can't get my database values?
The query didn't match any data. moveToFirst() fails and the cursor doesn't point to a valid row. You should check that moveToFirst() succeeds - it returns a boolean.
Why it didn't match any data is because you're storing and retrieving data by different keys: STRING_CONFIGS_URL and GET_USER_INFO_URL.
instead of c==null try c.getColumnCount == 0