My application crashes when I do a SQL request.
It says that the table doesn't exist and I don't know why.
Could you help me?
Here is the logcat:
03-27 15:35:49.718 5672-5672/descartes.info.l3ag2.eyetrek E/AndroidRuntime: FATAL EXCEPTION: main
Process: descartes.info.l3ag2.eyetrek,
PID: 5672 android.database.sqlite.SQLiteException: no such table: bddchampignons (code 1):,
while compiling: SELECT * FROM bddchampignons
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
at descartes.info.l3ag2.eyetrek.classes.DatabaseHandler.getAllChampignons(DatabaseHandler.java:578)
at descartes.info.l3ag2.eyetrek.fragment.mushroomanalysis.FragmentCirconstance1.lambda$onCreateView$2$FragmentCirconstance1(FragmentCirconstance1.java:147)
at descartes.info.l3ag2.eyetrek.fragment.mushroomanalysis.FragmentCirconstance1$$Lambda$2.onClick(Unknown Source)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
this is the request I am doing :
List<Mushroom> MushroomList = new ArrayList<Mushroom>();
MushroomList = databaseHandler.getAllChampignons();
String res= "";
Log.e("List", MushroomList.toString());
for (Mushroom mushroom: MushroomList) {
Log.e("NAME", mushroom.getName());
res = res + mushroom.getId() + "\n";
}
createAlertBox("Resultats", res);
and this is a part of the code from my DataBaseHandler class where is the method getAllChampignons:
private static final String TABLE_CHAMPIGNON = "bddchampignons";
//(my csv file is named "bddchampignons")
public List<Mushroom> getAllChampignons() {
List<Mushroom> champignonsList = new ArrayList<Mushroom>();
String selectQuery = "SELECT * FROM " + TABLE_CHAMPIGNON;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Mushroom champ = new Mushroom();
champ.setId(Integer.parseInt(cursor.getString(0)));
champ.setName(cursor.getString(1));
champ.setDiametreMin(Integer.parseInt(cursor.getString(2)));
champ.setDiametreMax(Integer.parseInt(cursor.getString(3)));
champ.setCouleurChapeau(cursor.getString(4));
champ.setFormeChapeau(cursor.getString(5));
champ.setSurfaceChapeau(cursor.getString(6));
champ.setTypeMarge(cursor.getString(7));
champ.setCouleurMarge(cursor.getString(8));
champ.setDessousChapeau(cursor.getString(9));
champ.setCouleurDessousChapeau(cursor.getString(10));
champ.setOxydationChapeau(cursor.getString(11));
champ.setCouleurOxydationChapeau(cursor.getString(12));
champ.setInsertionDessousPied(cursor.getString(13));
champ.setEspaceLamelles(cursor.getString(14));
champ.setTypeLamelles(cursor.getString(15));
champ.setCouleurPied(cursor.getString(16));
champ.setPiedCreuxPlein(cursor.getString(17));
champ.setFormePied(cursor.getString(18));
champ.setLongueurPied(cursor.getString(19));
champ.setSurfacePied(cursor.getString(20));
champ.setPositionPiedChapeau(cursor.getString(21));
champ.setPresenceAnneau(cursor.getString(22));
champ.setOrientationAnneau(cursor.getString(23));
champ.setMobiliteAnneau(cursor.getString(24));
champ.setCouleurAnneau(cursor.getString(25));
champ.setPousseTouffe(cursor.getString(26));
champ.setCouleurBasePied(cursor.getString(27));
champ.setCouleurChair(cursor.getString(28));
champ.setOxydationChair(cursor.getString(29));
champ.setCouleurOxydationChair(cursor.getString(30));
champ.setFermeteChair(cursor.getString(31));
champ.setOdeur(cursor.getString(32));
champ.setLatex(cursor.getString(33));
champ.setCouleurLatex(cursor.getString(34));
champ.setMoisPousseTot(cursor.getString(35));
champ.setMoisPousseTard(cursor.getString(36));
champ.setMilieu(cursor.getString(37));
champ.setPousseBois(cursor.getString(38));
champ.setNomVernaculaire(cursor.getString(39));
champ.setComestibilite(cursor.getString(40));
champ.setCommentaires(cursor.getString(41));
champ.setSynonymes(cursor.getString(42));
champignonsList.add(champ);
} while (cursor.moveToNext());
}
return champignonsList;
}
this is my DataBaseHandler classe where I created my table, but it doesn't work ..
I'm just showing you the part where it's about champignons(mushrooms)
and you can find :
- method onCreate where the table champignons is created
- method to create an Mushroom Object
- method which return a list with the elements corresponding to the SQL request
- method which return a list with all the elements of the database
- method
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "db_eyetrek";
private static final String TABLE_CHAMPIGNON = "bddchampignons";
private static final String CHAMP_ID = "id";
private static final String CHAMP_NAME = "name";
private static final String CHAMP_DIAMETRE_MIN = "diametreMin";
private static final String CHAMP_DIAMETRE_MAX = "diametreMax";
private static final String COULEUR_CHAPEAU = "couleurChapeau";
private static final String FORME_CHAPEAU = "formeChapeau";
private static final String SURFACE_CHAPEAU = "surfaceChapeau";
private static final String TYPE_MARGE= "typeMarge";
private static final String COULEUR_MARGE = "couleurMarge";
private static final String DESSOUS_CHAPEAU = "dessousChapeau";
private static final String COULEUR_DESSOUS_CHAPEAU = "couleurDessousChapeau";
private static final String OXYDATION_CHAPEAU = "oxydationChapeau";
private static final String COULEUR_OXYDATION_CHAPEAU = "couleurOxydationChapeau";
private static final String INSERTION_DESSOUS_PIED= "insertionDessousPied";
private static final String ESPACE_LAMELLES = "espaceLamelles";
private static final String TYPE_LAMELLES = "typeLamelles";
private static final String COULEUR_PIED = "couleurPied";
private static final String PIED_CREUX_PLEIN = "piedCreuxPlein";
private static final String FORME_PIED = "formePied";
private static final String LONGEUR_PIED = "longueurPied";
private static final String SURFACE_PIED = "surfacePied";
private static final String POSITION_PIED_CHAPEAU = "positionPiedChapeau";
private static final String PRESENCE_ANNEAU = "presenceAnneau";
private static final String ORIENTATION_ANNEAU = "orientationAnneau";
private static final String MOBILITE_ANNEAU = "mobiliteAnneau";
private static final String COULEUR_ANNEAU = "couleurAnneau";
private static final String POUSSE_TOUFFE = "pousseTouffe";
private static final String COULEUR_BASE_PIED = "couleurBasePied";
private static final String COULEUR_CHAIR = "couleurChair";
private static final String OXYDATION_CHAIR = "oxydationChair";
private static final String COULEUR_OXYDATION_CHAIR = "couleurOxydationChair";
private static final String FERMETE_CHAIR = "fermeteChair";
private static final String ODEUR = "odeur";
private static final String LATEX = "latex";
private static final String COULEUR_LATEX = "couleurLatex";
private static final String MOIS_POUSSE_TOT = "moisPousseTot";
private static final String MOIS_POUSSE_TARD = "moisPousseTard";
private static final String MILIEU = "milieu";
private static final String POUSSE_BOIS = "pousseBois";
private static final String NOM_VERNACULAIRE = "nomVernaculaire";
private static final String COMESTIBILITE = "comestibilite";
private static final String COMMENTAIRES = "commentaires";
private static final String SYNONYMES = "synonymes";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
getReadableDatabase();
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
//Création de la table champignon
String CREATE_CHAMPIGNON_TABLE = "create table if not exists " + TABLE_CHAMPIGNON + " ("
+ CHAMP_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + CHAMP_NAME + " VARCHAR (40),"
+ CHAMP_DIAMETRE_MIN + " INTEGER (2)," + CHAMP_DIAMETRE_MAX + " VARCHAR(3) ," + COULEUR_CHAPEAU + " VARCHAR (30)," + FORME_CHAPEAU + " VARCHAR (70),"
+ SURFACE_CHAPEAU + " VARCHAR (105)," + TYPE_MARGE + " VARCHAR (101)," + COULEUR_MARGE + " VARCHAR (11)," + DESSOUS_CHAPEAU + " VARCHAR (26),"
+ COULEUR_DESSOUS_CHAPEAU + " VARCHAR (29)," + OXYDATION_CHAPEAU + " VARCHAR(20)," + COULEUR_OXYDATION_CHAPEAU + " VARCHAR(14)," + INSERTION_DESSOUS_PIED + " VARCHAR (46),"
+ ESPACE_LAMELLES + " VARCHAR (8)," + TYPE_LAMELLES + " VARCHAR (34)," + COULEUR_PIED + " VARCHAR (22)," + PIED_CREUX_PLEIN + " VARCHAR (21),"
+ FORME_PIED + " VARCHAR (165)," + LONGEUR_PIED + " VARCHAR (10)," + SURFACE_PIED + " VARCHAR (84)," + POSITION_PIED_CHAPEAU + " VARCHAR (9),"
+ PRESENCE_ANNEAU + " VARCHAR (3)," + ORIENTATION_ANNEAU + " VARCHAR (10)," + MOBILITE_ANNEAU + " VARCHAR (6)," + COULEUR_ANNEAU + " VARCHAR (43),"
+ POUSSE_TOUFFE + " VARCHAR (3),"+ COULEUR_BASE_PIED + " VARCHAR (21)," + COULEUR_CHAIR + " VARCHAR (30)," + OXYDATION_CHAIR + " VARCHAR (3),"
+ COULEUR_OXYDATION_CHAIR + " VARCHAR (21)," + FERMETE_CHAIR + " VARCHAR (16)," + ODEUR + " VARCHAR (25)," + LATEX + " VARCHAR (3)," + COULEUR_LATEX + " VARCHAR (14),"
+ MOIS_POUSSE_TOT + " VARCHAR (19)," + MOIS_POUSSE_TARD + " VARCHAR (20)," + MILIEU + " VARCHAR (49)," + POUSSE_BOIS + " VARCHAR (3)," + NOM_VERNACULAIRE + " VARCHAR (87),"
+ COMESTIBILITE + " VARCHAR (18)," + COMMENTAIRES + " VARCHAR (332)," + SYNONYMES + " VARCHAR (34) )";
sqLiteDatabase.execSQL(CREATE_CHAMPIGNON_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_DIDACTICIEL);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_LEAFS);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_ANIMAL);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CHAMPIGNON);
onCreate(sqLiteDatabase);
}
public void addChampignon (Mushroom champignon) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CHAMP_NAME, champignon.getName());
values.put(CHAMP_DIAMETRE_MIN, champignon.getDiametreMin());
values.put(CHAMP_DIAMETRE_MAX, champignon.getDiametreMax());
values.put(COULEUR_CHAPEAU, champignon.getCouleurChapeau());
values.put(FORME_CHAPEAU, champignon.getFormeChapeau());
values.put(SURFACE_CHAPEAU, champignon.getSurfaceChapeau());
values.put(TYPE_MARGE, champignon.getTypeMarge());
values.put(COULEUR_MARGE, champignon.getCouleurMarge());
values.put(DESSOUS_CHAPEAU, champignon.getDessousChapeau());
values.put(COULEUR_DESSOUS_CHAPEAU,champignon.getCouleurDessousChapeau());
values.put(OXYDATION_CHAPEAU, champignon.getOxydationChapeau());
values.put(COULEUR_OXYDATION_CHAPEAU, champignon.getCouleurOxydationChapeau());
values.put(INSERTION_DESSOUS_PIED, champignon.getInsertionDessousPied());
values.put(ESPACE_LAMELLES, champignon.getEspaceLamelles());
values.put(TYPE_LAMELLES, champignon.getTypeLamelles());
values.put(COULEUR_PIED, champignon.getCouleurPied());
values.put(PIED_CREUX_PLEIN, champignon.getPiedCreuxPlein());
values.put(FORME_PIED, champignon.getFormePied());
values.put(LONGEUR_PIED, champignon.getLongueurPied());
values.put(SURFACE_PIED, champignon.getSurfacePied());
values.put(POSITION_PIED_CHAPEAU, champignon.getPositionPiedChapeau());
values.put(PRESENCE_ANNEAU, champignon.getPresenceAnneau());
values.put(ORIENTATION_ANNEAU, champignon.getOrientationAnneau());
values.put(MOBILITE_ANNEAU, champignon.getMobiliteAnneau());
values.put(COULEUR_ANNEAU, champignon.getCouleurAnneau());
values.put(POUSSE_TOUFFE, champignon.getPousseTouffe());
values.put(COULEUR_BASE_PIED, champignon.getCouleurBasePied());
values.put(COULEUR_CHAIR, champignon.getCouleurChair());
values.put(OXYDATION_CHAIR, champignon.getCouleurOxydationChair());
values.put(COULEUR_OXYDATION_CHAIR, champignon.getCouleurOxydationChair());
values.put(FERMETE_CHAIR, champignon.getFermeteChair());
values.put(ODEUR, champignon.getOdeur());
values.put(LATEX, champignon.getLatex());
values.put(COULEUR_LATEX, champignon.getCouleurLatex());
values.put(MOIS_POUSSE_TOT, champignon.getMoisPousseTot());
values.put(MOIS_POUSSE_TARD, champignon.getMoisPousseTard());
values.put(MILIEU, champignon.getMilieu());
values.put(POUSSE_BOIS, champignon.getPousseBois());
values.put(NOM_VERNACULAIRE, champignon.getNomVernaculaire());
values.put(COMESTIBILITE, champignon.getComestibilite());
values.put(COMMENTAIRES, champignon.getCommentaires());
values.put(SYNONYMES, champignon.getSynonymes());
db.insert(TABLE_CHAMPIGNON, null, values);
db.close();
}
/**
* Retourne une liste des champignons correspondant à la requête
*
* #param query
* #return
*/
public List<Mushroom> getChampignonFromRequest(String query) {
List<Mushroom> mushroomList = new ArrayList<Mushroom>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
Mushroom champ = new Mushroom();
champ.setId(Integer.parseInt(cursor.getString(0)));
champ.setName(cursor.getString(1));
champ.setDiametreMin(Integer.parseInt(cursor.getString(2)));
champ.setDiametreMax(Integer.parseInt(cursor.getString(3)));
champ.setCouleurChapeau(cursor.getString(4));
champ.setFormeChapeau(cursor.getString(5));
champ.setSurfaceChapeau(cursor.getString(6));
champ.setTypeMarge(cursor.getString(7));
champ.setCouleurMarge(cursor.getString(8));
champ.setDessousChapeau(cursor.getString(9));
champ.setCouleurDessousChapeau(cursor.getString(10));
champ.setOxydationChapeau(cursor.getString(11));
champ.setCouleurOxydationChapeau(cursor.getString(12));
champ.setInsertionDessousPied(cursor.getString(13));
champ.setEspaceLamelles(cursor.getString(14));
champ.setTypeLamelles(cursor.getString(15));
champ.setCouleurPied(cursor.getString(16));
champ.setPiedCreuxPlein(cursor.getString(17));
champ.setFormePied(cursor.getString(18));
champ.setLongueurPied(cursor.getString(19));
champ.setSurfacePied(cursor.getString(20));
champ.setPositionPiedChapeau(cursor.getString(21));
champ.setPresenceAnneau(cursor.getString(22));
champ.setOrientationAnneau(cursor.getString(23));
champ.setMobiliteAnneau(cursor.getString(24));
champ.setCouleurAnneau(cursor.getString(25));
champ.setPousseTouffe(cursor.getString(26));
champ.setCouleurBasePied(cursor.getString(27));
champ.setCouleurChair(cursor.getString(28));
champ.setOxydationChair(cursor.getString(29));
champ.setCouleurOxydationChair(cursor.getString(30));
champ.setFermeteChair(cursor.getString(31));
champ.setOdeur(cursor.getString(32));
champ.setLatex(cursor.getString(33));
champ.setCouleurLatex(cursor.getString(34));
champ.setMoisPousseTot(cursor.getString(35));
champ.setMoisPousseTard(cursor.getString(36));
champ.setMilieu(cursor.getString(37));
champ.setPousseBois(cursor.getString(38));
champ.setNomVernaculaire(cursor.getString(39));
champ.setComestibilite(cursor.getString(40));
champ.setCommentaires(cursor.getString(41));
champ.setSynonymes(cursor.getString(42));
mushroomList.add(champ);
} while (cursor.moveToNext());
}
cursor.close();
return mushroomList;
}
/**
* Ajout des Champignons depuis& un CSV
*
* #param inputStream
* #param context
*/
public void addChampignonFromCsv(InputStream inputStream, Context context) {
DatabaseHandler db = new DatabaseHandler(context);
Scanner scanner = new Scanner(inputStream);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String str[] = line.split(";");
db.addChampignon(new Mushroom(Integer.parseInt(str[0]), str[1], Integer.parseInt(str[2]), Integer.parseInt(str[3]),str[4],str[5],
str[6],str[7],str[8],str[9],str[10],str[11],str[12],str[13],str[14],str[15],
str[16],str[17],str[18],str[19],str[20],str[21],str[22],str[23],str[24],str[25],
str[26],str[27],str[28],str[29],str[30],str[31],str[32],str[33],str[34],str[35],
str[36],str[37],str[38],str[39],str[40],str[41],str[42]));
}
scanner.close();
}
/**
* Retourne tous les champignons de la base de données
*
* #return
*/
public List<Mushroom> getAllChampignons() {
List<Mushroom> champignonsList = new ArrayList<Mushroom>();
String selectQuery = "SELECT * FROM " + TABLE_CHAMPIGNON;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Mushroom champ = new Mushroom();
champ.setId(Integer.parseInt(cursor.getString(0)));
champ.setName(cursor.getString(1));
champ.setDiametreMin(Integer.parseInt(cursor.getString(2)));
champ.setDiametreMax(Integer.parseInt(cursor.getString(3)));
champ.setCouleurChapeau(cursor.getString(4));
champ.setFormeChapeau(cursor.getString(5));
champ.setSurfaceChapeau(cursor.getString(6));
champ.setTypeMarge(cursor.getString(7));
champ.setCouleurMarge(cursor.getString(8));
champ.setDessousChapeau(cursor.getString(9));
champ.setCouleurDessousChapeau(cursor.getString(10));
champ.setOxydationChapeau(cursor.getString(11));
champ.setCouleurOxydationChapeau(cursor.getString(12));
champ.setInsertionDessousPied(cursor.getString(13));
champ.setEspaceLamelles(cursor.getString(14));
champ.setTypeLamelles(cursor.getString(15));
champ.setCouleurPied(cursor.getString(16));
champ.setPiedCreuxPlein(cursor.getString(17));
champ.setFormePied(cursor.getString(18));
champ.setLongueurPied(cursor.getString(19));
champ.setSurfacePied(cursor.getString(20));
champ.setPositionPiedChapeau(cursor.getString(21));
champ.setPresenceAnneau(cursor.getString(22));
champ.setOrientationAnneau(cursor.getString(23));
champ.setMobiliteAnneau(cursor.getString(24));
champ.setCouleurAnneau(cursor.getString(25));
champ.setPousseTouffe(cursor.getString(26));
champ.setCouleurBasePied(cursor.getString(27));
champ.setCouleurChair(cursor.getString(28));
champ.setOxydationChair(cursor.getString(29));
champ.setCouleurOxydationChair(cursor.getString(30));
champ.setFermeteChair(cursor.getString(31));
champ.setOdeur(cursor.getString(32));
champ.setLatex(cursor.getString(33));
champ.setCouleurLatex(cursor.getString(34));
champ.setMoisPousseTot(cursor.getString(35));
champ.setMoisPousseTard(cursor.getString(36));
champ.setMilieu(cursor.getString(37));
champ.setPousseBois(cursor.getString(38));
champ.setNomVernaculaire(cursor.getString(39));
champ.setComestibilite(cursor.getString(40));
champ.setCommentaires(cursor.getString(41));
champ.setSynonymes(cursor.getString(42));
champignonsList.add(champ);
} while (cursor.moveToNext());
}
return champignonsList;
}
Related
so I'm developing this app which uses SQLite database and displays it in a TableLayout in android studio. Now I want a button to export the data in the TableLayout to an Excel sheet. I'm using this library to do it: https://github.com/androidmads/SQLite2XL
and my database doesn't have a name for it. This is my DBHelper.java:-
package com.kbjg.frissco.eattendence;
import android.annotation.SuppressLint;
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.SQLiteOpenHelper;
import android.os.Build;
import androidx.annotation.Nullable;
import java.util.PrimitiveIterator;
public class DBHelper extends SQLiteOpenHelper {
private static final int VERSION = 2;
//class table
public static final String CLASS_TABLE_NAME = "CLASS_TABLE";
public static final String C_ID = "_CID";
public static final String CLASS_NAME_KEY = "CLASS_NAME";
public static final String SUBJECT_NAME_KEY = "SUBJECT_NAME";
private static final String CREATE_CLASS_TABLE =
"CREATE TABLE " + CLASS_TABLE_NAME + "( " +
C_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
CLASS_NAME_KEY + " TEXT NOT NULL, " +
SUBJECT_NAME_KEY + " TEXT NOT NULL, " +
"UNIQUE (" + CLASS_NAME_KEY + "," + SUBJECT_NAME_KEY + ")" +
");";
private static final String DROP_CLASS_TABLE = "DROP TABLE IF EXISTS " + CLASS_TABLE_NAME;
private static final String SELECT_CLASS_TABLE = "SELECT * FROM " + CLASS_TABLE_NAME;
//student table
private static final String STUDENT_TABLE_NAME = "STUDENT_TABLE";
public static final String S_ID = "_SID";
public static final String STUDENT_NAME_KEY = "STUDENT_NAME";
public static final String STUDENT_ROLL_KEY = "ROLL";
private static final String CREATE_STUDENT_TABLE =
"CREATE TABLE " + STUDENT_TABLE_NAME +
"( " +
S_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
C_ID + " INTEGER NOT NULL, " +
STUDENT_NAME_KEY + " TEXT NOT NULL, " +
STUDENT_ROLL_KEY + " INTEGER, " +
" FOREIGN KEY ( " + C_ID + ") REFERENCES " + CLASS_TABLE_NAME + "(" + C_ID + ")" +
");";
private static final String DROP_STUDENT_TABLE = "DROP TABLE IF EXISTS " + STUDENT_TABLE_NAME;
private static final String SELECT_STUDENT_TABLE = "SELECT * FROM " + STUDENT_TABLE_NAME;
//STATUS TABLE
private static final String STATUS_TABLE_NAME = "STATUS_TABLE";
public static final String STATUS_ID = "_STATUS_ID";
public static final String DATE_KEY = "STATUS_DATE";
public static final String STATUS_KEY = "STATUS";
private static final String CREATE_STATUS_TABLE =
"CREATE TABLE " + STATUS_TABLE_NAME +
"(" +
STATUS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
S_ID + " INTEGER NOT NULL, " +
C_ID + " INTEGER NOT NULL, " +
DATE_KEY + " DATE NOT NULL, " +
STATUS_KEY + " TEXT NOT NULL, " +
" UNIQUE (" + S_ID + "," + DATE_KEY + ")," +
" FOREIGN KEY (" + S_ID + ") REFERENCES " + STUDENT_TABLE_NAME + "( " + S_ID + ")," +
" FOREIGN KEY (" + C_ID + ") REFERENCES " + CLASS_TABLE_NAME + "( " + C_ID + ")" +
");";
private static final String DROP_STATUS_TABLE = "DROP TABLE IF EXISTS " + STATUS_TABLE_NAME;
private static final String SELECT_STATUS_TABLE = "SELECT * FROM " + STATUS_TABLE_NAME;
public DBHelper(#Nullable Context context) {
super(context, "Attendance.db", null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_CLASS_TABLE);
db.execSQL(CREATE_STUDENT_TABLE);
db.execSQL(CREATE_STATUS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_CLASS_TABLE);
db.execSQL(DROP_STUDENT_TABLE);
db.execSQL(DROP_STATUS_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
long addClass(String className,String subjectName){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CLASS_NAME_KEY,className);
values.put(SUBJECT_NAME_KEY,subjectName);
return database.insert(CLASS_TABLE_NAME,null,values);
}
Cursor getClassTable(){
SQLiteDatabase database = this.getReadableDatabase();
return database.rawQuery(SELECT_CLASS_TABLE,null);
}
int deleteClass(long cid){
SQLiteDatabase database = this.getReadableDatabase();
return database.delete(CLASS_TABLE_NAME,C_ID+"=?",new String[]{String.valueOf(cid)});
}
long updateClass(long cid,String className,String subjectName){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CLASS_NAME_KEY,className);
values.put(SUBJECT_NAME_KEY,subjectName);
return database.update(CLASS_TABLE_NAME,values,C_ID+"=?",new String[]{String.valueOf(cid)});
}
long addStudent(long cid,int roll,String name){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(C_ID,cid);
values.put(STUDENT_ROLL_KEY,roll);
values.put(STUDENT_NAME_KEY,name);
return database.insert(STUDENT_TABLE_NAME,null,values);
}
Cursor getStudentTable(long cid){
SQLiteDatabase database = this.getReadableDatabase();
return database.query(STUDENT_TABLE_NAME,null,C_ID+"=?",new String[]{String.valueOf(cid)},null,null,STUDENT_ROLL_KEY);
}
int deleteStudent(long sid){
SQLiteDatabase database = this.getReadableDatabase();
return database.delete(STUDENT_TABLE_NAME,S_ID+"=?",new String[]{String.valueOf(sid)});
}
long updateStudent(long sid,String name){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(STUDENT_NAME_KEY,name);
return database.update(STUDENT_TABLE_NAME,values,S_ID+"=?",new String[]{String.valueOf(sid)});
}
long addStatus(long sid,long cid, String date, String status){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(S_ID,sid);
values.put(C_ID,cid);
values.put(DATE_KEY,date);
values.put(STATUS_KEY,status);
return database.insert(STATUS_TABLE_NAME,null,values);
}
long updateStatus(long sid,String date,String status){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(STATUS_KEY,status);
String whereClause = DATE_KEY +"='"+date+"' AND "+S_ID+"="+sid;
return database.update(STATUS_TABLE_NAME,values,whereClause,null);
}
#SuppressLint("Range")
String getStatus(long sid, String date){
String status=null;
SQLiteDatabase database = this.getReadableDatabase();
String whereClause = DATE_KEY +"='"+date+"' AND "+S_ID+"="+sid;
Cursor cursor = database.query(STATUS_TABLE_NAME,null,whereClause,null,null,null,null);
if(cursor.moveToFirst()) {
status = cursor.getString(cursor.getColumnIndex(STATUS_KEY));
}
return status;
}
Cursor getDistinctMonths(long cid){
SQLiteDatabase database = this.getReadableDatabase();
return database.query(STATUS_TABLE_NAME,new String[]{DATE_KEY},C_ID+"="+cid,null,"substr("+DATE_KEY+",4,7)",null,null);//23.01.2022
}
}
and this is the code I used to generate the Excel sheet:-
csv_maker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
String directory_path = Environment.getExternalStorageDirectory().getPath() + "/Project Brown/";
File file = new File(directory_path);
if (!file.exists()) {
file.mkdirs();
}
// Export SQLite DB as EXCEL FILE
SQLiteToExcel sqliteToExcel = new SQLiteToExcel(getApplicationContext(), DBHelper.CLASS_NAME_KEY);
sqliteToExcel.exportAllTables("users.xls", new SQLiteToExcel.ExportListener() {
#Override
public void onStart() {
}
#Override
public void onCompleted(String filePath) {
Toast.makeText(SheetActivity.this, "Excel Exported", Toast.LENGTH_SHORT).show();;
}
#Override
public void onError(Exception e) {
}
});
}
});
Actually what happening is when I click the button a directory is created but the is not generated. Kindly help me. Thanks in Advance.
I have 2 table Employee and order table, I'm trying to implement those tables into the same databasehelper class, but is gives me several errors, should i create a another databasehelper class, or can i implement these to into one
tables are looks like this
`public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "shopinstyle.db";
private static final String DB_TABLE = "Employee";
private static final String ORDER_TABLE = "Order";
//Employee
//columns
private static final String ID = "ID";
private static final String FNAME = "FNAME";
private static final String LNAME = "LNAME";
private static final String PNUMBER = "PNUMBER";
private static final String EMAIL = "EMAIL";
private static final String NIC = "NIC";
//Order
//columns
private static final String ord_ID = "ord_ID";
private static final String ord_Name = "ord_Name";
private static final String ord_Qty = "ord_Qty";
private static final String ord_Price = "ord_Price";
private static final String ord_Location = "ord_Location";
private static final String CREATE_TABLE = "CREATE TABLE " + DB_TABLE + " (" +
ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
FNAME + " TEXT, " +
LNAME + " TEXT, " +
PNUMBER + " TEXT, " +
EMAIL + " TEXT, " +
NIC + " TEXT" + ")";
private static final String CREATE_TABLE_ORDER = "CREATE TABLE " + ORDER_TABLE + " (" +
ord_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
ord_Name + " TEXT, " +
ord_Qty + " TEXT, " +
ord_Price + " TEXT, " +
ord_Location + " TEXT " + ")";
public DatabaseHelper(Context context) {
super(context, DB_NAME,ORDER_TABLE, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_TABLE);
sqLiteDatabase.execSQL(CREATE_TABLE_ORDER);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + ORDER_TABLE);
onCreate(sqLiteDatabase);
}`
there is a error in this line
public DatabaseHelper(Context context) {
super(context, DB_NAME,ORDER_TABLE, null, 1);
}
The 3d argument in the cal of super() inside the constructor of the DatabaseHelper class is factory which you can pass as null and not a table's name:
super(context, DB_NAME,null, 1);
I Have Total 5 Table in SQLite database So if i create a all table in DatabaseHalper.class and perform all CRUD((Create, Read, Update and Delete)) Operation in this class then this is look like a Big Data
Table Is Like: Company, Contact, ToDo. etc
So 1st I Want to create a multiple table in DatabaseHalper.class
2nd Create a another class Like using Table Name ComapnyDB.class
In this Class i want to Perform CRUD operation for a Company Table also All query perform for Company table
3rd same for Contact table. Create table in DatabaseHalper.class
and create a new class like Contact.class in this class perform all CURD operation and perform other operation
So this way my code was Divided in different different class
For Example Below class is my DatabseHalper.class and in this class i'll create a Database Tables.
DatabaseHalper.class
public class DatabaseHelper extends SQLiteOpenHelper {
// Logcat tag
private static final String LOG = "DatabaseHelper";
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
//Tables Name
private static final String COMPANY = "company";
private static final String CONTACTS = "contacts";
private static final String EVENT = "event";
private static final String TODO = "todo";
private static final String USER = "user";
// Common column names
private static final String KEY_ID = "id";
//Companies Table Column Name
private static final String KEY_COMPANY_ID = "CompanyId";
private static final String KEY_COMPANY_REFERENCE_ID = "ReferenceId";
private static final String KEY_COMPANY_NAME = "CompanyName";
private static final String KEY_COMPANY_WEBSITE = "CompanyWebsite";
private static final String KEY_COMPANY_EMAIL = "CompanyEmail";
private static final String KEY_COMPANY_PHONE_HOME = "CompanyPhoneHome";
private static final String KEY_COMPANY_PHONE_PRIMARY = "CompanyPhonePrimary";
private static final String KEY_COMPANY_ADDRESS1 = "CompanyAddress";
private static final String KEY_COMPANY_ADDRESS2 = "CompanyAddressSecondary";
private static final String KEY_COMPANY_CITY = "CompanyCity";
private static final String KEY_COMPANY_STATE = "CompanyState";
private static final String KEY_COMPANY_ZIP = "CompanyZip";
private static final String KEY_COMPANY_COUNTRY = "CompanyCountry";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Table Create Statements
// Todo table create statement
private static final String CREATE_TABLE_COMPANY = "CREATE TABLE "
+ COMPANY + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_COMPANY_ID + " INTEGER,"
+ KEY_COMPANY_REFERENCE_ID + " INTEGER,"
+ KEY_COMPANY_NAME + " VARCHAR,"
+ KEY_COMPANY_WEBSITE + "VARCHAR,"
+ KEY_COMPANY_EMAIL + "VARCHAR,"
+ KEY_COMPANY_PHONE_HOME + "VARCHAR,"
+ KEY_COMPANY_PHONE_PRIMARY + "VARCHAR,"
+ KEY_COMPANY_ADDRESS1 + "VARCHAR,"
+ KEY_COMPANY_ADDRESS2 + "VARCHAR,"
+ KEY_COMPANY_CITY + "VARCHAR,"
+ KEY_COMPANY_STATE + "VARCHAR,"
+ KEY_COMPANY_ZIP + "INTEGER,"
+ KEY_COMPANY_COUNTRY + "VARCHAR" + ")";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_COMPANY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + COMPANY);
}
}
Now I'll Create CompanyDB.class For a CURD Operation But How to i access DatabaseHelper.class In Company.class.
Thanks In Advance :)
The following is an example of splitting tables away from the DatabaseHelper :-
ContactDB.java
public class ContactDB {
public static final String TBNAME = "contact";
public static final String COL_ID = BaseColumns._ID;
public static final String COL_NAME = "contact_name";
public static final String COL_EMAIL = "contact_email";
public static String getTableCreatSQL() {
return "CREATE TABLE IF NOT EXISTS " + TBNAME + "(" +
COL_ID + " INTEGER PRIMARY KEY, " +
COL_NAME + " TEXT," +
COL_EMAIL + " TEXT" +
")";
}
public static long addContact(SQLiteDatabase db, String contact_name, String contact_email) {
ContentValues cv = new ContentValues();
cv.put(COL_NAME,contact_name);
cv.put(COL_EMAIL,contact_email);
return db.insert(TBNAME,null,cv);
}
public static Cursor getAllContacts(SQLiteDatabase db) {
return db.query(TBNAME,null,null,null,null,null,COL_NAME + " ASC," + COL_EMAIL + " ASC");
}
}
CompanyDB.java
public class CompanyDB {
public static final String TBNAME = "company";
public static final String COL_ID = BaseColumns._ID;
public static final String COL_NAME = "company_name";
public static String getTableCreateSQL() {
return "CREATE TABLE IF NOT EXISTS " + TBNAME + "(" +
COL_ID + " INTEGER PRIMARY KEY," +
COL_NAME + " TEXT" +
")";
}
public static long addCompany(SQLiteDatabase db, String company_name ) {
ContentValues cv = new ContentValues();
cv.put(COL_NAME,company_name);
return db.insert(TBNAME,null,cv);
}
public static Cursor getAllCompanies(SQLiteDatabase db) {
return db.query(TBNAME,null,null,null,null,null,COL_NAME + " ASC");
}
}
DBHelper.java (Database helper)
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydatabase";
public static final int DBVERSION = 1;
private static SQLiteDatabase mDB;
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CompanyDB.getTableCreateSQL());
db.execSQL(ContactDB.getTableCreatSQL());
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Cursor mAllContacts;
Cursor mAllCompanies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLiteDatabase mDB = new DBHelper(this).getWritableDatabase();
CompanyDB.addCompany(mDB,"mycompany");
ContactDB.addContact(mDB,"Fred","Fred#email.com");
ContactDB.addContact(mDB,"Bert","bertbloggins#bloggings.moc");
mAllCompanies = CompanyDB.getAllCompanies(mDB);
while (mAllCompanies.moveToNext()) {
Log.d("COMPANY",
"Company Name = " +
mAllCompanies.getString(
mAllCompanies.getColumnIndex(
CompanyDB.COL_NAME
)
)
);
}
Cursor mAllContacts = ContactDB.getAllContacts(mDB);
while (mAllContacts.moveToNext()) {
Log.d("CONTACT",
"Contact Name = " +
mAllContacts.getString(
mAllContacts.getColumnIndex(
ContactDB.COL_NAME
)
) +
" Email = " +
mAllContacts.getString(
mAllContacts.getColumnIndex(
ContactDB.COL_EMAIL
)
)
);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mAllCompanies.close();
mAllContacts.close();
}
}
This will add a company and 2 contacts (each time that it is run), retrieve the companies and contacts from the database and write the details to the log.
Output would be lime (first run) :-
04-02 09:09:42.556 1497-1497/so49607475_splittableclasses.so49607475_splittableclasses D/COMPANY: Company Name = mycompany
04-02 09:09:42.556 1497-1497/so49607475_splittableclasses.so49607475_splittableclasses D/CONTACT: Contact Name = Bert Email = bertbloggins#bloggings.moc
Contact Name = Fred Email = Fred#email.com
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 am trying to update the value of a particular column in my table. I already have a ContentProvder set up. I am receiving an error and I don't know how to fix it. I have searched for help on-line and none of them seem to update based on the unique-id. Here is my code..
#Override
public int update (Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int uriType = NewsContract.sURI_MATCHER.match(uri);
SQLiteDatabase db = dictionaryHelper.getWritableDatabase();
int rowsUpdated = 0;
String id = null;
switch (uriType)
{case DictionaryContract.RECENT:
rowsUpdated = db.update(DictionaryContract.DictionaryDataContract.RECENT_TABLE_NAME,
values,
selection,
selectionArgs);
break;
case DictionaryContract.RECENT_ID:
id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsUpdated = db.update(DictionaryContract.DictionaryDataContract.RECENT_TABLE_NAME,
values,
DictionaryContract.DictionaryDataContract._ID + "=" + id,
null);
} else {
rowsUpdated = db.update(DictionaryContract.DictionaryDataContract.RECENT_TABLE_NAME,
values,
DictionaryContract.DictionaryDataContract._ID + "=" + id
+ " and "
+ selection, selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI" + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
And this is how I am calling the update method of the ContentProvider:
private boolean UpdateRecentTable()
{
cursor.moveToLast();
Long id = cursor.getLong(cursor.getColumnIndex(DictionaryContract.DictionaryDataContract._ID));
Log.i("Update", " " + id);
String filter = DictionaryContract.DictionaryDataContract._ID + "=" + id;
ContentValues args = new ContentValues();
args.put(DictionaryContract.DictionaryDataContract.REC_FAVORITED, 1);
dResolver.update(DictionaryContract.CONTENT_URI_RECENT, args, filter, null);
return true;
}
Error:
03-21 04:05:36.823 18326-18673/com.example.clinton.light E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1 Process: com.example.clinton.light, PID: 18326
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.IllegalArgumentException: Unknown URIcontent://com.example.clinton.light.provider.dictionary/recents
at com.example.clinton.light.database.DictionaryContentProvider.update(DictionaryContentProvider.java:216)
at android.content.ContentProvider$Transport.update(ContentProvider.java:355)
at android.content.ContentResolver.update(ContentResolver.java:1362)
at com.example.clinton.light.dictionary_main.StoreFavWord.UpdateRecentTable(StoreFavWord.java:72)
at com.example.clinton.light.dictionary_main.StoreFavWord.doInBackground(StoreFavWord.java:41)
at com.example.clinton.light.dictionary_main.StoreFavWord.doInBackground(StoreFavWord.java:18)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
03-21 04:05:37.271 18326-18352/com.example.clinton.light E/Surface: getSlotFromBufferLocked: unknown buffer: 0xe0c79230
DataContract
ublic class DictionaryContract {
public DictionaryContract(){}
public static final int TODAY = 100;
public static final int TODAY_ID = 115;
public static final int FAVORITE = 120;
public static final int FAVORITE_ID = 125;
public static final int RECENT = 130;
public static final int RECENT_ID = 135;
private static final String AUTHORITY = "com.example.clinton.light.provider.dictionary";
public static final String TODAY_BASE_PATH = "today";
public static final String FAVORITE_BASE_PATH = "favorites";
public static final String RECENT_BASE_PATH = "recents";
public static final UriMatcher sURI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
static {
sURI_MATCHER.addURI(AUTHORITY, TODAY_BASE_PATH, TODAY);
sURI_MATCHER.addURI(AUTHORITY, TODAY_BASE_PATH + "/#", TODAY_ID);
sURI_MATCHER.addURI(AUTHORITY, FAVORITE_BASE_PATH, FAVORITE);
sURI_MATCHER.addURI(AUTHORITY, FAVORITE_BASE_PATH + "/#", FAVORITE_ID);
sURI_MATCHER.addURI(AUTHORITY, RECENT_BASE_PATH, RECENT);
sURI_MATCHER.addURI(AUTHORITY, RECENT_BASE_PATH + "/#", RECENT_ID);
}
public static final Uri CONTENT_URI_TODAY = Uri.parse("content://" + AUTHORITY + "/" + TODAY_BASE_PATH);
public static final Uri CONTENT_URI_FAVORITES = Uri.parse("content://" + AUTHORITY + "/" + FAVORITE_BASE_PATH);
public static final Uri CONTENT_URI_RECENT = Uri.parse("content://" + AUTHORITY + "/" + RECENT_BASE_PATH);
public static abstract class DictionaryDataContract implements BaseColumns
{
public static final String TODAY_TABLE_NAME = "todaytable";
public static final String TODAY_DATE = "worddate";
public static final String WORD = "wordname";
public static final String DEFINITION = "worddefinition";
public static final String SPEECH = "wordspeech";
public static final String ROOT = "wordroot";
public static final String EXAMPLE = "wordexample";
private static final String CREATE_TODAY_TABLE = "create table "+
TODAY_TABLE_NAME +
"(" +
_ID +
" integer primary key autoincrement, " +
TODAY_DATE +
" text not null, " +
WORD +
" text not null, " +
DEFINITION +
" text not null, " +
EXAMPLE +
" text not null, " +
SPEECH +
" text not null, " +
ROOT +
" text not null);";
public static final String FAVORITE_TABLE_NAME = "favoritetable";
public static final String FAV_WORD = "wordname";
public static final String FAV_DEFINITION = "worddefinition";
public static final String FAV_DEFINITION2 = "worddefinition2";
public static final String FAV_SPEECH = "wordspeech";
public static final String FAV_SPEECH2 = "wordspeech2";
public static final String FAV_RELATED = "wordrelated";
public static final String FAV_EXAMPLE = "wordexample";
public static final String RECENT_TABLE_NAME = "recentetable";
public static final String REC_WORD = "wordname";
public static final String REC_DEFINITION = "worddefinition";
public static final String REC_DEFINITION2 = "worddefinition2";
public static final String REC_SPEECH = "wordspeech";
public static final String REC_SPEECH2 = "wordspeech2";
public static final String REC_RELATED = "wordrelated";
public static final String REC_EXAMPLE = "wordexample";
public static final String REC_FAVORITED = "favorited";
private static final String CREATE_FAVORITE_TABLE = "create table "+
FAVORITE_TABLE_NAME +
"(" +
_ID +
" integer primary key autoincrement, " +
FAV_WORD +
" text not null, " +
FAV_DEFINITION +
" text not null, " +
FAV_DEFINITION2 +
" text not null, " +
FAV_EXAMPLE +
" text not null, " +
FAV_SPEECH +
" text not null, " +
FAV_SPEECH2 +
" text not null, " +
FAV_RELATED +
" text not null);";
private static final String CREATE_RECENT_TABLE = "create table "+
RECENT_TABLE_NAME +
"(" +
_ID +
" integer primary key autoincrement, " +
REC_WORD +
" text not null, " +
REC_DEFINITION +
" text not null, " +
REC_DEFINITION2 +
" text not null, " +
REC_EXAMPLE +
" text not null, " +
REC_SPEECH +
" text not null, " +
REC_SPEECH2 +
" text not null, " +
REC_FAVORITED +
" int not null, " +
REC_RELATED +
" text not null);";
public static void onCreate (SQLiteDatabase db) {
db.execSQL(CREATE_TODAY_TABLE);
db.execSQL(CREATE_FAVORITE_TABLE);
db.execSQL(CREATE_RECENT_TABLE);
}
public static void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TODAY_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + FAVORITE_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + RECENT_TABLE_NAME);
onCreate(db);
}
}
}