Android - Displaying database information in another class - java

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

Related

How to Show SQLite table in Logcat

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

Authentication code not working in android studio(SQLite)

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.

Android SQLite Database : Cannot resolve constructor

I am trying to create a simple SQLite database in android. I am following this tutorial. But the code gives this error "Cannot resolve constructor Contact()". Below is the code for DatabaseHandler.java. I have pointed out the line where the error occurs so it's easy to understand.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Usama on 10/7/2017.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "favouritesmanager";
// Contacts table name
private static final String TABLE_CONTACTS = "favourites";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_ADRESS = "adress";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + KEY_ADRESS + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone Number
values.put(KEY_ADRESS, contact.getAdress()); //address
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact(); <<<< HERE IS THE ERROR
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
contact.setAdress(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
}
and here is the contact.java class
public class Contact {
int _id;
String _name;
String _phone_number;
String _adress;
// constructor
public Contact(int id, String name, String _phone_number, String adress){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
this._adress = adress;
}
// constructor
public Contact(String name, String _phone_number, String adress){
this._name = name;
this._phone_number = _phone_number;
this._adress = adress;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
// getting phone number
public String getPhoneNumber(){
return this._phone_number;
}
// setting phone number
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
//getting adress
public String getAdress(){
return this._adress;
}
//setting adress
public void setAdress(String adresstowrite){
this._adress = adresstowrite;
}
}
Any fixes for this error please?
Create empty constructor.
// Empty constructor
public Contact(){
}

Retrieve data from SQLite on android

I am trying to read data from SQLite in android using three parameters, id, name and date. For example, id="number" and name="something" and date between ("first date", "second date"). the problem is that, i cannot figure out what to do with the last function. There are two more parameters left and i dont know what to do or where to place it. So does anyone have any experience and familiar with this code style and can share or help me? (I take this code from book too and there was not any solution for related to this at all in the book.)
//Table person; It contain the same attribute as Person class
public static final class PersonTable
{
public static final String NAME = "Persons";
public static final class Cols
{
static final String ID = "id";
static final String NAME = "name";
static final String DATE = "date";
}
}
public class PersonCursorWrapper extends CursorWrapper
{
public PersonCursorWrapper(Cursor cursor)
{
super(cursor);
}
public Person getPerson()
{
int id = geIntI(getColumnIndex(PersonTable.Cols.ID));
String name = getString(getColumnIndex(PersonTable.Cols.NAME));
long date = getLong(getColumnIndex(PersonTable.Cols.DATE));
Person Person = new Person();
Person.id(id);
Person.setDate(new Date(date));
Person.setName(name);
return Person;
}
}
}
private PersonCursorWrapper queryPersons(String whereClause, String[] whereArgs)
{
Cursor cursor = mDatabase.query
(
PersonTable.NAME,
null,
whereClause,
whereArgs,
null,
null,
null
);
return new PersonCursorWrapper(cursor);
}
public Person getPerson(int id, String name, String date)
{
PersonCursorWrapper cursor = queryPersons(
PersonTable.Cols.ID + " = ?"+" "+
PersonTable.Cols.NAME + " = ?"+" "+
PersonTable.Cols.DATE + " = ?",
new String[] { id.toString() }
);
try
{
if (cursor.getCount() == 0)
{
return null;
}
cursor.moveToFirst();
return cursor.getPerson();
}
finally
{
cursor.close();
}
}
You have three parameter markers (?), so you have to give it three parameters:
cursor = queryPersons(
...,
new String[] { id.toString(), name, date }
);
For android sqlite database operations you can simply use SQLiteOpenHelper class provided with android.
This is a complete implementation for your case with SQLiteOpenHelper.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler2 extends SQLiteOpenHelper {
// Database details
private static final int DATABASE_VERSION = 1;
private static String DATABASE_NAME = "dbname.db";
// Table names
private static String TABLE_PERSON = "person";
// Table Columns name
private static final String COLUMN_ID = "workout_id";
private static final String COLUMN_NAME = "exercise_id";
// Create queries
private static final String CREATE_TABLE_PERSON = "CREATE TABLE " + TABLE_PERSON + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT NOT NULL)";
public DatabaseHandler2(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_PERSON);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_PERSON);
}
public Person getPerson(int id) {
Person person = new Person();
String selectQuery = "SELECT * FROM " + TABLE_PERSON + " WHERE " + COLUMN_ID + "=" + id;
SQLiteDatabase rdb;
rdb = this.getReadableDatabase();
Cursor cursor = rdb.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
person.setId(cursor.getInt(0));
person.setName(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
rdb.close();
return person;
}
public List<Person> getAllPersons() {
List<Person> personList = new ArrayList<Person>();
String selectQuery = "SELECT * FROM " + TABLE_PERSON;
SQLiteDatabase rdb;
rdb = this.getReadableDatabase();
Cursor cursor = rdb.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Person person = new Person();
person.setId(cursor.getInt(0));
person.setName(cursor.getString(1));
personList.add(person);
} while (cursor.moveToNext());
}
cursor.close();
rdb.close();
return personList;
}
public void savePerson(Person person) {
SQLiteDatabase wdb;
ContentValues values = new ContentValues();
values.put(COLUMN_ID, person.getId());
values.put(COLUMN_NAME, person.getName());
wdb = this.getWritableDatabase();
long rowId = wdb.insert(TABLE_PERSON, null, values);
wdb.close();
}
public void deletePerson(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_PERSON, COLUMN_ID + "='" + id + "'", null);
db.close();
}
public boolean renamePerson(int id, String newName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, newName);
int numOfRowsEffected = db.update(TABLE_PERSON, values, COLUMN_ID + "='" + id + "'", null);
db.close();
return numOfRowsEffected > 0 ? true : false;
}
}
Here is the Person class
public class Person {
private int id;
private String name;
public Person() {
}
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

What is the best way to use a single instance of SQLiteOpenHelper among two different activities?

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.

Categories