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.
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();
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.
I am abit confused why in the RoutineRetrieved function I am using result.getInt(2) when assigning the ACTIVITYIMAGE and result.getInt(3) when assigning the SLOT.... while in the ColourChange function I am using result.getInt(0) when assigning the DAY.
I previously assumed I was pointing to the columns in my sqlite database. But now I am confused. Could someone explain what these numbers mean?
RoutineRetrieved function:
private void routineRetrieved() {
Cursor result = myDb.retrieveRoutine(currentDay);
if (result.getCount() == 0) {
// Do nothing
} else {
while (result.moveToNext()) {
int ActivityImage = result.getInt(2);
int Slot = result.getInt(3);
ImageView emptySlot = (ImageView) findViewById(Slot);
emptySlot.setImageResource(ActivityImage);
}
}
}
ColourChange function:
private void colourChange() {
Cursor result = myDb.checkColour();
if (result.getCount() == 0) {
// Default colour remains
} else {
while (result.moveToNext()) {
String day = result.getString(0);
findViewById(getResources().getIdentifier(day + "button", "id", getPackageName()))
.setBackgroundColor(getResources().getColor(R.color.colorSuccess));
}
}
}
Database.java
public class Database extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "application.db";
public static final int DATABASE_VERSION = 9;
// Table Name
public static final String RoutineTable = "Routines";
// Column Names
public static final String RoutineColumn1 = "DayOfWeek";
public static final String RoutineColumn2 = "Activity";
public static final String RoutineColumn3 = "Slot";
public Database(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE `Routines` (`Routine` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,`DayOfWeek` TEXT NOT NULL,`Activity` INTEGER NOT NULL, `Slot` INTEGER NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
onCreate(db);
}
public Cursor retrieveRoutine(String selectedDay) { WHERE DayOfWeek equals selectedDay and store this as result.
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("select * from " + RoutineTable + " WHERE DayOfWeek = '" + selectedDay + "'", null);
return result;
}
public boolean insertRoutine(int activityImage, String selectedDay, int activitySlot) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(RoutineColumn1,selectedDay);
contentValues.put(RoutineColumn2,activityImage);
contentValues.put(RoutineColumn3,activitySlot);
long result = db.insert(RoutineTable, null, contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor checkColour() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("SELECT DayOfWeek FROM " + RoutineTable + " GROUP BY DayOfWeek", null);
return result;
}
The number parameter in the methods getInt and getString is index, starting by 0, of the column you want to get, relatively to the query you've done.
You have 2 different queries. In the method checkColour() you have the following query, which have only one field:
"SELECT DayOfWeek FROM " + RoutineTable + " GROUP BY DayOfWeek"
So, when you call
Cursor result = myDb.retrieveRoutine(currentDay);
String fieldValue = result.getString(0);
fieldValue will have the value of the first field of the query, in this case DayOfWeek
The same in the other query, that is a SELECT * of the table Routines. In this case the index refers to the field position in the CREATE TABLE statement.
I'm developing an app that uses SQLite database to store some info. When I run the app on an emulator or on my physical device plugger via USB from android studio, it works fine. However, when I use an APK version (send via email or installed from the play store) the database works but the insertRow command doesn't seem to work. All the other command seems to work for as far as I can test them. I already tried to uninstall-reinstall multiple times without success.
DBadapter
public class DBAdapter {
/////////////////////////////////////////////////////////////////////
// Constants & Data
/////////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_IMM = "imm";
public static final String KEY_TYPE = "type";
public static final String KEY_WEIGHT = "weight";
public static final String KEY_CG = "cg";
public static final String KEY_LAT = "lat";
public static final String KEY_UNIT = "unit";
public static final String KEY_EXTRA1 = "extra1";
public static final String KEY_EXTRA2 = "extra2";
public static final String KEY_EXTRA3 = "extra3";
public static final String KEY_EXTRA4 = "extra4";
public static final String KEY_EXTRA5 = "extra5";
public static final String KEY_EXTRA6 = "extra6";
public static final String KEY_EXTRA7 = "extra7";
public static final String KEY_EXTRA8 = "extra8";
public static final String KEY_EXTRA9 = "extra9";
public static final String KEY_EXTRA10 = "extra10";
public static final String KEY_EXTRA11 = "extra11";
public static final String KEY_EXTRA12 = "extra12";
public static final String KEY_EXTRA13 = "extra13";
public static final String KEY_FUEL = "fuel";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_IMM = 1;
public static final int COL_TYPE = 2;
public static final int COL_WEIGHT = 3;
public static final int COL_CG = 4;
public static final int COL_LAT = 5;
public static final int COL_UNIT = 6;
public static final int COL_EXTRA1 = 7;
public static final int COL_EXTRA2 = 8;
public static final int COL_EXTRA3 = 9;
public static final int COL_EXTRA4 = 10;
public static final int COL_EXTRA5 = 11;
public static final int COL_EXTRA6 = 12;
public static final int COL_EXTRA7 = 13;
public static final int COL_EXTRA8 = 14;
public static final int COL_EXTRA9 = 15;
public static final int COL_EXTRA10 = 16;
public static final int COL_EXTRA11 = 17;
public static final int COL_EXTRA12 = 18;
public static final int COL_EXTRA13 = 19;
public static final int COL_FUEL = 20;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_IMM, KEY_TYPE, KEY_WEIGHT, KEY_CG, KEY_LAT, KEY_UNIT
, KEY_EXTRA1, KEY_EXTRA2, KEY_EXTRA3, KEY_EXTRA4, KEY_EXTRA5, KEY_EXTRA6, KEY_EXTRA7, KEY_EXTRA8, KEY_EXTRA9, KEY_EXTRA10
, KEY_EXTRA11
, KEY_EXTRA12, KEY_EXTRA13, KEY_FUEL
};
// DB info: its name, and the table we are using (just one).
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
// Track DB version if status1 new version of your app changes the format.
public static final int DATABASE_VERSION = 12; // version 9 online (needs 11) TODO <--- If you are adding or deleting KEYS, change the version #.
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is status1 required field (must be given status1 value).
// NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
+ KEY_IMM + " text not null, "
+ KEY_TYPE + " string , "
+ KEY_WEIGHT + " string , "
+ KEY_CG + " double , "
+ KEY_LAT + " double , "
+ KEY_UNIT + " string , "
+ KEY_EXTRA1 + " string , "
+ KEY_EXTRA2 + " string , "
+ KEY_EXTRA3 + " string , "
+ KEY_EXTRA4 + " string , "
+ KEY_EXTRA5 + " string , "
+ KEY_EXTRA6 + " string , "
+ KEY_EXTRA7 + " string , "
+ KEY_EXTRA8 + " string , "
+ KEY_EXTRA9 + " string , "
+ KEY_EXTRA10 + " string , "
+ KEY_EXTRA11 + " string , "
+ KEY_EXTRA12 + " string , "
+ KEY_EXTRA13 + " string , "
+ KEY_FUEL + " string "
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String imm, String type, String weight, String cg, String lat, String unit) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_IMM, imm);
initialValues.put(KEY_TYPE, type);
initialValues.put(KEY_WEIGHT, weight);
initialValues.put(KEY_CG, cg);
initialValues.put(KEY_LAT, lat);
initialValues.put(KEY_UNIT, unit);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete status1 row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
c.moveToLast();
if (c != null) {
c.moveToPrevious();
}
return c;
}
// Get status1 specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String imm, String weight, String cg, String lat) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_IMM, imm);
newValues.put(KEY_WEIGHT, weight);
newValues.put(KEY_CG, cg);
newValues.put(KEY_LAT, lat);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
// Change an existing row to be equal to new data.
public boolean save11Values(long rowId, String fuel, String extra1, String extra2, String extra3, String extra4, String extra5,
String extra6, String extra7, String extra8, String extra9, String extra10) {
String where = KEY_ROWID + "=" + rowId;
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
ContentValues newValues = new ContentValues();
newValues.put(KEY_FUEL, fuel);
newValues.put(KEY_EXTRA1, extra1);
newValues.put(KEY_EXTRA2, extra2);
newValues.put(KEY_EXTRA3, extra3);
newValues.put(KEY_EXTRA4, extra4);
newValues.put(KEY_EXTRA5, extra5);
newValues.put(KEY_EXTRA6, extra6);
newValues.put(KEY_EXTRA7, extra7);
newValues.put(KEY_EXTRA8, extra8);
newValues.put(KEY_EXTRA9, extra9);
newValues.put(KEY_EXTRA10, extra10);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
public boolean save14Values(long rowId, String fuel, String extra1, String extra2, String extra3, String extra4, String extra5,
String extra6, String extra7, String extra8, String extra9, String extra10, String extra11,
String extra12, String extra13) {
String where = KEY_ROWID + "=" + rowId;
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
ContentValues newValues = new ContentValues();
newValues.put(KEY_FUEL, fuel);
newValues.put(KEY_EXTRA1, extra1);
newValues.put(KEY_EXTRA2, extra2);
newValues.put(KEY_EXTRA3, extra3);
newValues.put(KEY_EXTRA4, extra4);
newValues.put(KEY_EXTRA5, extra5);
newValues.put(KEY_EXTRA6, extra6);
newValues.put(KEY_EXTRA7, extra7);
newValues.put(KEY_EXTRA8, extra8);
newValues.put(KEY_EXTRA9, extra9);
newValues.put(KEY_EXTRA10, extra10);
newValues.put(KEY_EXTRA11, extra11);
newValues.put(KEY_EXTRA12, extra12);
newValues.put(KEY_EXTRA13, extra13);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
//TODO on upgrade///////////////////
private static final String DATABASE_ALTER_1 = "ALTER TABLE "
+ DATABASE_TABLE + " ADD COLUMN " + KEY_EXTRA11 + " string;";
private static final String DATABASE_ALTER_2 = "ALTER TABLE "
+ DATABASE_TABLE + " ADD COLUMN " + KEY_EXTRA12 + " string;";
private static final String DATABASE_ALTER_3 = "ALTER TABLE "
+ DATABASE_TABLE + " ADD COLUMN " + KEY_EXTRA13 + " string;";
private static final String DATABASE_ALTER_4 = "ALTER TABLE "
+ DATABASE_TABLE + " ADD COLUMN " + KEY_FUEL + " string;";
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
if (oldVersion < 10) {
_db.execSQL(DATABASE_ALTER_1);
_db.execSQL(DATABASE_ALTER_2);
}
if (oldVersion < 11) {
_db.execSQL(DATABASE_ALTER_3);
}
if (oldVersion < 12) {
_db.execSQL(DATABASE_ALTER_4);
}
}
}
}
It appears that on a previous version of my database KEY_IMM to KEY_EXTRA10 were set as NOT NULL. Using (android:debuggable="true") allowed me to see it.
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.